diff --git a/.github/workflows/stale-issues-safe.yml b/.github/workflows/stale-issues-safe.yml index 844b19c7a3f..1682b92a7a7 100644 --- a/.github/workflows/stale-issues-safe.yml +++ b/.github/workflows/stale-issues-safe.yml @@ -16,7 +16,7 @@ jobs: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-message: 'This issue is stale because it has been open 1 year with no activity. If this is a bug, please comment to confirm it is still present on latest stable version. if this is a feature request, please comment to notify the request is still relevant and not yet covered by latest stable version. This issue may be closed automatically by stale bot in 10 days (you should still be able to re-open it if required).' stale-label: 'Issue Stale (automatic label)' - exempt-labels: 'Priority High / Blocking,Priority Top Strategic,Priority Medium,Hacktoberfest,good first issue,Bug Security (CVE),Analysis of PR in progres' + exempt-labels: 'Priority High / Blocking,Priority Top Strategic,Priority Medium,hacktoberfest,hacktoberfest-accepted,good first issue,Bug Security (CVE),Analysis of PR in progress' days-before-stale: 365 days-before-close: 10 operations-per-run: 100 diff --git a/.gitignore b/.gitignore index 344822f0e9e..b49fdf8dc86 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,16 @@ htdocs/includes/sebastian/ htdocs/includes/squizlabs/ htdocs/includes/webmozart/ htdocs/.well-known/apple-developer-merchantid-domain-association + +# Node Modules +build/yarn-error.log +build/node_modules/ +node_modules/ + +#yarn +yarn.lock + +#package-lock +package-lock.json + +doc/install.lock diff --git a/.travis.yml b/.travis.yml index c47e1b19598..16d3403f554 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,8 @@ os: linux dist: xenial #dist: bionic -sudo: required +# Deprecated: The key sudo has no effect anymore. +#sudo: required language: php diff --git a/.tx/config b/.tx/config index 696ff858394..b98bf7828f2 100644 --- a/.tx/config +++ b/.tx/config @@ -164,6 +164,12 @@ source_file = htdocs/langs/en_US/hrm.lang source_lang = en_US type = MOZILLAPROPERTIES +[dolibarr.intracommreport] +file_filter = htdocs/langs//intracommreport.lang +source_file = htdocs/langs/en_US/intracommreport.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.install] file_filter = htdocs/langs//install.lang source_file = htdocs/langs/en_US/install.lang diff --git a/ChangeLog b/ChangeLog index ca5834f63f2..27d9129c762 100644 --- a/ChangeLog +++ b/ChangeLog @@ -12,7 +12,8 @@ NEW: Module Reception (for a more accurate management of your receptions) moved WARNING: Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: -* Properties ->contactid has been renamed into ->contact_id +* Properties ->contactid have been renamed into ->contact_id +* Properties ->titre have been renamed into ->title * Property $paiementid in API 'api_supplier_invoices.php' has been renamed into into $payment_mode_id (english) * The deprecated subsitution key __SIGNATURE__ has been removed. Replace with __USER_SIGNATURE__ if you used the old syntax in your email templates. @@ -24,6 +25,9 @@ Following changes may create regressions for some external modules, but were nec * The GETPOST(..., 'alpha') has now the same behaviour than GETPOST(..., 'alphanohtml') so no html will be allowed. Use GETPOST(..., 'restricthtml') to accept HTML. * If you have links in your code with '&action=delete' as a parameter, you must also add '&token='.newToken() as another parameter to avoid CSRF protection errors. * The API addPayment for api_invoice has evolved to accept amount into a foreign currency. You must provide array(amount=>X,mutlicurrency_ammount=>Y) instead of amount. +* The method select_thirdparty(), deprecated since 3.8, into html.form.class.php has been removed. +* Depreciate all methods with name valide(). Use instead methods validate(). + ***** ChangeLog for 12.0.3 compared to 12.0.2 ***** FIX: 10.0 - when the mime file name is different from the filesystem name, the attachment name should be the mime filename diff --git a/README.md b/README.md index 648d5ef003d..919fc62ae5b 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ ![Downloads per day](https://img.shields.io/sourceforge/dw/dolibarr.svg) ![Build status](https://img.shields.io/travis/Dolibarr/dolibarr/develop.svg) +[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%205.6-8892BF.svg?style=flat-square)](https://php.net/) +[![GitHub release](https://img.shields.io/github/v/release/Dolibarr/dolibarr)](https://github.com/Dolibarr/dolibarr) Dolibarr ERP & CRM is a modern software package that helps manage your organization's activity (contacts, suppliers, invoices, orders, stocks, agenda…). diff --git a/build/docker/docker-compose.yml b/build/docker/docker-compose.yml index efdc95d2858..7e4ceda902e 100644 --- a/build/docker/docker-compose.yml +++ b/build/docker/docker-compose.yml @@ -12,8 +12,11 @@ services: environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: dolibarr + ports: + - "3306:3306" networks: - internal-pod + - external-pod phpmyadmin: image: phpmyadmin/phpmyadmin diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index 24b32dcff91..85212d9c5ba 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -620,6 +620,9 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/fonts/utils`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/tools`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/LICENSE.TXT`; + + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/autoload.php`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/theme/common/octicons/LICENSE`; } diff --git a/build/perl/virtualmin/dolibarr.pl b/build/perl/virtualmin/dolibarr.pl index 343cebc6abe..8b6a9888db0 100644 --- a/build/perl/virtualmin/dolibarr.pl +++ b/build/perl/virtualmin/dolibarr.pl @@ -1,7 +1,7 @@ #---------------------------------------------------------------------------- # \file dolibarr.pl # \brief Dolibarr script install for Virtualmin Pro -# \author (c)2009-2019 Regis Houssin +# \author (c)2009-2020 Regis Houssin #---------------------------------------------------------------------------- @@ -30,7 +30,7 @@ return "Regis Houssin"; # script_dolibarr_versions() sub script_dolibarr_versions { -return ( "10.0.0", "9.0.3", "8.0.5", "7.0.5", "6.0.8" ); +return ( "12.0.3", "11.0.5", "10.0.7", "9.0.4", "8.0.6", "7.0.5" ); } sub script_dolibarr_release @@ -77,6 +77,16 @@ if ($ver >= 3.6) { push(@rv, "Dolibarr requires PHP version 5.3 or later"); } } +if ($ver >= 12.0) { + # Check for PHP 5.6+ + local $phpv = &get_php_version($phpver || 5, $d); + if (!$phpv) { + push(@rv, "Could not work out exact PHP version"); + } + elsif ($phpv < 5.6) { + push(@rv, "Dolibarr requires PHP version 5.6 or later"); + } + } return @rv; } @@ -376,7 +386,7 @@ sub script_dolibarr_realversion local ($d, $opts, $sinfo) = @_; local $lref = &read_file_lines("$opts->{'dir'}/filefunc.inc.php", 1); foreach my $l (@$lref) { - if ($l =~ /'DOL_VERSION','([0-9a-z\.\-]+)'/) { + if ($l =~ /'DOL_VERSION',\s?'([0-9a-z\.\-]+)'/) { return $1; } } @@ -390,6 +400,8 @@ sub script_dolibarr_check_latest { local ($ver) = @_; local @vers = &osdn_package_versions("dolibarr", + $ver >= 12.0 ? "dolibarr\\-(12\\.0\\.[0-9\\.]+)\\.tgz" : + $ver >= 11.0 ? "dolibarr\\-(11\\.0\\.[0-9\\.]+)\\.tgz" : $ver >= 10.0 ? "dolibarr\\-(10\\.0\\.[0-9\\.]+)\\.tgz" : $ver >= 9.0 ? "dolibarr\\-(9\\.0\\.[0-9\\.]+)\\.tgz" : $ver >= 8.0 ? "dolibarr\\-(8\\.0\\.[0-9\\.]+)\\.tgz" : @@ -410,7 +422,7 @@ return $ver eq $vers[0] ? undef : $vers[0]; sub script_dolibarr_site { -return 'http://www.dolibarr.org/'; +return 'https://www.dolibarr.org/'; } sub script_dolibarr_passmode diff --git a/build/rpm/dolibarr_fedora.spec b/build/rpm/dolibarr_fedora.spec index 115edcef397..039dafd198f 100755 --- a/build/rpm/dolibarr_fedora.spec +++ b/build/rpm/dolibarr_fedora.spec @@ -196,6 +196,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/imports %_datadir/dolibarr/htdocs/includes %_datadir/dolibarr/htdocs/install +%_datadir/dolibarr/htdocs/intracommreport %_datadir/dolibarr/htdocs/langs/HOWTO-Translation.txt %_datadir/dolibarr/htdocs/livraison %_datadir/dolibarr/htdocs/loan diff --git a/build/rpm/dolibarr_generic.spec b/build/rpm/dolibarr_generic.spec index 64293ff6580..098a041680a 100755 --- a/build/rpm/dolibarr_generic.spec +++ b/build/rpm/dolibarr_generic.spec @@ -276,6 +276,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/imports %_datadir/dolibarr/htdocs/includes %_datadir/dolibarr/htdocs/install +%_datadir/dolibarr/htdocs/intracommreport %_datadir/dolibarr/htdocs/langs/HOWTO-Translation.txt %_datadir/dolibarr/htdocs/livraison %_datadir/dolibarr/htdocs/loan diff --git a/build/rpm/dolibarr_mandriva.spec b/build/rpm/dolibarr_mandriva.spec index 28b58a4da96..a3f2d1d8d96 100755 --- a/build/rpm/dolibarr_mandriva.spec +++ b/build/rpm/dolibarr_mandriva.spec @@ -193,6 +193,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/imports %_datadir/dolibarr/htdocs/includes %_datadir/dolibarr/htdocs/install +%_datadir/dolibarr/htdocs/intracommreport %_datadir/dolibarr/htdocs/langs/HOWTO-Translation.txt %_datadir/dolibarr/htdocs/livraison %_datadir/dolibarr/htdocs/loan diff --git a/build/rpm/dolibarr_opensuse.spec b/build/rpm/dolibarr_opensuse.spec index 8b4ccf37808..5b1b86b28f4 100755 --- a/build/rpm/dolibarr_opensuse.spec +++ b/build/rpm/dolibarr_opensuse.spec @@ -204,6 +204,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/imports %_datadir/dolibarr/htdocs/includes %_datadir/dolibarr/htdocs/install +%_datadir/dolibarr/htdocs/intracommreport %_datadir/dolibarr/htdocs/langs/HOWTO-Translation.txt %_datadir/dolibarr/htdocs/livraison %_datadir/dolibarr/htdocs/loan diff --git a/dev/resources/iso-normes/Intracommreport-ManuelDebXml.pdf b/dev/resources/iso-normes/Intracommreport-ManuelDebXml.pdf new file mode 100644 index 00000000000..fef9f48f53e Binary files /dev/null and b/dev/resources/iso-normes/Intracommreport-ManuelDebXml.pdf differ diff --git a/dev/resources/iso-normes/Intracommreport-ManuelDesXML.pdf b/dev/resources/iso-normes/Intracommreport-ManuelDesXML.pdf new file mode 100644 index 00000000000..b1074b3b8a3 Binary files /dev/null and b/dev/resources/iso-normes/Intracommreport-ManuelDesXML.pdf differ diff --git a/dev/tools/dolibarr-postgres2mysql.php b/dev/tools/dolibarr-postgres2mysql.php index c17a73dfe12..fd30540c019 100644 --- a/dev/tools/dolibarr-postgres2mysql.php +++ b/dev/tools/dolibarr-postgres2mysql.php @@ -357,8 +357,8 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true) $line = str_replace(" time with time zone", " time", $line); $line = str_replace(" time without time zone", " time", $line); - $line = str_replace(" timestamp DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP", $line); - $line = str_replace(" timestamp without time zone DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP", $line); + $line = str_replace(" timestamp DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", $line); + $line = str_replace(" timestamp without time zone DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", $line); if (strstr($line, "auto_increment") || preg_match('/ rowid int/', $line) || preg_match('/ id int/', $line)) { $field = getfieldname($line); diff --git a/doc/images/invoice.png b/doc/images/invoice.png new file mode 100644 index 00000000000..9be03a52ed8 Binary files /dev/null and b/doc/images/invoice.png differ diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 0ac79bcc3aa..88282447c51 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -294,13 +294,11 @@ if ($resql) print ''; print ''; print ''; - print ''; print ''; $newcardbutton .= dolGetButtonTitle($langs->trans("New"), $langs->trans("Addanaccount"), 'fa fa-plus-circle', './card.php?action=create'); - - print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); + print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); // Box to select active chart of account print $langs->trans("Selectchartofaccounts")." : "; @@ -343,15 +341,15 @@ if ($resql) // Line for search fields print ''; - if (!empty($arrayfields['aa.account_number']['checked'])) print ''; - if (!empty($arrayfields['aa.label']['checked'])) print ''; - if (!empty($arrayfields['aa.labelshort']['checked'])) print ''; + if (!empty($arrayfields['aa.account_number']['checked'])) print ''; + if (!empty($arrayfields['aa.label']['checked'])) print ''; + if (!empty($arrayfields['aa.labelshort']['checked'])) print ''; if (!empty($arrayfields['aa.account_parent']['checked'])) { print ''; print $formaccounting->select_account($search_accountparent, 'search_accountparent', 2); print ''; } - if (!empty($arrayfields['aa.pcg_type']['checked'])) print ''; + if (!empty($arrayfields['aa.pcg_type']['checked'])) print ''; if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['aa.reconcilable']['checked'])) print ' '; } if (!empty($arrayfields['aa.active']['checked'])) print ' '; print ''; @@ -416,18 +414,24 @@ if ($resql) // Account parent if (!empty($arrayfields['aa.account_parent']['checked'])) { - if (!empty($obj->account_parent)) + // Note: obj->account_parent is a foreign key to a rowid. It is field in child table and obj->rowid2 is same, but in parent table. + // So for orphans, obj->account_parent is set but not obj->rowid2 + if (!empty($obj->account_parent) && !empty($obj->rowid2)) { + print ""; + print ''; $accountparent->id = $obj->rowid2; $accountparent->label = $obj->label2; - $accountparent->account_number = $obj->account_number2; - - print ""; + $accountparent->account_number = $obj->account_number2; // Sotre an account number for output print $accountparent->getNomUrl(1); print "\n"; if (!$i) $totalarray['nbfield']++; } else { - print ' '; + print ''; + if (!empty($obj->account_parent)) { + print ''; + } + print ''; if (!$i) $totalarray['nbfield']++; } } @@ -481,11 +485,11 @@ if ($resql) // Action print ''; if ($user->rights->accounting->chartofaccount) { - print ''; + print ''; print img_edit(); print ''; print ' '; - print ''; + print ''; print img_delete(); print ''; } diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index d605105f8e9..f68fbc18905 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -172,7 +172,7 @@ if ($action == 'display' || $action == 'delete') { print ''; print ''; print $langs->trans("DeleteFromCat"); - print img_picto($langs->trans("DeleteFromCat"), 'unlink'); + print img_picto($langs->trans("DeleteFromCat"), 'unlink', 'class="paddingleft"'); print ""; print ""; print "\n"; diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 3d03dc9c4b6..b9377ce4431 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -47,9 +47,9 @@ $action = GETPOST('action', 'aZ09'); $list_account_main = array( - 'ACCOUNTING_ACCOUNT_CUSTOMER', - 'ACCOUNTING_ACCOUNT_SUPPLIER', - 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', + 'ACCOUNTING_ACCOUNT_CUSTOMER', + 'ACCOUNTING_ACCOUNT_SUPPLIER', + 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', ); $list_account = array(); @@ -120,9 +120,9 @@ if ($action == 'update') { $constvalue = GETPOST($constname, 'alpha'); - if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error++; - } + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } } if (!$error) { @@ -159,20 +159,20 @@ print ''; print ''; foreach ($list_account_main as $key) { - print ''; - // Param - $label = $langs->trans($key); - $keydesc = $key.'_Desc'; + print ''; + // Param + $label = $langs->trans($key); + $keydesc = $key.'_Desc'; - $htmltext = $langs->trans($keydesc); - print ''; - // Value - print ''; - print ''; + $htmltext = $langs->trans($keydesc); + print ''; + // Value + print ''; + print ''; } diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index a122d3acab5..a4227a761a4 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -300,16 +300,16 @@ if ($action == 'create') if (!empty($user->rights->accounting->fiscalyear->write)) { - /* + /* * Barre d'actions */ - print '
'; + print ''; + print '
'; } } } else { diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index e48ee43ef8d..819160e7d23 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -22,7 +22,7 @@ * \brief Setup page to configure journals */ -if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; diff --git a/htdocs/accountancy/admin/subaccount.php b/htdocs/accountancy/admin/subaccount.php index 67175261f02..4b44bd35149 100644 --- a/htdocs/accountancy/admin/subaccount.php +++ b/htdocs/accountancy/admin/subaccount.php @@ -20,7 +20,7 @@ /** * \file htdocs/accountancy/admin/subaccount.php * \ingroup Accountancy (Double entries) - * \brief List accounting sub-account + * \brief List of accounting sub-account (auxiliary accounts) */ require '../../main.inc.php'; @@ -59,10 +59,10 @@ if (!$sortfield) $sortfield = "label"; if (!$sortorder) $sortorder = "ASC"; $arrayfields = array( - 'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), - 'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), - 'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1) + 'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), + 'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1) ); if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['reconcilable']); @@ -80,17 +80,17 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (!empty($cancel)) $action = ''; + if (!empty($cancel)) $action = ''; - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers - { - $search_subaccount = ""; - $search_label = ""; - $search_type = ""; + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers + { + $search_subaccount = ""; + $search_label = ""; + $search_type = ""; $search_array_options = array(); - } + } } @@ -100,13 +100,15 @@ if (empty($reshook)) $form = new Form($db); -llxHeader('', $langs->trans("ReportThirdParty")); +$title = $langs->trans('ChartOfIndividualAccountsOfSubsidiaryLedger'); + +llxHeader('', $title); // Customer $sql = "SELECT sa.rowid, sa.nom as label, sa.code_compta as subaccount, '0' as type, sa.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."societe sa"; -$sql .= ' WHERE sa.entity IN ('.getEntity('societe').')'; -$sql .= ' AND sa.code_compta <> ""'; +$sql .= " WHERE sa.entity IN (".getEntity('societe').")"; +$sql .= " AND sa.code_compta <> ''"; //print $sql; if (strlen(trim($search_subaccount))) { $lengthpaddingaccount = 0; @@ -142,13 +144,13 @@ if (strlen(trim($search_subaccount))) { } } if (strlen(trim($search_label))) $sql .= natural_search("sa.nom", $search_label); -if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$search_type."'"; +if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db->escape($search_type)."'"; // Supplier $sql .= " UNION "; $sql .= " SELECT sa.rowid, sa.nom as label, sa.code_compta_fournisseur as subaccount, '1' as type, sa.entity FROM ".MAIN_DB_PREFIX."societe sa"; -$sql .= ' WHERE sa.entity IN ('.getEntity('societe').')'; -$sql .= ' AND sa.code_compta_fournisseur <> ""'; +$sql .= " WHERE sa.entity IN (".getEntity('societe').")"; +$sql .= " AND sa.code_compta_fournisseur <> ''"; //print $sql; if (strlen(trim($search_subaccount))) { $lengthpaddingaccount = 0; @@ -184,13 +186,13 @@ if (strlen(trim($search_subaccount))) { } } if (strlen(trim($search_label))) $sql .= natural_search("sa.nom", $search_label); -if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$search_type."'"; +if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db->escape($search_type)."'"; // User $sql .= " UNION "; $sql .= " SELECT u.rowid, u.lastname as label, u.accountancy_code as subaccount, '2' as type, u.entity FROM ".MAIN_DB_PREFIX."user u"; -$sql .= ' WHERE u.entity IN ('.getEntity('user').')'; -$sql .= ' AND u.accountancy_code <> ""'; +$sql .= " WHERE u.entity IN (".getEntity('user').")"; +$sql .= " AND u.accountancy_code <> ''"; //print $sql; if (strlen(trim($search_subaccount))) { $lengthpaddingaccount = 0; @@ -226,7 +228,7 @@ if (strlen(trim($search_subaccount))) { } } if (strlen(trim($search_label))) $sql .= natural_search("u.lastname", $search_label); -if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$search_type."'"; +if (!empty($search_type) && $search_type >= 0) $sql .= " HAVING type LIKE '".$db->escape($search_type)."'"; $sql .= $db->order($sortfield, $sortorder); @@ -268,18 +270,18 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans('ReportThirdParty'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit, 0, 0, 1); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit, 0, 0, 1); print '
'.$langs->trans("WarningCreateSubAccounts").'
'; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $moreforfilter = ''; - $massactionbutton = ''; + $moreforfilter = ''; + $massactionbutton = ''; - print '
'; - print '
'.$langs->trans("ThirdParties").' | '.$langs->trans("Users").'
'; - print $form->textwithpicto($label, $htmltext); - print ''; // Do not force class=right, or it align also the content of the select box - print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); - print '
'; + print $form->textwithpicto($label, $htmltext); + print ''; // Do not force class=right, or it align also the content of the select box + print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); + print '
'."\n"; + print '
'; + print '
'."\n"; // Line for search fields print ''; @@ -293,7 +295,7 @@ if ($resql) print ''; print ''; - print ''; + print ''; if (!empty($arrayfields['subaccount']['checked'])) print_liste_field_titre($arrayfields['subaccount']['label'], $_SERVER["PHP_SELF"], "subaccount", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['label']['checked'])) print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], "label", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'center '); @@ -335,17 +337,17 @@ if ($resql) // Customer if ($obj->type == 0) { - $s .= ''.$langs->trans("Customer").''; + $s .= ''.$langs->trans("Customer").''; } // Supplier elseif ($obj->type == 1) { - $s .= ''.$langs->trans("Supplier").''; + $s .= ''.$langs->trans("Supplier").''; } // User elseif ($obj->type == 2) { - $s .= ''.$langs->trans("Employee").''; + $s .= ''.$langs->trans("Employee").''; } print $s; print ''; diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 3608622916d..c3e225e5399 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -339,7 +339,7 @@ if ($action != 'export_csv') print ''; print ''; print ''; - print ''; + print ''; print ''; print "\n"; diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index ef105b6709a..8ca880de25f 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -328,7 +328,7 @@ llxHeader('', $langs->trans("CreateMvts")); // Confirmation to delete the command if ($action == 'delete') { - $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&mode='.$mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1); + $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&mode='.$mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'confirm_delete', '', 0, 1); print $formconfirm; } diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 813dbd4a37f..d89d0dca60c 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -108,7 +108,7 @@ $hookmanager->initHooks(array('bookkeepinglist')); $formaccounting = new FormAccounting($db); $form = new Form($db); -if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !isset($_POST['begin']) && !isset($_GET['begin']) && !isset($_POST['formfilteraction']) && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) +if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GETPOSTISSET('begin') && !isset($_POST['formfilteraction']) && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) { if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('restore_lastsearch_values')) { @@ -529,7 +529,7 @@ if ($action == 'export_file' && $user->rights->accounting->mouvements->export) { $formother = new FormOther($db); $formfile = new FormFile($db); -$title_page = $langs->trans("Bookkeeping"); +$title_page = $langs->trans("Operations").' - '.$langs->trans("Journals"); // Count total nb of records $nbtotalofrecords = ''; @@ -608,22 +608,21 @@ if ($action == 'delbookkeepingyear') { 'default' => $deljournal ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); print $formconfirm; } //$param=''; param started before -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); print ''; print ''; print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') print ''; print ''; -print ''; -print ''; -print ''; +print ''; +print ''; if (count($filter)) $buttonLabel = $langs->trans("ExportFilteredList"); else $buttonLabel = $langs->trans("ExportList"); @@ -638,13 +637,14 @@ $newcardbutton .= ''.$langs->trans("I $newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export); -$newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param, '', 1, array('morecss'=>'marginleftonly btnTitleSelected')); +$newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss'=>'marginleftonly')); $url = './card.php?action=create'; if (!empty($socid)) $url .= '&socid='.$socid; $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', $url, '', $user->rights->accounting->mouvements->creer); -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -670,12 +670,10 @@ if (!empty($arrayfields['t.doc_date']['checked'])) { print ''; } @@ -703,25 +701,25 @@ if (!empty($arrayfields['t.subledger_account']['checked'])) { print ''; @@ -771,12 +769,10 @@ if (!empty($arrayfields['t.date_creation']['checked'])) { print ''; } @@ -785,12 +781,10 @@ if (!empty($arrayfields['t.tms']['checked'])) { print ''; } @@ -799,12 +793,10 @@ if (!empty($arrayfields['t.date_export']['checked'])) { print ''; } @@ -1049,10 +1041,10 @@ while ($i < min($num, $limit)) print ''; diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index e0e16e00d12..4ed055be0b1 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -33,7 +33,6 @@ require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Load translation files required by the page @@ -55,6 +54,7 @@ if ($search_accountancy_code_end == - 1) { } $search_doc_ref = GETPOST('search_doc_ref', 'alpha'); $search_label_operation = GETPOST('search_label_operation', 'alpha'); +$search_mvt_num = GETPOST('search_mvt_num', 'int'); $search_direction = GETPOST('search_direction', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); $search_debit = GETPOST('search_debit', 'alpha'); @@ -86,7 +86,7 @@ $hookmanager->initHooks(array('bookkeepingbyaccountlist')); $formaccounting = new FormAccounting($db); $form = new Form($db); -if (empty($search_date_start) && empty($search_date_end) && GETPOSTISSET('search_date_startday') && GETPOSTISSET('search_date_startmonth') && GETPOSTISSET('search_date_starthour')) { +if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('search_date_startday') && !GETPOSTISSET('search_date_startmonth') && !GETPOSTISSET('search_date_starthour')) { $sql = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear "; $sql .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."'"; $sql .= $db->plimit(1); @@ -149,6 +149,7 @@ if (empty($reshook)) $search_label_account = ''; $search_doc_ref = ''; $search_label_operation = ''; + $search_mvt_num = ''; $search_direction = ''; $search_ledger_code = ''; $search_date_start = ''; @@ -193,6 +194,10 @@ if (empty($reshook)) $filter['t.label_compte'] = $search_label_account; $param .= '&search_label_compte=' . urlencode($search_label_account); } + if (!empty($search_mvt_num)) { + $filter['t.piece_num'] = $search_mvt_num; + $param .= '&search_mvt_num=' . urlencode($search_mvt_num); + } if (!empty($search_doc_ref)) { $filter['t.doc_ref'] = $search_doc_ref; $param .= '&search_doc_ref=' . urlencode($search_doc_ref); @@ -294,7 +299,7 @@ $formfile = new FormFile($db); $formother = new FormOther($db); $form = new Form($db); -$title_page = $langs->trans("Bookkeeping").' '.strtolower($langs->trans("By")).' '.strtolower($langs->trans("AccountAccounting")); +$title_page = $langs->trans("Operations").' - '.$langs->trans("VueByAccountAccounting").' ('.$langs->trans("Bookkeeping").')'; llxHeader('', $title_page); @@ -358,7 +363,7 @@ if ($action == 'delbookkeepingyear') { 'default' => $deljournal ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?'.$param, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'delbookkeepingyearconfirm', $form_question, '', 1, 300); print $formconfirm; } @@ -370,16 +375,19 @@ if ($optioncss != '') print ''; print ''; print ''; -print ''; -$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); +$newcardbutton .= dolGetButtonTitle($langs->trans('VueByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss'=>'marginleftonly btnTitleSelected')); + +$newcardbutton .= '   '; + $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', './card.php?action=create'); if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $viewflat.$newcardbutton, '', $limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $viewflat.$newcardbutton, '', $limit, 0, 0, 1); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -394,10 +402,10 @@ $moreforfilter = ''; // Accountancy account $moreforfilter .= '
'; $moreforfilter .= $langs->trans('AccountAccounting').': '; -$moreforfilter .= '
'; +$moreforfilter .= '
'; $moreforfilter .= $langs->trans('From').' '; $moreforfilter .= $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array(), 1, 1, 'maxwidth200'); -$moreforfilter .= $langs->trans('to').' '; +$moreforfilter .= ' '.$langs->trans('to').' '; $moreforfilter .= $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, 'maxwidth200'); $moreforfilter .= '
'; $moreforfilter .= '
'; @@ -425,12 +433,10 @@ if (!empty($arrayfields['t.code_journal']['checked'])) { if (!empty($arrayfields['t.doc_date']['checked'])) { print '
'; } @@ -697,10 +703,10 @@ while ($i < min($num, $limit)) print ''; diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 24f14d2ebd2..199899f89d5 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -448,7 +448,7 @@ class AccountingAccount extends CommonObject * @param int $notooltip 1=Disable tooltip * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @param int $withcompletelabel 0=Short label (field short label), 1=Complete label (field label) - * @param string $option 'bookkeeping', 'bookkeepinglistbyaccount', 'accountcard' + * @param string $option 'ledger', 'journals', 'accountcard' * @return string String with URL */ public function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1, $withcompletelabel = 0, $option = '') @@ -460,12 +460,12 @@ class AccountingAccount extends CommonObject $result = ''; - if (empty($option) || $option == 'bookkeeping') { - $url = DOL_URL_ROOT . '/accountancy/bookkeeping/list.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; - $labelurl = $langs->trans("ShowAccountingAccountInBookKeeping"); - } elseif ($option == 'bookkeepinglistbyaccount') { + if (empty($option) || $option == 'ledger') { $url = DOL_URL_ROOT . '/accountancy/bookkeeping/listbyaccount.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; - $labelurl = $langs->trans("ShowAccountingAccountInBookKeepingByAccount"); + $labelurl = $langs->trans("ShowAccountingAccountInLedger"); + } elseif ($option == 'journals') { + $url = DOL_URL_ROOT . '/accountancy/bookkeeping/list.php?search_accountancy_code_start=' . $this->account_number . '&search_accountancy_code_end=' . $this->account_number; + $labelurl = $langs->trans("ShowAccountingAccountInJournals"); } elseif ($option == 'accountcard') { $url = DOL_URL_ROOT . '/accountancy/admin/card.php?id=' . $this->id; $labelurl = $langs->trans("ShowAccountingAccount"); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 790aba68203..f5f4bf80221 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -57,80 +57,80 @@ class BookKeeping extends CommonObject */ public $id; - /** - * @var string Date of source document, in db date NOT NULL - */ + /** + * @var string Date of source document, in db date NOT NULL + */ public $doc_date; - /** - * @var int Deadline for payment - */ + /** + * @var int Deadline for payment + */ public $date_lim_reglement; - /** - * @var string doc_type - */ - public $doc_type; + /** + * @var string doc_type + */ + public $doc_type; - /** - * @var string doc_ref - */ + /** + * @var string doc_ref + */ public $doc_ref; /** - * @var int ID - */ + * @var int ID + */ public $fk_doc; /** - * @var int ID - */ + * @var int ID + */ public $fk_docdet; - /** - * @var string thirdparty code - */ - public $thirdparty_code; + /** + * @var string thirdparty code + */ + public $thirdparty_code; - /** - * @var string subledger account - */ + /** + * @var string subledger account + */ public $subledger_account; - /** - * @var string subledger label - */ + /** + * @var string subledger label + */ public $subledger_label; - /** - * @var string doc_type - */ + /** + * @var string doc_type + */ public $numero_compte; - /** - * @var string label compte - */ - public $label_compte; + /** + * @var string label compte + */ + public $label_compte; - /** - * @var string label operation - */ - public $label_operation; + /** + * @var string label operation + */ + public $label_operation; - /** - * @var float FEC:Debit - */ + /** + * @var float FEC:Debit + */ public $debit; - /** - * @var float FEC:Credit - */ + /** + * @var float FEC:Credit + */ public $credit; - /** - * @var float FEC:Amount (Not necessary) - * @deprecated Use $amount - */ + /** + * @var float FEC:Amount (Not necessary) + * @deprecated Use $amount + */ public $montant; /** @@ -138,34 +138,34 @@ class BookKeeping extends CommonObject */ public $amount; - /** - * @var string FEC:Sens (Not necessary) - */ + /** + * @var string FEC:Sens (Not necessary) + */ public $sens; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; - /** - * @var string key for import - */ + /** + * @var string key for import + */ public $import_key; - /** - * @var string code journal - */ + /** + * @var string code journal + */ public $code_journal; - /** - * @var string label journal - */ + /** + * @var string label journal + */ public $journal_label; - /** - * @var int accounting transaction id - */ + /** + * @var int accounting transaction id + */ public $piece_num; /** @@ -179,8 +179,8 @@ class BookKeeping extends CommonObject * * @param DoliDb $db Database handler */ - public function __construct(DoliDB $db) - { + public function __construct(DoliDB $db) + { $this->db = $db; } @@ -191,8 +191,8 @@ class BookKeeping extends CommonObject * @param bool $notrigger false=launch triggers after, true=disable triggers * @return int <0 if KO, Id of created object if OK */ - public function create(User $user, $notrigger = false) - { + public function create(User $user, $notrigger = false) + { global $conf, $langs; dol_syslog(__METHOD__, LOG_DEBUG); @@ -504,11 +504,11 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, Id of created object if OK */ - public function createStd(User $user, $notrigger = false, $mode = '') - { + public function createStd(User $user, $notrigger = false, $mode = '') + { global $conf, $langs; - $langs->loadLangs(array("accountancy", "bills", "compta")); + $langs->loadLangs(array("accountancy", "bills", "compta")); dol_syslog(__METHOD__, LOG_DEBUG); @@ -578,7 +578,7 @@ class BookKeeping extends CommonObject $now = dol_now(); // Check parameters - $this->journal_label = $langs->trans($this->journal_label); + $this->journal_label = $langs->trans($this->journal_label); // Insert request $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.' ('; @@ -673,8 +673,8 @@ class BookKeeping extends CommonObject * * @return int <0 if KO, 0 if not found, >0 if OK */ - public function fetch($id, $ref = null, $mode = '') - { + public function fetch($id, $ref = null, $mode = '') + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -771,8 +771,8 @@ class BookKeeping extends CommonObject * * @return int <0 if KO, >=0 if OK */ - public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') - { + public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -904,11 +904,11 @@ class BookKeeping extends CommonObject * @param int $offset Offset limit * @param array $filter Filter array * @param string $filtermode Filter mode (AND or OR) - * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default)) + * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default)) * @return int <0 if KO, >0 if OK */ - public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1) - { + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1) + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -940,7 +940,7 @@ class BookKeeping extends CommonObject $sql .= " t.date_creation,"; $sql .= " t.date_lim_reglement,"; $sql .= " t.tms as date_modification,"; - $sql .= " t.date_export"; + $sql .= " t.date_export"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; // Manage filter $sqlwhere = array(); @@ -960,8 +960,8 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.tms>=' || $key == 't.tms<=') { $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; - } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { - $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; + } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } else { @@ -970,9 +970,9 @@ class BookKeeping extends CommonObject } } $sql .= ' WHERE t.entity IN ('.getEntity('accountancy').')'; - if ($showAlreadyExportMovements == 0) { - $sql .= " AND t.date_export IS NULL"; - } + if ($showAlreadyExportMovements == 0) { + $sql .= " AND t.date_export IS NULL"; + } if (count($sqlwhere) > 0) { $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } @@ -1020,7 +1020,7 @@ class BookKeeping extends CommonObject $line->date_creation = $this->db->jdate($obj->date_creation); $line->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement); $line->date_modification = $this->db->jdate($obj->date_modification); - $line->date_export = $this->db->jdate($obj->date_export); + $line->date_export = $this->db->jdate($obj->date_export); $this->lines[] = $line; @@ -1133,8 +1133,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode ('' or _tmp') * @return int <0 if KO, >0 if OK */ - public function update(User $user, $notrigger = false, $mode = '') - { + public function update(User $user, $notrigger = false, $mode = '') + { $error = 0; dol_syslog(__METHOD__, LOG_DEBUG); @@ -1300,8 +1300,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function delete(User $user, $notrigger = false, $mode = '') - { + public function delete(User $user, $notrigger = false, $mode = '') + { dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; @@ -1348,8 +1348,8 @@ class BookKeeping extends CommonObject * @param string $importkey Import key * @return int Result */ - public function deleteByImportkey($importkey) - { + public function deleteByImportkey($importkey) + { $this->db->begin(); // first check if line not yet in bookkeeping @@ -1379,11 +1379,11 @@ class BookKeeping extends CommonObject * @param int $delmonth Month * @return int <0 if KO, >0 if OK */ - public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0) - { - global $langs; + public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0) + { + global $langs; - if (empty($delyear) && empty($journal)) + if (empty($delyear) && empty($journal)) { $this->error = 'ErrorOneFieldRequired'; return -1; @@ -1428,8 +1428,8 @@ class BookKeeping extends CommonObject * @param int $piecenum Piecenum to delete * @return int Result */ - public function deleteMvtNum($piecenum) - { + public function deleteMvtNum($piecenum) + { global $conf; $this->db->begin(); @@ -1463,8 +1463,8 @@ class BookKeeping extends CommonObject * @param int $fromid Id of object to clone * @return int New id of clone */ - public function createFromClone(User $user, $fromid) - { + public function createFromClone(User $user, $fromid) + { dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; @@ -1511,8 +1511,8 @@ class BookKeeping extends CommonObject * * @return void */ - public function initAsSpecimen() - { + public function initAsSpecimen() + { global $user; $now = dol_now(); @@ -1548,8 +1548,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function fetchPerMvt($piecenum, $mode = '') - { + public function fetchPerMvt($piecenum, $mode = '') + { global $conf; $sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type,date_creation"; @@ -1613,8 +1613,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function fetchAllPerMvt($piecenum, $mode = '') - { + public function fetchAllPerMvt($piecenum, $mode = '') + { global $conf; $sql = "SELECT rowid, doc_date, doc_type,"; @@ -1664,16 +1664,16 @@ class BookKeeping extends CommonObject return 1; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Export bookkeeping * * @param string $model Model * @return int Result */ - public function export_bookkeeping($model = 'ebp') - { - // phpcs:enable + public function export_bookkeeping($model = 'ebp') + { + // phpcs:enable global $conf; $sql = "SELECT rowid, doc_date, doc_type,"; @@ -1739,10 +1739,10 @@ class BookKeeping extends CommonObject $this->db->begin(); - if ($direction == 0) + if ($direction == 0) { $next_piecenum = $this->getNextNumMvt(); - $now = dol_now(); + $now = dol_now(); if ($next_piecenum < 0) { $error++; @@ -1819,22 +1819,22 @@ class BookKeeping extends CommonObject */ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Return list of accounts with label by chart of accounts - * - * @param string $selectid Preselected chart of accounts - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param array $event Event options - * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) - * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number - * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number - * @return string String with HTML select - */ - public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') - { - // phpcs:enable + * Return list of accounts with label by chart of accounts + * + * @param string $selectid Preselected chart of accounts + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) + * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number + * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number + * @return string String with HTML select + */ + public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') + { + // phpcs:enable global $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; @@ -1891,7 +1891,7 @@ class BookKeeping extends CommonObject return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Description of a root accounting account * @@ -1900,7 +1900,7 @@ class BookKeeping extends CommonObject */ public function get_compte_racine($account = null) { - // phpcs:enable + // phpcs:enable global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; @@ -1932,16 +1932,16 @@ class BookKeeping extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Description of accounting account * * @param string $account Accounting account * @return string Account desc */ - public function get_compte_desc($account = null) - { - // phpcs:enable + public function get_compte_desc($account = null) + { + // phpcs:enable global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; @@ -1989,13 +1989,13 @@ class BookKeepingLine public $doc_ref; /** - * @var int ID - */ + * @var int ID + */ public $fk_doc; /** - * @var int ID - */ + * @var int ID + */ public $fk_docdet; public $thirdparty_code; @@ -2007,26 +2007,26 @@ class BookKeepingLine public $debit; public $credit; - /** - * @var float Amount - * @deprecated see $amount - */ + /** + * @var float Amount + * @deprecated see $amount + */ public $montant; - /** - * @var float Amount - */ + /** + * @var float Amount + */ public $amount; - /** - * @var string Sens - */ - public $sens; - public $lettering_code; + /** + * @var string Sens + */ + public $sens; + public $lettering_code; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; public $import_key; @@ -2035,17 +2035,17 @@ class BookKeepingLine public $piece_num; /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; /** * @var integer|string $date_modification; */ - public $date_modification; + public $date_modification; - /** - * @var integer|string $date_export; - */ - public $date_export; + /** + * @var integer|string $date_export; + */ + public $date_export; } diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index f99f1148044..a6cf6f2fc14 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -166,7 +166,7 @@ print '\n"; -print load_fiche_titre($langs->trans("Backup"), '', 'title_setup'); +$title = $langs->trans("Backup"); + +print load_fiche_titre($title, '', 'title_setup'); //print_barre_liste($langs->trans("Backup"), '', '', '', '', '', $langs->trans("BackupDesc",DOL_DATA_ROOT), 0, 0, 'title_setup'); print '
'; @@ -139,7 +142,9 @@ print '
'; print '
'; -print load_fiche_titre($title ? $title : $langs->trans("BackupDumpWizard")); +$title = $langs->trans("BackupDumpWizard"); + +print load_fiche_titre($title); print '
'.price($opening_balances["'".$line->numero_compte."'"]).''.price($line->debit).''.price($line->credit).''.price($line->debit - $line->credit).''.price(price2num($line->debit - $line->credit, 'MT')).''.$link; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1); + print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1); + print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { + print $langs->trans('From').' '; print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); } else { - print ''; + print ''; } print '
'; print '
'; - print $langs->trans('to').' '; // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { + print $langs->trans('to').' '; print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); } else { - print ''; + print ''; } print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_creation_start, 'date_creation_start', 0, 0, 1); + print $form->selectDate($search_date_creation_start, 'date_creation_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_creation_end, 'date_creation_end', 0, 0, 1); + print $form->selectDate($search_date_creation_end, 'date_creation_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_modification_start, 'date_modification_start', 0, 0, 1); + print $form->selectDate($search_date_modification_start, 'date_modification_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_modification_end, 'date_modification_end', 0, 0, 1); + print $form->selectDate($search_date_modification_end, 'date_modification_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; print '
'; - print $langs->trans('From').' '; - print $form->selectDate($search_date_export_start, 'date_export_start', 0, 0, 1); + print $form->selectDate($search_date_export_start, 'date_export_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to').' '; - print $form->selectDate($search_date_export_end, 'date_export_end', 0, 0, 1); + print $form->selectDate($search_date_export_end, 'date_export_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; if (empty($line->date_export)) { if ($user->rights->accounting->mouvements->creer) { - print ''.img_edit().''; + print ''.img_edit().''; } if ($user->rights->accounting->mouvements->supprimer) { - print ' '.img_delete().''; + print ''.img_delete().''; } } print ''; print '
'; - print $langs->trans('From') . ': '; - print $form->selectDate($search_date_start, 'search_date_start', 0, 0, 1); + print $form->selectDate($search_date_start, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); print '
'; print '
'; - print $langs->trans('to') . ': '; - print $form->selectDate($search_date_end, 'search_date_end', 0, 0, 1); + print $form->selectDate($search_date_end, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print '
'; if (empty($line->date_export)) { if ($user->rights->accounting->mouvements->creer) { - print ''.img_edit().''; + print ''.img_edit().''; } if ($user->rights->accounting->mouvements->supprimer) { - print ' '.img_delete().''; + print '   '.img_delete().''; } } print '
'; print ''; @@ -155,19 +160,19 @@ print ''; diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index 560530c9161..c962a9fb776 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -73,16 +73,16 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $transkey = ''; - $transvalue = ''; - $toselect = ''; - $search_array_options = array(); + $transkey = ''; + $transvalue = ''; + $toselect = ''; + $search_array_options = array(); } if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION') { - if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); + if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity); + else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); } if ($action == 'update') @@ -139,25 +139,25 @@ if ($action == 'add') } if (!$error) { - $db->begin(); + $db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")"; $result = $db->query($sql); if ($result > 0) { - $db->commit(); - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $db->commit(); + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ""; $transkey = ""; $transvalue = ""; } else { - $db->rollback(); - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); - } else { - setEventMessages($db->lasterror(), null, 'errors'); - } + $db->rollback(); + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); + } else { + setEventMessages($db->lasterror(), null, 'errors'); + } $action = ''; } } @@ -196,15 +196,15 @@ $enabledisablehtml = ''; $enabledisablehtml .= $langs->trans("EnableOverwriteTranslation").' '; if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { - // Button off, click to enable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); - $enabledisablehtml .= ''; + // Button off, click to enable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= ''; } else { - // Button on, click to disable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); - $enabledisablehtml .= ''; + // Button on, click to disable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= ''; } print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup'); @@ -247,43 +247,43 @@ if ($mode == 'overwrite') if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit = ' disabled'; print '
'; - print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); - $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; - print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; - print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; - print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; - print '
'; + print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); + $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; + print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; + print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; + print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; + print ''; - print '
'; + print '
'; print ''; - print ''; + print ''; print '
'; - print '
'; print '
'; print '
'.$langs->trans("ExportMethod").''; if (in_array($type, array('mysql', 'mysqli'))) { - print '
'; - print ''; - print '
'; - print '
'; - print '
'; - print ''; - print '
'; + print '
'; + print ''; + print '
'; + print '
'; + print '
'; + print ''; + print '
'; } elseif (in_array($type, array('pgsql'))) { - print '
'; - print ''; - print '
'; + print '
'; + print ''; + print '
'; } else { - print 'No method available with database '.$label; + print 'No method available with database '.$label; } print '
'; print '
'; @@ -178,200 +183,200 @@ print '
'; print '
'; if (in_array($type, array('mysql', 'mysqli'))) { - print "\n"; - print '
'.$langs->trans("MySqlExportParameters").''; + print "\n"; + print '
'.$langs->trans("MySqlExportParameters").''; - print '
'.$langs->trans("FullPathToMysqldumpCommand"); - if (empty($conf->global->SYSTEMTOOLS_MYSQLDUMP)) - { - $fullpathofmysqldump = $db->getPathOfDump(); - } else { - $fullpathofmysqldump = $conf->global->SYSTEMTOOLS_MYSQLDUMP; - } - print '
'; - print '
'; + print '
'.$langs->trans("FullPathToMysqldumpCommand"); + if (empty($conf->global->SYSTEMTOOLS_MYSQLDUMP)) + { + $fullpathofmysqldump = $db->getPathOfDump(); + } else { + $fullpathofmysqldump = $conf->global->SYSTEMTOOLS_MYSQLDUMP; + } + print '
'; + print '
'; - print '
'; - print '
'.$langs->trans("ExportOptions").''; - print '
'; - print ''; - print ''; - print '
'; + print '
'; + print '
'.$langs->trans("ExportOptions").''; + print '
'; + print ''; + print ''; + print '
'; - if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) { - print '
'; - print ''; - print ''; - print '
'; - } + if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) { + print '
'; + print ''; + print ''; + print '
'; + } - print ''; + print ''; - print ''; - print '
'; + print ''; + print '
'; - print ''; - print '
'; + print ''; + print '
'; - print '
'; - print '
'; - print ''; - print ''; - print ''; - print ''; + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print '
'; - print '
'; + print ''; + print ''; + print '
'; + print '
'; - print '
'; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'; + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print '
'; - print '
'; - print "\n"; - print '
'; - print ''.$langs->trans("MySqlExportParameters").''; - print '
'; - print ''.$langs->trans("ExportOptions").''; - print '
'; - print ''; - print ''; + print '
'; + print '
'; + print "\n"; + print '
'; + print ''.$langs->trans("MySqlExportParameters").''; + print '
'; + print ''.$langs->trans("ExportOptions").''; + print '
'; + print ''; + print ''; - print '
'; - if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) { - print '
'; - print ''; - print ''; - print '
'; - } - print '
'; + print '
'; + if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) { + print '
'; + print ''; + print ''; + print '
'; + } + print ''; - print '
'; - print '
'.$langs->trans('ExportStructure').''; - print ''; - print ''; - print '
'; - print '
'; + print '
'; + print '
'.$langs->trans('ExportStructure').''; + print ''; + print ''; + print '
'; + print '
'; - print '
'; - print '
'; - print ''.$langs->trans("Datas").''; + print '
'; + print '
'; + print ''.$langs->trans("Datas").''; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print ''; - print ''; - print '
'; + print ''; + print ''; + print '
'; - print '
'; - print '
'; + print ''; + print ''; } if (in_array($type, array('pgsql'))) { - print "\n"; - print '
'.$langs->trans("PostgreSqlExportParameters").''; + print "\n"; + print '
'.$langs->trans("PostgreSqlExportParameters").''; - print '
'.$langs->trans("FullPathToPostgreSQLdumpCommand"); - if (empty($conf->global->SYSTEMTOOLS_POSTGRESQLDUMP)) { - $fullpathofpgdump = $db->getPathOfDump(); - } else { - $fullpathofpgdump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP; - } - print '
'; - print '
'; + print '
'.$langs->trans("FullPathToPostgreSQLdumpCommand"); + if (empty($conf->global->SYSTEMTOOLS_POSTGRESQLDUMP)) { + $fullpathofpgdump = $db->getPathOfDump(); + } else { + $fullpathofpgdump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP; + } + print '
'; + print '
'; - print '
'; - print '
'; - print ''.$langs->trans("ExportOptions").''; - print ''; - print ''; - print '
'; - print ''; - print '
'; - print '
'; - print '
'; - print ''; - print ''; - print ''; - print ''; - print '
'; - print '
'; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print ''.$langs->trans("ExportOptions").''; + print ''; + print ''; + print '
'; + print ''; + print '
'; + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print '
'; + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; + print '
'; + print '
'; } print ''; @@ -418,16 +423,16 @@ if (in_array($type, array('mysql', 'mysqli'))) { // 'id' => 'radio_compression_zip', // 'label' => $langs->trans("FormatZip") // ); - $compression['bz'] = array( + $compression['bz'] = array( 'function' => 'bzopen', 'id' => 'radio_compression_bzip', 'label' => $langs->trans("Bzip2") ); - $compression['none'] = array( - 'function' => '', - 'id' => 'radio_compression_none', - 'label' => $langs->trans("None") - ); + $compression['none'] = array( + 'function' => '', + 'id' => 'radio_compression_none', + 'label' => $langs->trans("None") + ); } else { $compression['none'] = array( 'function' => '', @@ -480,14 +485,14 @@ print '
'; if (!empty($_SESSION["commandbackuplastdone"])) { - print '
'.$langs->trans("RunCommandSummary").':
'."\n"; - print '
'."\n"; - print '
'; + print '
'.$langs->trans("RunCommandSummary").':
'."\n"; + print '
'."\n"; + print '
'; - //print $paramclear; + //print $paramclear; - // Now show result - print ''.$langs->trans("BackupResult").': '; + // Now show result + print ''.$langs->trans("BackupResult").': '; print $_SESSION["commandbackupresult"]; $_SESSION["commandbackuplastdone"] = ''; @@ -568,20 +573,20 @@ $filecompression['zip'] = array('function' => 'dol_compress_dir', 'id' => 'radio $i = 0; foreach ($filecompression as $key => $val) { - if (!$val['function'] || function_exists($val['function'])) // Enabled export format - { - $checked = ''; - if ($key == 'gz') $checked = ' checked'; - print ''; - print ' '; - } else // Disabled export format - { - print ''; - print ' '; - print ' ('.$langs->trans("NotAvailable").')'; - } - print '     '; - $i++; + if (!$val['function'] || function_exists($val['function'])) // Enabled export format + { + $checked = ''; + if ($key == 'gz') $checked = ' checked'; + print ''; + print ' '; + } else // Disabled export format + { + print ''; + print ' '; + print ' ('.$langs->trans("NotAvailable").')'; + } + print '     '; + $i++; } print ''; diff --git a/htdocs/admin/tools/export.php b/htdocs/admin/tools/export.php index cbe25f0ff75..7ab26f6f6e0 100644 --- a/htdocs/admin/tools/export.php +++ b/htdocs/admin/tools/export.php @@ -122,7 +122,7 @@ $utils = new Utils($db); // MYSQL if ($what == 'mysql') { - $cmddump = GETPOST("mysqldump"); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg + $cmddump = GETPOST("mysqldump", 'none'); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg $cmddump = dol_sanitizePathName($cmddump); if (!empty($dolibarr_main_restrict_os_commands)) @@ -163,7 +163,7 @@ if ($what == 'mysqlnobin') // POSTGRESQL if ($what == 'postgresql') { - $cmddump = GETPOST("postgresqldump"); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg + $cmddump = GETPOST("postgresqldump", 'none'); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg $cmddump = dol_sanitizePathName($cmddump); /* Not required, the command is output on screen but not ran for pgsql diff --git a/htdocs/admin/tools/export_files.php b/htdocs/admin/tools/export_files.php index 485df8c318b..28eaa2d9d54 100644 --- a/htdocs/admin/tools/export_files.php +++ b/htdocs/admin/tools/export_files.php @@ -113,7 +113,7 @@ $utils = new Utils($db); if ($compression == 'zip') { $file .= '.zip'; - $ret = dol_compress_dir(DOL_DATA_ROOT, $outputdir."/".$file, $compression, '/(\.log|\/temp\/|documents\/admin\/documents\/)/'); + $ret = dol_compress_dir(DOL_DATA_ROOT, $outputdir."/".$file, $compression, '/(\.back|\.old|\.log|[\\\/]temp[\\\/]|documents[\\\/]admin[\\\/]documents[\\\/])/i'); if ($ret < 0) { if ($ret == -2) { diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index 32567f14074..82111e0716d 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -167,7 +167,7 @@ $usefilter = 0; $sql = "SELECT e.rowid, e.type, e.ip, e.user_agent, e.dateevent,"; $sql .= " e.fk_user, e.description, e.prefix_session,"; -$sql .= " u.login"; +$sql .= " u.login, u.admin, u.entity, u.firstname, u.lastname, u.statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."events as e"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = e.fk_user"; $sql .= " WHERE e.entity IN (".getEntity('event').")"; @@ -337,7 +337,18 @@ if ($result) { $userstatic->id = $obj->fk_user; $userstatic->login = $obj->login; + $userstatic->admin = $obj->admin; + $userstatic->entity = $obj->entity; + $userstatic->status = $obj->status; + print $userstatic->getLoginUrl(1); + if (!empty($conf->multicompany->enabled) && $userstatic->admin && !$userstatic->entity) + { + print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"'); + } elseif ($userstatic->admin) + { + print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"'); + } } else print ' '; print '
'; - print ''; - print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); - //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); - print ''; - print "\n"; + print '
'; + print ''; + print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); + print ''; + print "\n"; - // Line to add new record - print "\n"; + // Line to add new record + print "\n"; - print ''."\n"; - print ''; - // Limit to superadmin - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print ''."\n"; + print ''; + // Limit to superadmin + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print '\n"; - print ''; + print '\n"; + print ''; - // Show constants - $sql = "SELECT rowid, entity, lang, transkey, transvalue"; - $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql .= " WHERE 1 = 1"; - $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; - $sql .= $db->order($sortfield, $sortorder); + // Show constants + $sql = "SELECT rowid, entity, lang, transkey, transvalue"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE 1 = 1"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + $sql .= $db->order($sortfield, $sortorder); - dol_syslog("translation::select from table", LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($result); + while ($i < $num) + { + $obj = $db->fetch_object($result); - print "\n"; + print "\n"; - print ''; + print ''; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; - // Value - print ''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + } else { + print dol_escape_htmltag($obj->transvalue); + } + print ''; - print ''; + print ''; + } else { + print ''.img_edit().''; + print '   '; + print ''.img_delete().''; + } + print ''; - print "\n"; - print "\n"; - $i++; - } - } + print "\n"; + print "\n"; + $i++; + } + } - print '
'; - print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); - print ''; - print ''; - print ''; - print ''; - print '
'; + print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); + print ''; + print ''; + print ''; + print ''; + print ''; print ''; @@ -292,118 +292,118 @@ if ($mode == 'overwrite') } else {*/ - print ''; - print ''; - //} - print ''; - print "
'; + print ''; + //} + print ''; + print "
'.$obj->lang.''.$obj->transkey.''.$obj->lang.''.$obj->transkey.''; - /*print ''; + // Value + print ''; + /*print ''; print ''; print ''; print ''; */ - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { - print ''; - } else { - print dol_escape_htmltag($obj->transvalue); - } - print ''; - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { - print ''; - print ''; - print '   '; - print ''; - } else { - print ''.img_edit().''; + print ''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + print ''; print '   '; - print ''.img_delete().''; - } - print '
'; - print ''; + print ''; + print ''; } if ($mode == 'searchkey') { - $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; + $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; - $newlang = new Translate('', $conf); - $newlang->setDefaultLang($langcode); + $newlang = new Translate('', $conf); + $newlang->setDefaultLang($langcode); - $newlangfileonly = new Translate('', $conf); - $newlangfileonly->setDefaultLang($langcode); + $newlangfileonly = new Translate('', $conf); + $newlangfileonly->setDefaultLang($langcode); - $recordtoshow = array(); + $recordtoshow = array(); - // Search modules dirs - $modulesdir = dolGetModulesDirs(); + // Search modules dirs + $modulesdir = dolGetModulesDirs(); - $nbtotaloffiles = 0; - $nbempty = 0; - /*var_dump($langcode); + $nbtotaloffiles = 0; + $nbempty = 0; + /*var_dump($langcode); var_dump($transkey); var_dump($transvalue);*/ - if (empty($langcode) || $langcode == '-1') $nbempty++; - if (empty($transkey)) $nbempty++; - if (empty($transvalue)) $nbempty++; - if ($action == 'search' && ($nbempty > 999)) // 999 to disable this - { - setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings'); - } else { - // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root) - $i = 0; - foreach ($modulesdir as $keydir => $tmpsearchdir) - { - $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' + if (empty($langcode) || $langcode == '-1') $nbempty++; + if (empty($transkey)) $nbempty++; + if (empty($transvalue)) $nbempty++; + if ($action == 'search' && ($nbempty > 999)) // 999 to disable this + { + setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings'); + } else { + // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root) + $i = 0; + foreach ($modulesdir as $keydir => $tmpsearchdir) + { + $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' - // Directory of translation files - $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels - $dir_lang_osencoded = dol_osencode($dir_lang); + // Directory of translation files + $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels + $dir_lang_osencoded = dol_osencode($dir_lang); - $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); - foreach ($filearray as $file) - { + $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); + foreach ($filearray as $file) + { $tmpfile = preg_replace('/.lang/i', '', basename($file['name'])); $moduledirname = (basename(dirname(dirname($dir_lang)))); @@ -416,135 +416,135 @@ if ($mode == 'searchkey') if ($result < 0) print 'Failed to load language file '.$tmpfile.'
'."\n"; else $nbtotaloffiles++; //print 'After loading lang '.$langkey.', newlang has '.count($newlang->tab_translate).' records
'."\n"; - } - $i++; - } + } + $i++; + } - // Now search into translation array - foreach ($newlang->tab_translate as $key => $val) - { - if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; - if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; - $recordtoshow[$key] = $val; - } - } + // Now search into translation array + foreach ($newlang->tab_translate as $key => $val) + { + if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; + if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; + $recordtoshow[$key] = $val; + } + } - //print '
'; - $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); - $nbtotalofrecords = count($recordtoshow); - $num = $limit + 1; - if (($offset + $num) > $nbtotalofrecords) $num = $limit; + //print '
'; + $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); + $nbtotalofrecords = count($recordtoshow); + $num = $limit + 1; + if (($offset + $num) > $nbtotalofrecords) $num = $limit; - //print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder; - $title = $langs->trans("TranslationKeySearch"); - if ($nbtotalofrecords > 0) $title .= ' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')'; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); + //print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder; + $title = $langs->trans("TranslationKeySearch"); + if ($nbtotalofrecords > 0) $title .= ' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')'; + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); - print ''; - print ''; + print ''; + print ''; print '
'; - print ''; - print ''; - print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); - //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); - print ''; - print "\n"; + print '
'; + print ''; + print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); + print ''; + print "\n"; - // Line to search new record - print "\n"; + // Line to search new record + print "\n"; - print ''."\n"; - print ''."\n"; + print ''; - // Action column - print ''; - print ''; + print ''; + //} + print ''; + // Action column + print ''; + print ''; - if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow); - if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow); - if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow); - if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow); + if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow); + if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow); + if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow); + if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow); - // Show result - $i = 0; - foreach ($recordtoshow as $key => $val) - { - $i++; - if ($i <= $offset) continue; - if ($i > ($offset + $limit)) break; - print ''; }*/ - print ''."\n"; - } + print ''."\n"; + } - print '
'; - //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1); - print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1); - print ''; - print ''; - print ''; - print ''; - // Limit to superadmin - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print '
'; + //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1); + print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1); + print ''; + print ''; + print ''; + print ''; + // Limit to superadmin + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''; print ''; } else {*/ - print ''; - //} - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); - print $searchpicto; - print '
'; + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + print $searchpicto; + print '
'.$langcode.''.$key.''; - print dol_escape_htmltag($val); - print ''; - if (!empty($newlangfileonly->tab_translate[$key])) - { - if ($val != $newlangfileonly->tab_translate[$key]) - { - // retrieve rowid - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql .= " WHERE transkey = '".$key."'"; - $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; - dol_syslog("translation::select from table", LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - } - print ''.img_edit().''; - print ' '; - print ''.img_delete().''; - print '  '; - $htmltext = $langs->trans("OriginalValueWas", ''.$newlangfileonly->tab_translate[$key].''); - print $form->textwithpicto('', $htmltext, 1, 'info'); - } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) - { - //print $key.'-'.$val; - print ''.img_edit_add($langs->trans("Overwrite")).''; - } + // Show result + $i = 0; + foreach ($recordtoshow as $key => $val) + { + $i++; + if ($i <= $offset) continue; + if ($i > ($offset + $limit)) break; + print '
'.$langcode.''.$key.''; + print dol_escape_htmltag($val); + print ''; + if (!empty($newlangfileonly->tab_translate[$key])) + { + if ($val != $newlangfileonly->tab_translate[$key]) + { + // retrieve rowid + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE transkey = '".$key."'"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + } + print ''.img_edit().''; + print ' '; + print ''.img_delete().''; + print '  '; + $htmltext = $langs->trans("OriginalValueWas", ''.$newlangfileonly->tab_translate[$key].''); + print $form->textwithpicto('', $htmltext, 1, 'info'); + } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) + { + //print $key.'-'.$val; + print ''.img_edit_add($langs->trans("Overwrite")).''; + } - if (!empty($conf->global->MAIN_FEATURES_LEVEL)) - { - $transifexlangfile = '$'; // $ means 'All' - //$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; - $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key; + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) + { + $transifexlangfile = '$'; // $ means 'All' + //$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; + $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key; - print '   '.img_picto($langs->trans('FixOnTransifex'), 'globe').''; - } - } else { - $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key); - print $form->textwithpicto('', $htmltext, 1, 'warning'); - } - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print '   '.img_picto($langs->trans('FixOnTransifex'), 'globe').''; + } + } else { + $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key); + print $form->textwithpicto('', $htmltext, 1, 'warning'); + } + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''.$val.'
'; - print '
'; + print ''; + print ''; } dol_fiche_end(); diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index b8520ecc227..19d71ebb1d9 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -124,252 +124,252 @@ $sourceList = array(); // Actions add or modify a website if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield = explode(',', $tabfield[$id]); - $listfieldinsert = explode(',', $tabfieldinsert[$id]); - $listfieldmodify = explode(',', $tabfieldinsert[$id]); - $listfieldvalue = explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', $tabfield[$id]); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); - // Check that all fields are filled - $ok = 1; - foreach ($listfield as $f => $value) - { - if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) - { - $ok = 0; - $fieldnamekey = $listfield[$f]; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - break; - } elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) - { + // Check that all fields are filled + $ok = 1; + foreach ($listfield as $f => $value) + { + if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) + { $ok = 0; - $fieldnamekey = $listfield[$f]; + $fieldnamekey = $listfield[$f]; + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + break; + } elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) + { + $ok = 0; + $fieldnamekey = $listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities($fieldnamekey)), null, 'errors'); break; - } - } + } + } - // Clean parameters - if (!empty($_POST['ref'])) - { - $websitekey = strtolower($_POST['ref']); - } + // Clean parameters + if (!empty($_POST['ref'])) + { + $websitekey = strtolower($_POST['ref']); + } - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd', 'alpha')) - { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid = 0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid = ($obj->newid + 1); - } else { - dol_print_error($db); - } - } + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd', 'alpha')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid = 0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid = ($obj->newid + 1); + } else { + dol_print_error($db); + } + } - /* $website=new Website($db); + /* $website=new Website($db); $website->ref= $website->description= $website->virtualhost= $website->create($user); */ - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $tabrowid[$id].","; - $sql .= $tabfieldinsert[$id]; - $sql .= ",status)"; - $sql .= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",status)"; + $sql .= " VALUES("; - // List of values - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $newid.","; - $i = 0; - foreach ($listfieldinsert as $f => $value) - { - if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($value == 'ref') { - $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); - } - if ($i) $sql .= ","; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql .= ",1)"; + // List of values + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($value == 'ref') { + $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); + } + if ($i) $sql .= ","; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql .= ",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - unset($_POST); // Clean $_POST array, we keep only - } else { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + unset($_POST); // Clean $_POST array, we keep only + } else { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify', 'alpha')) - { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify', 'alpha')) + { + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $db->begin(); + $db->begin(); - $website = new Website($db); - $rowid = GETPOST('rowid', 'int'); - $website->fetch($rowid); + $website = new Website($db); + $rowid = GETPOST('rowid', 'int'); + $website->fetch($rowid); - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) - { - $sql .= $tabrowid[$id]."="; - $sql .= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql .= ","; - $sql .= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) + { + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); - if ($newname != $website->ref) - { - $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; - $destfile = DOL_DATA_ROOT.'/website/'.$newname; + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); + if ($newname != $website->ref) + { + $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; + $destfile = DOL_DATA_ROOT.'/website/'.$newname; - if (dol_is_dir($destfile)) - { - $error++; - setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); - } else { - @rename($srcfile, $destfile); + if (dol_is_dir($destfile)) + { + $error++; + setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); + } else { + @rename($srcfile, $destfile); - // We must now rename $website->ref into $newname inside files - $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html'); - $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$'); + // We must now rename $website->ref into $newname inside files + $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html'); + $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$'); foreach ($listofilestochange as $key => $value) - { - dolReplaceInFile($value['fullname'], $arrayreplacement); - } - } - } - } else { - $error++; - setEventMessages($db->lasterror(), null, 'errors'); - } + { + dolReplaceInFile($value['fullname'], $arrayreplacement); + } + } + } + } else { + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + } - if (!$error) - { - $db->commit(); - } else { - $db->rollback(); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + if (!$error) + { + $db->commit(); + } else { + $db->rollback(); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel', 'alpha')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $website = new Website($db); - $website->fetch($rowid); + $website = new Website($db); + $website->fetch($rowid); - if ($website->id > 0) - { - $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid); - $result = $db->query($sql); + if ($website->id > 0) + { + $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid); - $result = $db->query($sql); + $sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid); - $result = $db->query($sql); + $sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid); - $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } else { - dol_print_error($db); - } - } + $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid); + $result = $db->query($sql); + if (!$result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } else { + dol_print_error($db); + } + } - if ($website->ref) - { - dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); - } - } else { - dol_print_error($db, 'Failed to load website with id '.$rowid); - } + if ($website->ref) + { + dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); + } + } else { + dol_print_error($db, 'Failed to load website with id '.$rowid); + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -411,7 +411,7 @@ print "
\n"; // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220); } //var_dump($elementList); @@ -420,205 +420,205 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql = $tabsql[$id]; - $sql .= $db->order($sortfield, $sortorder); - $sql .= $db->plimit($limit + 1, $offset); - //print $sql; + // Complete requete recherche valeurs avec critere de tri + $sql = $tabsql[$id]; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($limit + 1, $offset); + //print $sql; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - print ''; - print ''; - print ''; + print ''; + print ''; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused = 0; - $var = false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused = 0; + $var = false; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - $align = ''; - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($valuetoshow != '') - { - print ''; - } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; - } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $align = ''; + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; + } - print ''; - print ''; + print ''; + print ''; - // Line to enter new values - print ""; + // Line to enter new values + print ""; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd', 'alpha')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val, 'alpha')) - $obj->$val = GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd', 'alpha')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val, 'alpha')) + $obj->$val = GETPOST($val); + } + } - fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); + fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); - print ''; - print ""; + print ''; + print ""; - $colspan = count($fieldlist) + 2; - } + $colspan = count($fieldlist) + 2; + } - print '
'; - if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (!empty($tabhelp[$id][$value])) - { - if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); - else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); - } else print $valuetoshow; - print '
'; + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + elseif (!empty($tabhelp[$id][$value])) + { + if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); + else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + } else print $valuetoshow; + print ''; - print '
'; + print '
'; - if ($action != 'edit') - { - print ''; - } - print '
'; + if ($action != 'edit') + { + print ''; + } + print '
'; - print ''; + print ''; + print ''; - // List of websites in database - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - if ($num) - { - print '
'; + // List of websites in database + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + if ($num) + { + print '
'; - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print '
'; - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield = 1; // Par defaut - $align = "left"; - $sortable = 1; - $valuetoshow = ''; - /* + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield = 1; // Par defaut + $align = "left"; + $sortable = 1; + $valuetoshow = ''; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); - } - } + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "status", ($page ? 'page='.$page.'&' : ''), "", 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) - { - $tmpaction = 'edit'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) + { + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); + if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); - print ''; - } else { - $tmpaction = 'view'; - $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + print ''; + } else { + $tmpaction = 'view'; + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { - $showfield = 1; - $align = "left"; - $fieldname = $fieldlist[$field]; - $valuetoshow = $obj->$fieldname; + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { + $showfield = 1; + $align = "left"; + $fieldname = $fieldlist[$field]; + $valuetoshow = $obj->$fieldname; // Show value for field if ($showfield) print ''; - } - } + } + } - // Can an entry be erased or disabled ? - $iserasable = 1; $isdisable = 1; // true by default - if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first. + // Can an entry be erased or disabled ? + $iserasable = 1; $isdisable = 1; // true by default + if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first. - $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&'; + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&'; - // Active - print '"; + // Active + print '"; - // Modify link - print ''; + // Modify link + print ''; - // Delete link - if ($iserasable) print ''; - else print ''; + // Delete link + if ($iserasable) print ''; + else print ''; - print "\n"; - } - $i++; - } + print "\n"; + } + $i++; + } - print '
 '; - print '  '; + print ' '.$valuetoshow.''; - print ''.$actl[($obj->status ? 1 : 0)].''; - print "'; + print ''.$actl[($obj->status ? 1 : 0)].''; + print "'.img_edit().''.img_edit().''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').'
'; + print ''; - print '
'; - } - } else { - dol_print_error($db); - } + print ''; + } + } else { + dol_print_error($db); + } } dol_fiche_end(); @@ -649,7 +649,7 @@ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') foreach ($fieldlist as $field => $value) { - $fieldname = $fieldlist[$field]; + $fieldname = $fieldlist[$field]; if ($fieldlist[$field] == 'lang') { print ''; diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index fbe5e7b1872..8177fbf7e1e 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -35,1865 +35,1865 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; */ class Setup extends DolibarrApi { - private $translations = null; - - /** - * Constructor - */ - public function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of ordering methods. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment type is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')" - * - * @url GET dictionary/ordering_methods - * - * @return array [List of ordering methods] - * - * @throws RestException 400 - */ - public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } - - $sql = "SELECT rowid, code, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of payments types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment type is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/payment_types - * - * @return array [List of payment types] - * - * @throws RestException 400 - */ - public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of states/provinces. - * - * The names of the states will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by state ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of countries - * - * @url GET dictionary/states - * - * @throws RestException - */ - public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t"; - $sql .= " WHERE 1 = 1"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $state = new Cstate($this->db); - if ($state->fetch($obj->rowid) > 0) { - if (empty($filter) || stripos($state->label, $filter) !== false) { - $list[] = $this->_cleanObjectDatas($state); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of states'); - } - - return $list; - } - - /** - * Get state by ID. - * - * @param int $id ID of state - * @return array Array of cleaned object properties - * - * @url GET dictionary/states/{id} - * - * @throws RestException - */ - public function getStateByID($id) - { - return $this->_fetchCstate($id, ''); - } - - /** - * Get state by Code. - * - * @param string $code Code of state - * @return array Array of cleaned object properties - * - * @url GET dictionary/states/byCode/{code} - * - * @throws RestException - */ - public function getStateByCode($code) - { - return $this->_fetchCstate('', $code); - } - - /** - * Get the list of countries. - * - * The names of the countries will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by country ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $lang Code of the language the label of the countries must be translated to - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of countries - * - * @url GET dictionary/countries - * - * @throws RestException - */ - public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; - $sql .= " WHERE 1 = 1"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $country = new Ccountry($this->db); - if ($country->fetch($obj->rowid) > 0) { - // Translate the name of the country if needed - // and then apply the filter if there is one. - $this->translateLabel($country, $lang, 'Country'); - - if (empty($filter) || stripos($country->label, $filter) !== false) { - $list[] = $this->_cleanObjectDatas($country); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of countries'); - } - - return $list; - } - - /** - * Get country by ID. - * - * @param int $id ID of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/{id} - * - * @throws RestException - */ - public function getCountryByID($id, $lang = '') - { - return $this->_fetchCcountry($id, '', '', $lang); - } - - /** - * Get country by Code. - * - * @param string $code Code of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/byCode/{code} - * - * @throws RestException - */ - public function getCountryByCode($code, $lang = '') - { - return $this->_fetchCcountry('', $code, '', $lang); - } - - /** - * Get country by Iso. - * - * @param string $iso ISO of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/byISO/{iso} - * - * @throws RestException - */ - public function getCountryByISO($iso, $lang = '') - { - return $this->_fetchCcountry('', '', $iso, $lang); - } - - /** - * Get state. - * - * @param int $id ID of state - * @param string $code Code of state - * @return array Array of cleaned object properties - * - * @throws RestException - */ - private function _fetchCstate($id, $code = '') - { - $state = new Cstate($this->db); - - $result = $state->fetch($id, $code); - if ($result < 0) { - throw new RestException(503, 'Error when retrieving state : '.$state->error); - } elseif ($result == 0) { - throw new RestException(404, 'State not found'); - } - - return $this->_cleanObjectDatas($state); - } - - /** - * Get country. - * - * @param int $id ID of country - * @param string $code Code of country - * @param string $iso ISO of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @throws RestException - */ - private function _fetchCcountry($id, $code = '', $iso = '', $lang = '') - { - $country = new Ccountry($this->db); - - $result = $country->fetch($id, $code, $iso); - if ($result < 0) { - throw new RestException(503, 'Error when retrieving country : '.$country->error); - } elseif ($result == 0) { - throw new RestException(404, 'country not found'); - } - - $this->translateLabel($country, $lang, 'Country'); - - return $this->_cleanObjectDatas($country); - } - - /** - * Get the list of delivery times. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Delivery times is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. - * - * @url GET dictionary/availability - * - * @return array [List of availability] - * - * @throws RestException 400 - */ - public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } - - $sql = "SELECT rowid, code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); - - unset($object->error); - unset($object->errors); - - return $object; - } - - /** - * Translate the name of the object to the given language. - * - * @param object $object Object with label to translate - * @param string $lang Code of the language the name of the object must be translated to - * @param string $prefix Prefix for translation key - * - * @return void - */ - private function translateLabel($object, $lang, $prefix = 'Country') - { - if (!empty($lang)) { - // Load the translations if this is a new language. - if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { - global $conf; - $this->translations = new Translate('', $conf); - $this->translations->setDefaultLang($lang); - $this->translations->load('dict'); - } - if ($object->code) { - $key = $prefix.$object->code; - - $translation = $this->translations->trans($key); - if ($translation != $key) { - $object->label = html_entity_decode($translation); - } - } - } - } - - /** - * Get the list of shipment methods. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * - * @return array List of shipment methods - * - * @url GET dictionary/shipment_methods - * - * @throws RestException - */ - public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of events types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of event - * @param string $module To filter on module events - * @param int $active Event's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of events types - * - * @url GET dictionary/event_types - * - * @throws RestException - */ - public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; - $sql .= " WHERE t.active = ".$active; - if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); - } - - return $list; - } - - - /** - * Get the list of Expense Report types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $module To filter on module - * @param int $active Event's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of expense report types - * - * @url GET dictionary/expensereport_types - * - * @throws RestException - */ - public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, label, accountancy_code, active, module, position"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; - $sql .= " WHERE t.active = ".$active; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); - } - - return $list; - } - - - /** - * Get the list of contacts types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of contact - * @param string $module To filter on module contacts - * @param int $active Contact's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of Contacts types - * - * @url GET dictionary/contact_types - * - * @throws RestException - */ - public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; - $sql .= " WHERE t.active = ".$active; - if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of civilities. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $module To filter on module events - * @param int $active Civility is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of civility types - * - * @url GET dictionary/civilities - * - * @throws RestException - */ - public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; - $sql .= " WHERE t.active = ".$active; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of currencies. - * - * @param int $multicurrency Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2} - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of currencies - * - * @url GET dictionary/currencies - * - * @throws RestException - */ - public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - $sql = "SELECT t.code_iso, t.label, t.unicode"; - if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; - $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; - if (!empty($multicurrency)) { - $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; - $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; - } - $sql .= " WHERE t.active = ".$active; - if (!empty($multicurrency)) { - $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; - if (!empty($multicurrency) && $multicurrency != 2) { - $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)"; - } - } - - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of extra fields. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" - * @return array List of extra fields - * - * @url GET extrafields - * - * @throws RestException - */ - public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->admin) { - throw new RestException(401, 'Only an admin user can get list of extrafields'); - } - - if ($type == 'thirdparty') $type = 'societe'; - if ($type == 'contact') $type = 'socpeople'; - - $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; - $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; - $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; - if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - while ($tab = $this->db->fetch_object($resql)) - { - // New usage - $list[$tab->elementtype][$tab->name]['type'] = $tab->type; - $list[$tab->elementtype][$tab->name]['label'] = $tab->label; - $list[$tab->elementtype][$tab->name]['size'] = $tab->size; - $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; - $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; - $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; - $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; - $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; - $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); - $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; - $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; - $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; - $list[$tab->elementtype][$tab->name]['list'] = $tab->list; - } - } - } else { - throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); - } - - if (!count($list)) - { - throw new RestException(404, 'No extrafield found'); - } - - return $list; - } - - - /** - * Get the list of towns. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $zipcode To filter on zipcode - * @param string $town To filter on city name - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of towns - * - * @url GET dictionary/towns - * - * @throws RestException - */ - public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; - $sql .= " AND t.active = ".$active; - if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; - if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of payments terms. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/payment_terms - * - * @return array List of payment terms - * - * @throws RestException 400 - */ - public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of shipping methods. - * - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Shipping methodsm is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/shipping_methods - * - * @return array List of shipping methods - * - * @throws RestException 400 - */ - public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - //$sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of measuring units. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Measuring unit is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of measuring unit - * - * @url GET dictionary/units - * - * @throws RestException - */ - public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - //TODO link with multicurrency module - $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of social networks. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Social network is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of social networks - * - * @url GET dictionary/socialnetworks - * - * @throws RestException - */ - public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - global $conf; - - if (empty($conf->socialnetworks->enabled)) { - throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); - } + private $translations = null; + + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of ordering methods. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')" + * + * @url GET dictionary/ordering_methods + * + * @return array [List of ordering methods] + * + * @throws RestException 400 + */ + public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid, code, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/payment_types + * + * @return array [List of payment types] + * + * @throws RestException 400 + */ + public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of states/provinces. + * + * The names of the states will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by state ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of countries + * + * @url GET dictionary/states + * + * @throws RestException + */ + public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t"; + $sql .= " WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $state = new Cstate($this->db); + if ($state->fetch($obj->rowid) > 0) { + if (empty($filter) || stripos($state->label, $filter) !== false) { + $list[] = $this->_cleanObjectDatas($state); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of states'); + } + + return $list; + } + + /** + * Get state by ID. + * + * @param int $id ID of state + * @return array Array of cleaned object properties + * + * @url GET dictionary/states/{id} + * + * @throws RestException + */ + public function getStateByID($id) + { + return $this->_fetchCstate($id, ''); + } + + /** + * Get state by Code. + * + * @param string $code Code of state + * @return array Array of cleaned object properties + * + * @url GET dictionary/states/byCode/{code} + * + * @throws RestException + */ + public function getStateByCode($code) + { + return $this->_fetchCstate('', $code); + } + + /** + * Get the list of countries. + * + * The names of the countries will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by country ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $lang Code of the language the label of the countries must be translated to + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of countries + * + * @url GET dictionary/countries + * + * @throws RestException + */ + public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql .= " WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $country = new Ccountry($this->db); + if ($country->fetch($obj->rowid) > 0) { + // Translate the name of the country if needed + // and then apply the filter if there is one. + $this->translateLabel($country, $lang, 'Country'); + + if (empty($filter) || stripos($country->label, $filter) !== false) { + $list[] = $this->_cleanObjectDatas($country); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of countries'); + } + + return $list; + } + + /** + * Get country by ID. + * + * @param int $id ID of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/{id} + * + * @throws RestException + */ + public function getCountryByID($id, $lang = '') + { + return $this->_fetchCcountry($id, '', '', $lang); + } + + /** + * Get country by Code. + * + * @param string $code Code of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/byCode/{code} + * + * @throws RestException + */ + public function getCountryByCode($code, $lang = '') + { + return $this->_fetchCcountry('', $code, '', $lang); + } + + /** + * Get country by Iso. + * + * @param string $iso ISO of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/byISO/{iso} + * + * @throws RestException + */ + public function getCountryByISO($iso, $lang = '') + { + return $this->_fetchCcountry('', '', $iso, $lang); + } + + /** + * Get state. + * + * @param int $id ID of state + * @param string $code Code of state + * @return array Array of cleaned object properties + * + * @throws RestException + */ + private function _fetchCstate($id, $code = '') + { + $state = new Cstate($this->db); + + $result = $state->fetch($id, $code); + if ($result < 0) { + throw new RestException(503, 'Error when retrieving state : '.$state->error); + } elseif ($result == 0) { + throw new RestException(404, 'State not found'); + } + + return $this->_cleanObjectDatas($state); + } + + /** + * Get country. + * + * @param int $id ID of country + * @param string $code Code of country + * @param string $iso ISO of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @throws RestException + */ + private function _fetchCcountry($id, $code = '', $iso = '', $lang = '') + { + $country = new Ccountry($this->db); + + $result = $country->fetch($id, $code, $iso); + if ($result < 0) { + throw new RestException(503, 'Error when retrieving country : '.$country->error); + } elseif ($result == 0) { + throw new RestException(404, 'country not found'); + } + + $this->translateLabel($country, $lang, 'Country'); + + return $this->_cleanObjectDatas($country); + } + + /** + * Get the list of delivery times. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Delivery times is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. + * + * @url GET dictionary/availability + * + * @return array [List of availability] + * + * @throws RestException 400 + */ + public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); + + unset($object->error); + unset($object->errors); + + return $object; + } + + /** + * Translate the name of the object to the given language. + * + * @param object $object Object with label to translate + * @param string $lang Code of the language the name of the object must be translated to + * @param string $prefix Prefix for translation key + * + * @return void + */ + private function translateLabel($object, $lang, $prefix = 'Country') + { + if (!empty($lang)) { + // Load the translations if this is a new language. + if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { + global $conf; + $this->translations = new Translate('', $conf); + $this->translations->setDefaultLang($lang); + $this->translations->load('dict'); + } + if ($object->code) { + $key = $prefix.$object->code; + + $translation = $this->translations->trans($key); + if ($translation != $key) { + $object->label = html_entity_decode($translation); + } + } + } + } + + /** + * Get the list of shipment methods. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * + * @return array List of shipment methods + * + * @url GET dictionary/shipment_methods + * + * @throws RestException + */ + public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of events types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of event + * @param string $module To filter on module events + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of events types + * + * @url GET dictionary/event_types + * + * @throws RestException + */ + public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of Expense Report types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of expense report types + * + * @url GET dictionary/expensereport_types + * + * @throws RestException + */ + public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, label, accountancy_code, active, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of contacts types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of contact + * @param string $module To filter on module contacts + * @param int $active Contact's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of Contacts types + * + * @url GET dictionary/contact_types + * + * @throws RestException + */ + public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of civilities. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module events + * @param int $active Civility is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of civility types + * + * @url GET dictionary/civilities + * + * @throws RestException + */ + public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of currencies. + * + * @param int $multicurrency Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2} + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of currencies + * + * @url GET dictionary/currencies + * + * @throws RestException + */ + public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + $sql = "SELECT t.code_iso, t.label, t.unicode"; + if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; + $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; + if (!empty($multicurrency)) { + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; + } + $sql .= " WHERE t.active = ".$active; + if (!empty($multicurrency)) { + $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; + if (!empty($multicurrency) && $multicurrency != 2) { + $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)"; + } + } + + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of extra fields. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" + * @return array List of extra fields + * + * @url GET extrafields + * + * @throws RestException + */ + public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->admin) { + throw new RestException(401, 'Only an admin user can get list of extrafields'); + } + + if ($type == 'thirdparty') $type = 'societe'; + if ($type == 'contact') $type = 'socpeople'; + + $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; + $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; + if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + while ($tab = $this->db->fetch_object($resql)) + { + // New usage + $list[$tab->elementtype][$tab->name]['type'] = $tab->type; + $list[$tab->elementtype][$tab->name]['label'] = $tab->label; + $list[$tab->elementtype][$tab->name]['size'] = $tab->size; + $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; + $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; + $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; + $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; + $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; + $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); + $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; + $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; + $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; + $list[$tab->elementtype][$tab->name]['list'] = $tab->list; + } + } + } else { + throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); + } + + if (!count($list)) + { + throw new RestException(404, 'No extrafield found'); + } + + return $list; + } + + + /** + * Get the list of towns. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $zipcode To filter on zipcode + * @param string $town To filter on city name + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of towns + * + * @url GET dictionary/towns + * + * @throws RestException + */ + public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql .= " AND t.active = ".$active; + if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; + if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments terms. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/payment_terms + * + * @return array List of payment terms + * + * @throws RestException 400 + */ + public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of shipping methods. + * + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Shipping methodsm is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/shipping_methods + * + * @return array List of shipping methods + * + * @throws RestException 400 + */ + public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + //$sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of measuring units. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Measuring unit is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of measuring unit + * + * @url GET dictionary/units + * + * @throws RestException + */ + public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + //TODO link with multicurrency module + $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of social networks. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Social network is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of social networks + * + * @url GET dictionary/socialnetworks + * + * @throws RestException + */ + public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + global $conf; + + if (empty($conf->socialnetworks->enabled)) { + throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); + } $list = array(); - //TODO link with multicurrency module - $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets categories. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket categories - * - * @url GET dictionary/ticket_categories - * - * @throws RestException - */ - public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets severity. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket severities - * - * @url GET dictionary/ticket_severities - * - * @throws RestException - */ - public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, color, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket types - * - * @url GET dictionary/ticket_types - * - * @throws RestException - */ - public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; - $sql .= " WHERE t.active = ".(int) $active; - // if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; - // if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql .= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get properties of company - * - * @url GET /company - * - * @return array|mixed Data without useless information - * - */ - public function getCompany() - { - global $mysoc; - - return $this->_cleanObjectDatas($mysoc); - } - - - /** - * Get value of a setup variables - * - * Note that conf variables that stores security key or password hashes can't be loaded with API. - * - * @param string $constantname Name of conf variable to get - * @return array|mixed Data without useless information - * - * @url GET conf/{constantname} - * - * @throws RestException 403 Forbidden - * @throws RestException 404 Error Bad or unknown value for constantname - */ - public function getConf($constantname) - { - global $conf; - - if (!DolibarrApiAccess::$user->admin - && (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) { - throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ'); - } - - if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { - throw new RestException(404, 'Error Bad or unknown value for constantname'); - } - if (isASecretKey($constantname)) { - throw new RestException(403, 'Forbidden. This parameter cant be read with APIs'); - } - - return $conf->global->$constantname; - } - - /** - * Do a test of integrity for files and setup. - * - * @param string $target Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr. - * @return array Result of file and setup integrity check - * - * @url GET checkintegrity - * - * @throws RestException 404 Signature file not found - * @throws RestException 500 Technical error - * @throws RestException 503 Forbidden - */ - public function getCheckIntegrity($target) - { - global $langs, $conf; - - if (!DolibarrApiAccess::$user->admin - && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) - { - throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); - } - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - - $langs->load("admin"); - - $outexpectedchecksum = ''; - $outcurrentchecksum = ''; - - // Modified or missing files - $file_list = array('missing' => array(), 'updated' => array()); - - // Local file to compare to - $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; - $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; - // Remote file to compare to - $xmlremote = ($target == 'default' ? '' : $target); - if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; - $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; - if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; - if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; - - if ($target == 'local') - { - if (dol_is_file($xmlfile)) - { - $xml = simplexml_load_file($xmlfile); - } else { - throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); - } - } else { - $xmlarray = getURLContent($xmlremote); - - // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) - if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') - { - $xmlfile = $xmlarray['content']; - //print "xmlfilestart".$xmlfile."endxmlfile"; - $xml = simplexml_load_string($xmlfile); - } else { - $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; - throw new RestException(500, $errormsg); - } - } - - - - if ($xml) - { - $checksumconcat = array(); - $file_list = array(); - $out = ''; - - // Forced constants - if (is_object($xml->dolibarr_constants[0])) - { - $out .= load_fiche_titre($langs->trans("ForcedConstants")); - - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - - $i = 0; - foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement - { - $constname = $constant['name']; - $constvalue = (string) $constant; - $constvalue = (empty($constvalue) ? '0' : $constvalue); - // Value found - $value = ''; - if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; - $valueforchecksum = (empty($value) ? '0' : $value); - - $checksumconcat[] = $valueforchecksum; - - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - - if ($i == 0) - { - $out .= ''; - } - $out .= '
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - } - - // Scan htdocs - if (is_object($xml->dolibarr_htdocs_dir[0])) - { - //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; - $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); - - // Defined qualified files (must be same than into generate_filelist_xml.php) - $regextoinclude = '\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|bak|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$'; - $regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs - $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); - - // Fill file_list with files in signature, new files, modified files - $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list - // Complete with list of new files - foreach ($scanfiles as $keyfile => $valfile) - { - $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); - if (!in_array($tmprelativefilename, $file_list['insignature'])) - { - $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file - $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); - } - } - - // Files missings - $out .= load_fiche_titre($langs->trans("FilesMissing")); - - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); - if (is_array($tmpfilelist) && count($tmpfilelist)) - { - $i = 0; - foreach ($tmpfilelist as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - - // Files modified - $out .= load_fiche_titre($langs->trans("FilesModified")); - - $totalsize = 0; - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); - if (is_array($tmpfilelist2) && count($tmpfilelist2)) - { - $i = 0; - foreach ($tmpfilelist2 as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); - $totalsize += $size; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - - // Files added - $out .= load_fiche_titre($langs->trans("FilesAdded")); - - $totalsize = 0; - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); - if (is_array($tmpfilelist3) && count($tmpfilelist3)) - { - $i = 0; - foreach ($tmpfilelist3 as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); - $totalsize += $size; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; - $out .= '
'; - - - // Show warning - if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3)) - { - //setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs'); - } else { - //setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings'); - } - } else { - throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile); - } - - - // Scan scripts - - - asort($checksumconcat); // Sort list of checksum - //var_dump($checksumconcat); - $checksumget = md5(join(',', $checksumconcat)); - $checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum); - - $outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown")); - if ($checksumget == $checksumtoget) - { - if (count($file_list['added'])) - { - $resultcode = 'warning'; - $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; - //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; - $outcurrentchecksum = $checksumget; - } else { - $resultcode = 'ok'; - $resultcomment = 'Success'; - //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; - } - } else { - $resultcode = 'error'; - $resultcomment = 'Error'; - //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; - } - } else { - throw new RestException(404, 'No signature file known'); - } - - return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out); - } + //TODO link with multicurrency module + $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets categories. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket categories + * + * @url GET dictionary/ticket_categories + * + * @throws RestException + */ + public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets severity. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket severities + * + * @url GET dictionary/ticket_severities + * + * @throws RestException + */ + public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, color, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket types + * + * @url GET dictionary/ticket_types + * + * @throws RestException + */ + public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; + $sql .= " WHERE t.active = ".(int) $active; + // if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + // if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get properties of company + * + * @url GET /company + * + * @return array|mixed Data without useless information + * + */ + public function getCompany() + { + global $mysoc; + + return $this->_cleanObjectDatas($mysoc); + } + + + /** + * Get value of a setup variables + * + * Note that conf variables that stores security key or password hashes can't be loaded with API. + * + * @param string $constantname Name of conf variable to get + * @return array|mixed Data without useless information + * + * @url GET conf/{constantname} + * + * @throws RestException 403 Forbidden + * @throws RestException 404 Error Bad or unknown value for constantname + */ + public function getConf($constantname) + { + global $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) { + throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ'); + } + + if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { + throw new RestException(404, 'Error Bad or unknown value for constantname'); + } + if (isASecretKey($constantname)) { + throw new RestException(403, 'Forbidden. This parameter cant be read with APIs'); + } + + return $conf->global->$constantname; + } + + /** + * Do a test of integrity for files and setup. + * + * @param string $target Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr. + * @return array Result of file and setup integrity check + * + * @url GET checkintegrity + * + * @throws RestException 404 Signature file not found + * @throws RestException 500 Technical error + * @throws RestException 503 Forbidden + */ + public function getCheckIntegrity($target) + { + global $langs, $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) + { + throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); + } + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + $langs->load("admin"); + + $outexpectedchecksum = ''; + $outcurrentchecksum = ''; + + // Modified or missing files + $file_list = array('missing' => array(), 'updated' => array()); + + // Local file to compare to + $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; + $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; + // Remote file to compare to + $xmlremote = ($target == 'default' ? '' : $target); + if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; + $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; + if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; + if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; + + if ($target == 'local') + { + if (dol_is_file($xmlfile)) + { + $xml = simplexml_load_file($xmlfile); + } else { + throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); + } + } else { + $xmlarray = getURLContent($xmlremote); + + // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) + if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') + { + $xmlfile = $xmlarray['content']; + //print "xmlfilestart".$xmlfile."endxmlfile"; + $xml = simplexml_load_string($xmlfile); + } else { + $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + throw new RestException(500, $errormsg); + } + } + + + + if ($xml) + { + $checksumconcat = array(); + $file_list = array(); + $out = ''; + + // Forced constants + if (is_object($xml->dolibarr_constants[0])) + { + $out .= load_fiche_titre($langs->trans("ForcedConstants")); + + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + + $i = 0; + foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement + { + $constname = $constant['name']; + $constvalue = (string) $constant; + $constvalue = (empty($constvalue) ? '0' : $constvalue); + // Value found + $value = ''; + if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; + $valueforchecksum = (empty($value) ? '0' : $value); + + $checksumconcat[] = $valueforchecksum; + + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + + if ($i == 0) + { + $out .= ''; + } + $out .= '
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + } + + // Scan htdocs + if (is_object($xml->dolibarr_htdocs_dir[0])) + { + //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; + $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); + + // Defined qualified files (must be same than into generate_filelist_xml.php) + $regextoinclude = '\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|bak|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$'; + $regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs + $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); + + // Fill file_list with files in signature, new files, modified files + $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list + // Complete with list of new files + foreach ($scanfiles as $keyfile => $valfile) + { + $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); + if (!in_array($tmprelativefilename, $file_list['insignature'])) + { + $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file + $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); + } + } + + // Files missings + $out .= load_fiche_titre($langs->trans("FilesMissing")); + + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); + if (is_array($tmpfilelist) && count($tmpfilelist)) + { + $i = 0; + foreach ($tmpfilelist as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + + // Files modified + $out .= load_fiche_titre($langs->trans("FilesModified")); + + $totalsize = 0; + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); + if (is_array($tmpfilelist2) && count($tmpfilelist2)) + { + $i = 0; + foreach ($tmpfilelist2 as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); + $totalsize += $size; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + + // Files added + $out .= load_fiche_titre($langs->trans("FilesAdded")); + + $totalsize = 0; + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); + if (is_array($tmpfilelist3) && count($tmpfilelist3)) + { + $i = 0; + foreach ($tmpfilelist3 as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); + $totalsize += $size; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; + $out .= '
'; + + + // Show warning + if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3)) + { + //setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs'); + } else { + //setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings'); + } + } else { + throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile); + } + + + // Scan scripts + + + asort($checksumconcat); // Sort list of checksum + //var_dump($checksumconcat); + $checksumget = md5(join(',', $checksumconcat)); + $checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum); + + $outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown")); + if ($checksumget == $checksumtoget) + { + if (count($file_list['added'])) + { + $resultcode = 'warning'; + $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; + //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; + $outcurrentchecksum = $checksumget; + } else { + $resultcode = 'ok'; + $resultcomment = 'Success'; + //$outcurrentchecksum = ''.$checksumget.''; + $outcurrentchecksum = $checksumget; + } + } else { + $resultcode = 'error'; + $resultcomment = 'Error'; + //$outcurrentchecksum = ''.$checksumget.''; + $outcurrentchecksum = $checksumget; + } + } else { + throw new RestException(404, 'No signature file known'); + } + + return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out); + } } diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php index d9bfea71510..ef3ea4ce975 100644 --- a/htdocs/asset/list.php +++ b/htdocs/asset/list.php @@ -386,7 +386,7 @@ foreach ($object->fields as $key => $val) if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index 121517b2544..7687ab250ac 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -85,7 +85,7 @@ $search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); + if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); } // List of fields to search into when doing a "search in all" @@ -311,6 +311,7 @@ foreach ($search as $key => $val) } if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); } + if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -485,7 +486,7 @@ foreach ($object->fields as $key => $val) if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 2a675cc60e1..a7bb62c9901 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -113,7 +113,7 @@ if ($conf->global->PRODUCT_USE_UNITS) { $coldisplay++; print ''; - print $form->selectUnits(empty($line->fk_unit) ? $conf->global->PRODUCT_USE_UNITS : $line->fk_unit, "units"); + // print $form->selectUnits(empty($line->fk_unit) ? $conf->global->PRODUCT_USE_UNITS : $line->fk_unit, "units"); print ''; } diff --git a/htdocs/bom/tpl/objectline_edit.tpl.php b/htdocs/bom/tpl/objectline_edit.tpl.php index 3840f495dea..6954e657db9 100644 --- a/htdocs/bom/tpl/objectline_edit.tpl.php +++ b/htdocs/bom/tpl/objectline_edit.tpl.php @@ -112,7 +112,7 @@ if ($conf->global->PRODUCT_USE_UNITS) { $coldisplay++; print ''; - print $form->selectUnits($line->fk_unit, "units"); + // print $form->selectUnits($line->fk_unit, "units"); print ''; } diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index c5ee3870272..ecaf9117aae 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -82,7 +82,7 @@ print ''; if ($conf->global->PRODUCT_USE_UNITS) { print ''; - $label = $line->getLabelOfUnit('short'); + $label = $tmpproduct->getLabelOfUnit('long'); if ($label !== '') { print $langs->trans($label); } @@ -111,21 +111,21 @@ print ''; if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') { print ''; $coldisplay++; - if (($line->info_bits & 2) == 2 || !empty($disableedit)) { - } else { - print 'id.'">'.img_edit().''; - } - print ''; + if (($line->info_bits & 2) == 2 || !empty($disableedit)) { + } else { + print 'id.'">'.img_edit().''; + } + print ''; - print ''; - $coldisplay++; - if (($line->fk_prev_id == null) && empty($disableremove)) { - //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation - print 'id.'">'; - print img_delete(); - print ''; - } - print ''; + print ''; + $coldisplay++; + if (($line->fk_prev_id == null) && empty($disableremove)) { + //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation + print 'id.'">'; + print img_delete(); + print ''; + } + print ''; if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) { print ''; @@ -146,14 +146,14 @@ if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') { $coldisplay++; } } else { - print ''; - $coldisplay = $coldisplay + 3; + print ''; + $coldisplay = $coldisplay + 3; } if ($action == 'selectlines') { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } print ''; diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index e1dc53ed6e8..d9d12c5d84e 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -141,7 +141,7 @@ for ($i = 0; $i < $nbtoshow; $i++) -
+
trans("Amount"); ?> diff --git a/htdocs/cashdesk/tpl/validation1.tpl.php b/htdocs/cashdesk/tpl/validation1.tpl.php index 0434473d359..cc558cca058 100644 --- a/htdocs/cashdesk/tpl/validation1.tpl.php +++ b/htdocs/cashdesk/tpl/validation1.tpl.php @@ -97,7 +97,7 @@ if ($obj_facturation->amountReturned()) { - +

load("categories"); $id = GETPOST('id', 'int'); -$ref = GETPOST('ref'); -$type = GETPOST('type'); +$ref = GETPOST('ref', 'alphanohtml'); +$type = GETPOST('type', 'alphanohtml'); $action = (GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'edit'); $confirm = GETPOST('confirm'); $cancel = GETPOST('cancel', 'alpha'); $socid = GETPOST('socid', 'int'); -$label = GETPOST('label'); -$description = GETPOST('description'); -$color = GETPOST('color', 'alpha'); +$label = GETPOST('label', 'alphanohtml'); +$description = GETPOST('description', 'restricthtml'); +$color = preg_replace('/[^0-9a-f#]/i', '', GETPOST('color', 'alphanohtml')); $visible = GETPOST('visible'); $parent = GETPOST('parent'); diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index dc0a980a6f8..866a98fd816 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -44,8 +44,8 @@ $confirm = GETPOST('confirm'); if ($id == '' && $label == '') { - dol_print_error('', 'Missing parameter id'); - exit(); + dol_print_error('', 'Missing parameter id'); + exit(); } // Security check @@ -70,34 +70,34 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) { - if ($object->id) { - $file = $_FILES['userfile']; - if (is_array($file['name']) && count($file['name']) > 0) - { - foreach ($file['name'] as $i => $name) - { - if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) - { - setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); - unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); - } - } - } + if ($object->id) { + $file = $_FILES['userfile']; + if (is_array($file['name']) && count($file['name']) > 0) + { + foreach ($file['name'] as $i => $name) + { + if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) + { + setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); + unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); + } + } + } - if (!empty($file['tmp_name'])) { - $object->add_photo($upload_dir, $file); - } - } + if (!empty($file['tmp_name'])) { + $object->add_photo($upload_dir, $file); + } + } } if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) { - $object->delete_photo($upload_dir."/".$_GET["file"]); + $object->delete_photo($upload_dir."/".$_GET["file"]); } if ($action == 'addthumb' && $_GET["file"]) { - $object->addThumbs($upload_dir."/".$_GET["file"]); + $object->addThumbs($upload_dir."/".$_GET["file"]); } @@ -126,7 +126,7 @@ if ($object->id) $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref .= $way."
\n"; + $morehtmlref .= $way."
\n"; } $morehtmlref .= ''; @@ -137,7 +137,7 @@ if ($object->id) */ if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); } print '
'; @@ -159,7 +159,7 @@ if ($object->id) print ''; print "\n"; - print ''; + print ''; dol_fiche_end(); @@ -213,62 +213,62 @@ if ($object->id) if (is_array($listofphoto) && count($listofphoto)) { - print '
'; - print ''; + print '
'; + print '
'; - foreach ($listofphoto as $key => $obj) - { - $nbphoto++; + foreach ($listofphoto as $key => $obj) + { + $nbphoto++; - if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print ''; - if ($nbbyrow) print ''; + if ($nbbyrow) print ''; - if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; - } + // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites + if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) + { + print ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; + } + if ($user->rights->categorie->creer) + { + print ''; + print img_delete().''; + } + if ($nbbyrow) print ''; + if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; + } - // Ferme tableau - while ($nbphoto % $nbbyrow) - { - print ''; - $nbphoto++; - } + // Ferme tableau + while ($nbphoto % $nbbyrow) + { + print ''; + $nbphoto++; + } - print '
'; + if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '
'; - print ''; + print ''; - // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine - if ($obj['photo_vignette']) - { - $filename = $obj['photo_vignette']; - } else { - $filename = $obj['photo']; - } + // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine + if ($obj['photo_vignette']) + { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } - // Nom affiche - $viewfilename = $obj['photo']; + // Nom affiche + $viewfilename = $obj['photo']; - // Taille de l'image - $object->get_image_size($dir.$filename); - $imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth; - $imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight; + // Taille de l'image + $object->get_image_size($dir.$filename); + $imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth; + $imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight; - print ''; + print ''; - print ''; - print '
'.$viewfilename; - print '
'; + print ''; + print '
'.$viewfilename; + print '
'; - // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites - if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) - { - print ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; - } - if ($user->rights->categorie->creer) - { - print ''; - print img_delete().''; - } - if ($nbbyrow) print '
  
'; + print ''; } if ($nbphoto < 1) @@ -277,7 +277,7 @@ if ($object->id) } } } else { - print $langs->trans("ErrorUnknown"); + print $langs->trans("ErrorUnknown"); } // End of page diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index f5755a697ca..f4e073c4e1c 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -83,43 +83,43 @@ $cancel != $langs->trans("Cancel") && $current_lang = $langs->getDefaultLang(); // check parameters - $forcelangprod = GETPOST('forcelangprod', 'alpha'); - $libelle = GETPOST('libelle', 'alpha'); - $desc = GETPOST('desc', 'restricthtml'); + $forcelangprod = GETPOST('forcelangprod', 'alpha'); + $libelle = GETPOST('libelle', 'alpha'); + $desc = GETPOST('desc', 'restricthtml'); - if (empty($forcelangprod)) { - $error++; - $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation')); - } + if (empty($forcelangprod)) { + $error++; + $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation')); + } - if (!$error) { - if (empty($libelle)) { - $error++; - $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); - } + if (!$error) { + if (empty($libelle)) { + $error++; + $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + } - if (!$error) { - // update de l'objet - if ($forcelangprod == $current_lang) { - $object->label = $libelle; - $object->description = dol_htmlcleanlastbr($desc); - } else { - $object->multilangs[$forcelangprod]["label"] = $libelle; - $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc); - } + if (!$error) { + // update de l'objet + if ($forcelangprod == $current_lang) { + $object->label = $libelle; + $object->description = dol_htmlcleanlastbr($desc); + } else { + $object->multilangs[$forcelangprod]["label"] = $libelle; + $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc); + } - // sauvegarde en base - $res = $object->setMultiLangs($user); - if ($res < 0) $error++; - } - } + // sauvegarde en base + $res = $object->setMultiLangs($user); + if ($res < 0) $error++; + } + } - if ($error) { - $action = 'add'; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - $action = ''; - } + if ($error) { + $action = 'add'; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + $action = ''; + } } // Validation de l'edition @@ -132,13 +132,13 @@ $cancel != $langs->trans("Cancel") && foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet { - $libelle = GETPOST('libelle-'.$key, 'alpha'); - $desc = GETPOST('desc-'.$key); + $libelle = GETPOST('libelle-'.$key, 'alpha'); + $desc = GETPOST('desc-'.$key); - if (empty($libelle)) { - $error++; - $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); - } + if (empty($libelle)) { + $error++; + $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + } if ($key == $current_lang) { $object->label = $libelle; @@ -149,17 +149,17 @@ $cancel != $langs->trans("Cancel") && } } - if (!$error) { - $res = $object->setMultiLangs($user); - if ($res < 0) $error++; - } + if (!$error) { + $res = $object->setMultiLangs($user); + if ($res < 0) $error++; + } - if ($error) { - $action = 'edit'; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - $action = ''; - } + if ($error) { + $action = 'edit'; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + $action = ''; + } } @@ -181,10 +181,10 @@ $head = categories_prepare_head($object, $type); $cnt_trans = 0; if (!empty($object->multilangs)) { - foreach ($object->multilangs as $key => $value) - { - $cnt_trans++; - } + foreach ($object->multilangs as $key => $value) + { + $cnt_trans++; + } } dol_fiche_head($head, 'translation', $langs->trans($title), -1, 'category'); @@ -195,7 +195,7 @@ $object->ref = $object->label; $morehtmlref = '

'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref .= $way."
\n"; + $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; @@ -238,11 +238,11 @@ print "\n
\n"; if ($action == '') { - if ($user->rights->produit->creer || $user->rights->service->creer) - { - print ''.$langs->trans('Add').''; - if ($cnt_trans > 0) print ''.$langs->trans('Update').''; - } + if ($user->rights->produit->creer || $user->rights->service->creer) + { + print ''.$langs->trans('Add').''; + if ($cnt_trans > 0) print ''.$langs->trans('Update').''; + } } print "\n
\n"; @@ -258,20 +258,20 @@ if ($action == 'edit') print ''; print ''; print ''; - print ''; + print ''; if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - print "
".$langs->trans('Language_'.$key)." :
"; + print "
".$langs->trans('Language_'.$key)." :
"; print ''; // Label - $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); + $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); print ''; // Desc - $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); + $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); print ''; + $html .= ''; + $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour'); + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + } + } else { + $html .= ''; + $html .= ''; + $html .= ''; + } + $html .= '
'.$langs->trans('Label').'
'.$langs->trans('Description').''; $doleditor = new DolEditor("desc-$key", $desc, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); @@ -293,20 +293,20 @@ if ($action == 'edit') print ''; } elseif ($action != 'add') { - if ($cnt_trans) print '
'; + if ($cnt_trans) print '
'; - if (!empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - $s = picto_from_langcode($key); + $s = picto_from_langcode($key); print ''; print ''; print ''; print ''; if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) { - print ''; + print ''; } print '
'.($s ? $s.' ' : '')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '').'
'.$langs->trans('Label').''.$object->multilangs[$key]["label"].'
'.$langs->trans('Description').''.$object->multilangs[$key]["description"].'
'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
'; } @@ -329,11 +329,11 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 3c8ed94c2bf..5b50958591f 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -71,8 +71,6 @@ $offsetunit = GETPOST('offsetunittype_duration', 'aZ09'); $remindertype = GETPOST('selectremindertype', 'aZ09'); $modelmail = GETPOST('actioncommsendmodel_mail', 'int'); -//var_dump($_POST); exit; - $datep = dol_mktime($fulldayevent ? '00' : $aphour, $fulldayevent ? '00' : $apmin, 0, GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int')); $datef = dol_mktime($fulldayevent ? '23' : $p2hour, $fulldayevent ? '59' : $p2min, $fulldayevent ? '59' : '0', GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int')); @@ -111,8 +109,6 @@ if ($id > 0 && $action != 'add') { // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -//var_dump($_POST); - // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('actioncard', 'globalcard')); @@ -144,7 +140,7 @@ if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') { if ($val['id'] == $idtoremove || $val['id'] == -1) unset($tmpassigneduserids[$key]); } - //var_dump($_POST['removedassigned']);exit; + $_SESSION['assignedtouser'] = json_encode($tmpassigneduserids); $donotclearsession = 1; if ($action == 'add') $action = 'create'; @@ -393,7 +389,7 @@ if (empty($reshook) && $action == 'add') $moreparam = ''; if ($user->id != $object->userownerid) $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view. - //Create reminders + // Create reminders if ($addreminder == 'on'){ $actionCommReminder = new ActionCommReminder($db); @@ -1068,49 +1064,48 @@ if ($action == 'create') // Location if (empty($conf->global->AGENDA_DISABLE_LOCATION)) { - print ''; + print ''; } // Assigned to print ''; // Done by if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) { print ''; } if ($conf->categorie->enabled) { // Categories - print '"; } @@ -1126,8 +1121,7 @@ if ($action == 'create') { // Related company print ''; } @@ -1161,7 +1156,7 @@ if ($action == 'create') print ''; // Date - print '"; - // Statut - print "\n"; + // Status + print '\n"; print "\n"; $i++; diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index d7b5773e1c2..56b23722a74 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -1543,6 +1543,7 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprin $contactstatic = new Contact($db); $out .= ''; + $out .= ''; if ($objcon && get_class($objcon) == 'Contact' && (is_null($filterobj) || get_class($filterobj) == 'Societe')) { diff --git a/htdocs/core/lib/ecm.lib.php b/htdocs/core/lib/ecm.lib.php index 3b0cef1a809..1f22e464358 100644 --- a/htdocs/core/lib/ecm.lib.php +++ b/htdocs/core/lib/ecm.lib.php @@ -146,30 +146,30 @@ function ecm_prepare_head_fm($object) */ function ecm_admin_prepare_head() { - global $langs, $conf; - $langs->load("ecm"); + global $langs, $conf; + $langs->load("ecm"); - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT."/admin/ecm.php"; - $head[$h][1] = $langs->trans("Setup"); - $head[$h][2] = 'ecm'; - $h++; + $head[$h][0] = DOL_URL_ROOT."/admin/ecm.php"; + $head[$h][1] = $langs->trans("Setup"); + $head[$h][2] = 'ecm'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsEcmFiles"); - $head[$h][2] = 'attributes_ecm_files'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsEcmFiles"); + $head[$h][2] = 'attributes_ecm_files'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories"); - $head[$h][2] = 'attributes_ecm_directories'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories"); + $head[$h][2] = 'attributes_ecm_directories'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin'); - complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove'); - return $head; + return $head; } diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index 7f2fd4ce70d..d926e6105a1 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -1506,9 +1506,10 @@ function dol_init_file_process($pathtoscan = '', $trackid = '') * @param string $link Link to add (to add a link instead of a file) * @param string $trackid Track id (used to prefix name of session vars to avoid conflict) * @param int $generatethumbs 1=Generate also thumbs for uploaded image files + * @param Object $object Object used to set 'src_object_*' fields * @return int <=0 if KO, >0 if OK */ -function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1) +function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesession = 0, $varfiles = 'addedfile', $savingdocmask = '', $link = null, $trackid = '', $generatethumbs = 1, $object = null) { global $db, $user, $conf, $langs; @@ -1533,7 +1534,7 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess $nbok = 0; for ($i = 0; $i < $nbfile; $i++) { - if (empty($TFile['name'][$i])) continue; // For example, when submitting a form with no file name + if (empty($TFile['name'][$i])) continue; // For example, when submitting a form with no file name // Define $destfull (path to file including filename) and $destfile (only filename) $destfull = $upload_dir."/".$TFile['name'][$i]; @@ -1602,7 +1603,7 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess // Update index table of files (llx_ecm_files) if ($donotupdatesession == 1) { - $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', 0); + $result = addFileIntoDatabaseIndex($upload_dir, basename($destfile).($resupload == 2 ? '.noexe' : ''), $TFile['name'][$i], 'uploaded', 0, $object); if ($result < 0) { if ($allowoverwrite) { @@ -1718,9 +1719,10 @@ function dol_remove_file_process($filenb, $donotupdatesession = 0, $donotdeletef * @param string $fullpathorig Full path of origin for file (can be '') * @param string $mode How file was created ('uploaded', 'generated', ...) * @param int $setsharekey Set also the share key + * @param Object $object Object used to set 'src_object_*' fields * @return int <0 if KO, 0 if nothing done, >0 if OK */ -function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0) +function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uploaded', $setsharekey = 0, $object = null) { global $db, $user; @@ -1743,6 +1745,12 @@ function addFileIntoDatabaseIndex($dir, $file, $fullpathorig = '', $mode = 'uplo $ecmfile->gen_or_uploaded = $mode; $ecmfile->description = ''; // indexed content $ecmfile->keyword = ''; // keyword content + + if (is_object($object) && $object->id > 0) { + $ecmfile->src_object_id = $object->id; + $ecmfile->src_object_type = $object->table_element; + } + if ($setsharekey) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -2053,7 +2061,7 @@ function dol_uncompress($inputfile, $outputdir) for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/\.\./', $zip->getNameIndex($i))) { dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING); - continue; // Discard the file + continue; // Discard the file } $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i))); } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index bdd6b0c976d..00f1f537ac2 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -84,8 +84,8 @@ function getEntity($element, $shared = 1, $currentobject = null) // fix different element names (France to English) switch ($element) { - case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php" - case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php" + case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php" + case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php" } if (is_object($mc)) @@ -664,8 +664,7 @@ function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = } break; case 'restricthtml': // Recommended for most html textarea - $out = dol_string_onlythesehtmltags($out, 0); - // TODO We can also remove all javascripts reference + $out = dol_string_onlythesehtmltags($out, 0, 1, 1); break; case 'custom': if (empty($filter)) return 'BadFourthParameterForGETPOST'; @@ -1001,17 +1000,25 @@ function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '') /** - * Clean a string from all non printable ascii chars (0x00-0x1F and 0x7F). It removes also CR-LF + * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars. - * + * Note, for information: UTF8 on 1 byte are: \x00-\7F + * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf + * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf + * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf * @param string $str String to clean + * @param int $removetabcrlf Remove also CR-LF * @return string Cleaned string * * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial() */ -function dol_string_nounprintableascii($str) +function dol_string_nounprintableascii($str, $removetabcrlf = 1) { - return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); + if ($removetabcrlf) { + return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace + } else { + return preg_replace('/[\x00-\x08\x11-\x12\x14-\x1F\x7F]/u', '', $str); // /u operator should make UTF8 valid characters being ignored so are not included into the replace + } } @@ -1209,6 +1216,38 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = } } +/** + * Return HTML code to output a button to open a dialog popup box. + * Such buttons must be included inside a HTML form. + * + * @param string $name A name for the html component + * @param string $label Label of button + * @param string $buttonstring button string + * @param string $url Url to open + * @param string $disabled Disabled text + * @return string HTML component with button + */ +function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '') +{ + //print ''; + $out = ''.$buttonstring.''; + $out .= ''; + return $out; +} /** * Show tab header of a card @@ -1224,6 +1263,7 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page * @return void + * @deprecated Use print dol_get_fiche_head() instead */ function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '') { @@ -1371,7 +1411,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab $tabsname = $moretabssuffix; if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); } $out .= '
'; - $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; // Do not use "reposition" class in the "More". + $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; // Do not use "reposition" class in the "More". $out .= '
'; $out .= $outmore; $out .= '
'; @@ -1382,7 +1422,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab $out .= "$('#moretabs".$tabsname."').mouseenter( function() { var x = this.offsetLeft, y = this.offsetTop; console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth); - if ((window.innerWidth - x) < ".($widthofpopup+10).") { + if ((window.innerWidth - x) < ".($widthofpopup + 10).") { $('#moretabsList".$tabsname."').css('".$right."','8px'); } $('#moretabsList".$tabsname."').css('".$left."','auto'); @@ -1489,8 +1529,9 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]); $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5); if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1; - if ($showimage) $morehtmlleft .= '
'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'
'; - else { + if ($showimage) { + $morehtmlleft .= '
'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'
'; + } else { if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) { $nophoto = ''; $morehtmlleft .= '
'; @@ -1572,14 +1613,14 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi if ($pdfexists && !$error) { - $heightforphotref = 70; + $heightforphotref = 80; if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; // If the preview file is found if (file_exists($fileimage)) { - $phototoshow = '
'; + $phototoshow = '
'; $phototoshow .= ''; - $phototoshow .= '
'; + $phototoshow .= '
'; } } } elseif (!$phototoshow) @@ -2011,15 +2052,13 @@ function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlang /** * Return an array with locale date info. - * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows - * WARNING: This function always use PHP server timezone to return locale informations !!! - * Usage must be avoid. - * FIXME: Replace this with PHP date function and a parameter $gm + * WARNING: This function use PHP server timezone by default to return locale informations. + * Be aware to add the third parameter to "UTC" if you need to work on UTC. * * @param int $timestamp Timestamp - * @param boolean $fast Fast mode + * @param boolean $fast Fast mode. deprecated. + * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'Europe/Paris' or '+0200' to force timezone. * @return array Array of informations - * If no fast mode: * 'seconds' => $secs, * 'minutes' => $min, * 'hours' => $hour, @@ -2027,34 +2066,42 @@ function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlang * 'wday' => $dow, 0=sunday, 6=saturday * 'mon' => $month, * 'year' => $year, - * 'yday' => floor($secsInYear/$_day_power), - * 'weekday' => gmdate('l',$_day_power*(3+$dow)), - * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), - * If fast mode: - * 'seconds' => $secs, - * 'minutes' => $min, - * 'hours' => $hour, - * 'mday' => $day, - * 'mon' => $month, - * 'year' => $year, - * 'yday' => floor($secsInYear/$_day_power), - * 'leap' => $leaf, - * 'ndays' => $ndays + * 'yday' => floor($secsInYear/$_day_power) + * '0' => original timestamp * @see dol_print_date(), dol_stringtotime(), dol_mktime() */ -function dol_getdate($timestamp, $fast = false) +function dol_getdate($timestamp, $fast = false, $forcetimezone = '') { global $conf; - $usealternatemethod = false; - if ($timestamp <= 0) $usealternatemethod = true; // <= 1970 - if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038 - - if ($usealternatemethod) - { - $arrayinfo = adodb_getdate($timestamp, $fast); + if (empty($conf->global->MAIN_USE_OLD_FUNCTIONS_FOR_GETDATE)) { + //$datetimeobj = new DateTime('@'.$timestamp); + $datetimeobj = new DateTime(); + $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone + if ($forcetimezone) $datetimeobj->setTimezone(new DateTimeZone($forcetimezone)); // (add timezone relative to the date entered) + $arrayinfo = array( + 'year'=>((int) date_format($datetimeobj, 'Y')), + 'mon'=>((int) date_format($datetimeobj, 'm')), + 'mday'=>((int) date_format($datetimeobj, 'd')), + 'wday'=>((int) date_format($datetimeobj, 'w')), + 'yday'=>((int) date_format($datetimeobj, 'z')), + 'hours'=>((int) date_format($datetimeobj, 'H')), + 'minutes'=>((int) date_format($datetimeobj, 'i')), + 'seconds'=>((int) date_format($datetimeobj, 's')), + '0'=>$timestamp + ); } else { - $arrayinfo = getdate($timestamp); + // PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows + $usealternatemethod = false; + if ($timestamp <= 0) $usealternatemethod = true; // <= 1970 + if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038 + + if ($usealternatemethod) + { + $arrayinfo = adodb_getdate($timestamp, $fast); + } else { + $arrayinfo = getdate($timestamp); + } } return $arrayinfo; @@ -2775,7 +2822,7 @@ function getUserRemoteIP() $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here } } else { - $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here } return $ip; } @@ -3100,7 +3147,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title', 'help', 'holiday', 'intervention', 'label', 'language', 'list', 'listlight', 'lot', - 'map-marker-alt', 'money-bill-alt', 'mrp', 'note', + 'map-marker-alt', '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', 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser', @@ -3114,7 +3161,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member', 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website', 'off', 'on', 'order', - 'paiment', 'play', 'playdisabled', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip', + 'paiment', 'play', 'playdisabled', 'previous', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip', 'setup', 'share-alt', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp', 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies', @@ -3148,10 +3195,11 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'email'=>'at', 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle', 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group', - 'member'=>'users', 'mrp'=>'cubes', 'trip'=>'wallet', 'group'=>'users', + 'member'=>'users', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right', + 'trip'=>'wallet', 'group'=>'users', 'sign-out'=>'sign-out-alt', 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star', - 'bank'=>'university', 'close_title'=>'window-close', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter', + 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter', 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table', 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice', 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle', @@ -3159,7 +3207,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'playdisabled'=>'play', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge', 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature', - 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell', + 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell', 'refresh'=>'redo', 'resource'=>'laptop-house', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach', @@ -4015,7 +4063,7 @@ function dol_print_error($db = '', $error = '', $errors = null) } // Return a http error code if possible - if (! headers_sent()) { + if (!headers_sent()) { http_response_code(500); } @@ -4342,6 +4390,7 @@ function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', // Right print '
'; print ''; - // MO - if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) - { - $nblines++; - //$ret = $product->load_stats_mo($socid); - if ($ret < 0) dol_print_error($db); - $langs->load("orders"); - print ''; - print ''; - } - // Customer proposals + // Customer proposals if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $nblines++; @@ -502,6 +485,61 @@ function show_stats_for_company($product, $socid) print ''; } + // BOM + if (!empty($conf->bom->enabled) && $user->rights->bom->read) + { + $nblines++; + $ret = $product->load_stats_bom($socid); + if ($ret < 0) { + setEventMessage($product->error, 'errors'); + } + $langs->load("mrp"); + + print ''; + print ''; + } + + + // MO + if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) + { + $nblines++; + $ret = $product->load_stats_mo($socid); + if ($ret < 0) { + setEventMessage($product->error, 'errors'); + } + $langs->load("mrp"); + print ''; + print ''; + } + return $nblines++; } diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 782e18151b2..29a522e7335 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -30,23 +30,23 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; /** * Prepare array with list of tabs * - * @param Object $object Object related to tabs - * @return array Array of tabs to show + * @param Project $project Object related to tabs + * @return array Array of tabs to show */ -function project_prepare_head($object) +function project_prepare_head(Project $project) { global $db, $langs, $conf, $user; $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$project->id; $head[$h][1] = $langs->trans("Project"); $head[$h][2] = 'project'; $h++; - $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$object->id; + $nbContact = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$project->id; $head[$h][1] = $langs->trans("ProjectContact"); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; @@ -55,12 +55,12 @@ function project_prepare_head($object) if (empty($conf->global->PROJECT_HIDE_TASKS)) { // Then tab for sub level of projet, i mean tasks - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$project->id; $head[$h][1] = $langs->trans("Tasks"); require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $taskstatic = new Task($db); - $nbTasks = count($taskstatic->getTasksArray(0, 0, $object->id, 0, 0)); + $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; $head[$h][2] = 'tasks'; $h++; @@ -71,7 +71,7 @@ function project_prepare_head($object) //$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt"; $sql .= " WHERE t.fk_task = pt.rowid"; - $sql .= " AND pt.fk_projet =".$object->id; + $sql .= " AND pt.fk_projet =".$project->id; $resql = $db->query($sql); if ($resql) { @@ -79,7 +79,7 @@ function project_prepare_head($object) if ($obj) $nbTimeSpent = 1; } else dol_print_error($db); - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$project->id; $head[$h][1] = $langs->trans("TimeSpent"); if ($nbTimeSpent > 0) $head[$h][1] .= '...'; $head[$h][2] = 'timespent'; @@ -91,8 +91,32 @@ function project_prepare_head($object) || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { - $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$object->id; + $count = 0; + + if (!empty($conf->propal->enabled)) $count += $project->getElementCount('propal', 'propal'); + if (!empty($conf->commande->enabled)) $count += $project->getElementCount('order', 'commande'); + if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice', 'facture'); + if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice_predefined', 'facture_rec'); + if (!empty($conf->supplier_proposal->enabled)) $count += $project->getElementCount('proposal_supplier', 'supplier_proposal'); + if (!empty($conf->supplier_order->enabled)) $count += $project->getElementCount('order_supplier', 'commande_fournisseur'); + if (!empty($conf->supplier_invoice->enabled)) $count += $project->getElementCount('invoice_supplier', 'facture_fourn'); + if (!empty($conf->contrat->enabled)) $count += $project->getElementCount('contract', 'contrat'); + if (!empty($conf->ficheinter->enabled)) $count += $project->getElementCount('intervention', 'fichinter'); + if (!empty($conf->expedition->enabled)) $count += $project->getElementCount('shipping', 'expedition'); + if (!empty($conf->mrp->enabled)) $count += $project->getElementCount('mrp', 'mrp_mo', 'fk_project'); + if (!empty($conf->deplacement->enabled)) $count += $project->getElementCount('trip', 'deplacement'); + if (!empty($conf->expensereport->enabled)) $count += $project->getElementCount('expensereport', 'expensereport'); + if (!empty($conf->don->enabled)) $count += $project->getElementCount('donation', 'don'); + if (!empty($conf->loan->enabled)) $count += $project->getElementCount('loan', 'loan'); + if (!empty($conf->tax->enabled)) $count += $project->getElementCount('chargesociales', 'chargesociales'); + if (!empty($conf->projet->enabled)) $count += $project->getElementCount('project_task', 'projet_task'); + if (!empty($conf->stock->enabled)) $count += $project->getElementCount('stock_mouvement', 'stock'); + if (!empty($conf->salaries->enabled)) $count += $project->getElementCount('salaries', 'payment_salary'); + if (!empty($conf->banque->enabled)) $count += $project->getElementCount('variouspayment', 'payment_various'); + + $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$project->id; $head[$h][1] = $langs->trans("ProjectOverview"); + if ($count > 0) $head[$h][1] .= ''.$count.''; $head[$h][2] = 'element'; $h++; } @@ -101,15 +125,15 @@ function project_prepare_head($object) // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'project'); + complete_head_from_modules($conf, $langs, $project, $head, $h, 'project'); if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$object->id; + if (!empty($project->note_private)) $nbNote++; + if (!empty($project->note_public)) $nbNote++; + $head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$project->id; $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'notes'; @@ -118,10 +142,10 @@ function project_prepare_head($object) require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref); + $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); - $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$object->id; + $nbLinks = Link::count($db, $project->element, $project->id); + $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$project->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'document'; @@ -130,15 +154,15 @@ function project_prepare_head($object) // Manage discussion if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { - $nbComments = $object->getNbComments(); - $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$object->id; + $nbComments = $project->getNbComments(); + $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$project->id; $head[$h][1] = $langs->trans("CommentLink"); if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.''; $head[$h][2] = 'project_comment'; $h++; } - $head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$project->id; $head[$h][1] .= $langs->trans("Events"); if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { @@ -148,7 +172,7 @@ function project_prepare_head($object) $head[$h][2] = 'agenda'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'project', 'remove'); + complete_head_from_modules($conf, $langs, $project, $head, $h, 'project', 'remove'); return $head; } diff --git a/htdocs/core/lib/security2.lib.php b/htdocs/core/lib/security2.lib.php index 6f206832e2d..60b01b567f4 100644 --- a/htdocs/core/lib/security2.lib.php +++ b/htdocs/core/lib/security2.lib.php @@ -290,6 +290,8 @@ if (!function_exists('dol_loginfunction')) // Include login page template include $template_dir.'login.tpl.php'; + // Global html output events ($mesgs, $errors, $warnings) + dol_htmloutput_events(0); $_SESSION["dol_loginmesg"] = ''; } diff --git a/htdocs/core/lib/tax.lib.php b/htdocs/core/lib/tax.lib.php index d56d2260afc..3b261bd0814 100644 --- a/htdocs/core/lib/tax.lib.php +++ b/htdocs/core/lib/tax.lib.php @@ -170,7 +170,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -208,7 +208,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } @@ -312,7 +312,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -350,7 +350,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } @@ -451,7 +451,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; $sql .= " ORDER BY e.rowid"; if (!$sql) @@ -622,7 +622,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -660,7 +660,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } @@ -764,7 +764,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -802,7 +802,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } @@ -903,7 +903,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (empty($conf->global->MAIN_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; $sql .= " ORDER BY e.rowid"; if (!$sql) diff --git a/htdocs/core/lib/usergroups.lib.php b/htdocs/core/lib/usergroups.lib.php index 7d67635a1e2..722c0f41263 100644 --- a/htdocs/core/lib/usergroups.lib.php +++ b/htdocs/core/lib/usergroups.lib.php @@ -421,6 +421,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) $colorbackhmenu1 = ''; $colorbackvmenu1 = ''; $colortexttitlenotab = ''; + $colortexttitlelink = ''; $colorbacktitle1 = ''; $colortexttitle = ''; $colorbacklineimpair1 = ''; @@ -526,7 +527,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) //var_dump($conf->global->THEME_ELDY_BACKBODY); if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKBODY, array()), ''), 'THEME_ELDY_BACKBODY', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKBODY, array()), ''), 'THEME_ELDY_BACKBODY', 'formcolor', 1, '', '', 'colorbackbody').' '; } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKBODY, array()), ''); if ($color) print ''; @@ -569,7 +570,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''."\n"; - $list = $this->getlistAvailablePrinters(); - //$html.= ''; - foreach ($list['available'] as $printer_det) - { - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; // id to identify printer to use - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - // Defaut - $html .= ''; - $html .= ''."\n"; - } - $this->resprint = $html; - return $error; - } + $html = ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''."\n"; + $list = $this->getlistAvailablePrinters(); + //$html.= ''; + foreach ($list['available'] as $printer_det) + { + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; // id to identify printer to use + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + // Defaut + $html .= ''; + $html .= ''."\n"; + } + $this->resprint = $html; + return $error; + } - /** - * Return list of available printers - * - * @return array list of printers - */ - public function getlistAvailablePrinters() - { - $ret = array(); - // Token storage - $storage = new DoliStorage($this->db, $this->conf); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } + /** + * Return list of available printers + * + * @return array list of printers + */ + public function getlistAvailablePrinters() + { + $ret = array(); + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + // Check if we have auth token + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - // Send a request with api - try { - $response = $apiService->request(self::PRINTERS_SEARCH_URL); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - print '
'.print_r($e->getMessage(), true).'
'; - } - //print ''; - $responsedata = json_decode($response, true); - $printers = $responsedata['printers']; - // Check if we have printers? - if (count($printers) == 0) { - // We dont have printers so return blank array - $ret['available'] = array(); - } else { - // We have printers so returns printers as array - $ret['available'] = $printers; - } - return $ret; - } + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + // Send a request with api + try { + $response = $apiService->request(self::PRINTERS_SEARCH_URL); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + print '
'.print_r($e->getMessage(), true).'
'; + } + //print ''; + $responsedata = json_decode($response, true); + $printers = $responsedata['printers']; + // Check if we have printers? + if (count($printers) == 0) { + // We dont have printers so return blank array + $ret['available'] = array(); + } else { + // We have printers so returns printers as array + $ret['available'] = $printers; + } + return $ret; + } - /** - * Print selected file - * - * @param string $file file - * @param string $module module - * @param string $subdir subdir for file - * @return int 0 if OK, >0 if KO - */ - public function printFile($file, $module, $subdir = '') - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Print selected file + * + * @param string $file file + * @param string $module module + * @param string $subdir subdir for file + * @return int 0 if OK, >0 if KO + */ + public function printFile($file, $module, $subdir = '') + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - global $conf, $user; - $error = 0; + global $conf, $user; + $error = 0; - $fileprint = $conf->{$module}->dir_output; - if ($subdir != '') { - $fileprint .= '/'.$subdir; - } - $fileprint .= '/'.$file; - $mimetype = dol_mimetype($fileprint); - // select printer uri for module order, propal,... - $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".$user->id; - $result = $this->db->query($sql); - if ($result) - { - $obj = $this->db->fetch_object($result); - if ($obj) - { - $printer_id = $obj->printer_id; - } else { - if (!empty($conf->global->PRINTING_GCP_DEFAULT)) - { - $printer_id = $conf->global->PRINTING_GCP_DEFAULT; - } else { - $this->errors[] = 'NoDefaultPrinterDefined'; - $error++; - return $error; - } - } - } else { - dol_print_error($this->db); - } + $fileprint = $conf->{$module}->dir_output; + if ($subdir != '') { + $fileprint .= '/'.$subdir; + } + $fileprint .= '/'.$file; + $mimetype = dol_mimetype($fileprint); + // select printer uri for module order, propal,... + $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".$user->id; + $result = $this->db->query($sql); + if ($result) + { + $obj = $this->db->fetch_object($result); + if ($obj) + { + $printer_id = $obj->printer_id; + } else { + if (!empty($conf->global->PRINTING_GCP_DEFAULT)) + { + $printer_id = $conf->global->PRINTING_GCP_DEFAULT; + } else { + $this->errors[] = 'NoDefaultPrinterDefined'; + $error++; + return $error; + } + } + } else { + dol_print_error($this->db); + } - $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype); - $this->error = 'PRINTGCP: '.$ret['errormessage']; - if ($ret['status'] != 1) { - $error++; - } - return $error; - } + $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype); + $this->error = 'PRINTGCP: '.$ret['errormessage']; + if ($ret['status'] != 1) { + $error++; + } + return $error; + } - /** - * Sends document to the printer - * - * @param string $printerid Printer id returned by Google Cloud Print - * @param string $printjobtitle Job Title - * @param string $filepath File Path to be send to Google Cloud Print - * @param string $contenttype File content type by example application/pdf, image/png - * @return array status array - */ - public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype) - { - // Check if printer id - if (empty($printerid)) { - return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID'); - } - // Open the file which needs to be print - $handle = fopen($filepath, "rb"); - if (!$handle) { - return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.'); - } - // Read file content - $contents = fread($handle, filesize($filepath)); - fclose($handle); - // Prepare post fields for sending print - $post_fields = array( - 'printerid' => $printerid, - 'title' => $printjobtitle, - 'contentTransferEncoding' => 'base64', - 'content' => base64_encode($contents), // encode file content as base64 - 'contentType' => $contenttype, - ); - // Dolibarr Token storage - $storage = new DoliStorage($this->db, $this->conf); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + /** + * Sends document to the printer + * + * @param string $printerid Printer id returned by Google Cloud Print + * @param string $printjobtitle Job Title + * @param string $filepath File Path to be send to Google Cloud Print + * @param string $contenttype File content type by example application/pdf, image/png + * @return array status array + */ + public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype) + { + // Check if printer id + if (empty($printerid)) { + return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID'); + } + // Open the file which needs to be print + $handle = fopen($filepath, "rb"); + if (!$handle) { + return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.'); + } + // Read file content + $contents = fread($handle, filesize($filepath)); + fclose($handle); + // Prepare post fields for sending print + $post_fields = array( + 'printerid' => $printerid, + 'title' => $printjobtitle, + 'contentTransferEncoding' => 'base64', + 'content' => base64_encode($contents), // encode file content as base64 + 'contentType' => $contenttype, + ); + // Dolibarr Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token and refresh it - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - if ($token_ok) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } + // Check if we have auth token and refresh it + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + if ($token_ok) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } - // Send a request with api - $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true); - //print ''; - return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']); - } + // Send a request with api + $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true); + //print ''; + return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']); + } - /** - * List jobs print - * - * @return int 0 if OK, >0 if KO - */ - public function listJobs() - { - global $conf, $langs; + /** + * List jobs print + * + * @return int 0 if OK, >0 if KO + */ + public function listJobs() + { + global $conf, $langs; - $error = 0; - $html = ''; - // Token storage - $storage = new DoliStorage($this->db, $this->conf); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - $error++; - } - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } + $error = 0; + $html = ''; + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + // Check if we have auth token + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + $error++; + } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - } - // Getting Jobs - // Send a request with api - try { - $response = $apiService->request(self::PRINTERS_GET_JOBS); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - $responsedata = json_decode($response, true); - //$html .= '
'.print_r($responsedata,true).'
'; - $html .= '
'; - $html .= '
'.$langs->trans('Translation').''; - print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); + print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); print '
'.$langs->trans('Label').'
'.$langs->trans("Location").'
'.$langs->trans("Location").'
'.$langs->trans("ActionAffectedTo").''; $listofuserid = array(); + $listofcontactid = array(); + $listofotherid = array(); + if (empty($donotclearsession)) { $assignedtouser = GETPOST("assignedtouser") ?GETPOST("assignedtouser") : (!empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : $user->id); if ($assignedtouser) $listofuserid[$assignedtouser] = array('id'=>$assignedtouser, 'mandatory'=>0, 'transparency'=>$object->transparency); // Owner first - $listofuserid[$user->id]['transparency'] = GETPOSTISSET('transparency') ?GETPOST('transparency', 'alpha') : 1; // 1 by default at first init + //$listofuserid[$user->id] = array('id'=>$user->id, 'mandatory'=>0, 'transparency'=>(GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 1)); // 1 by default at first init + $listofuserid[$assignedtouser]['transparency'] = (GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 1); // 1 by default at first init $_SESSION['assignedtouser'] = json_encode($listofuserid); } else { if (!empty($_SESSION['assignedtouser'])) { $listofuserid = json_decode($_SESSION['assignedtouser'], true); } - $listofuserid[$user->id]['transparency'] = GETPOSTISSET('transparency') ?GETPOST('transparency', 'alpha') : 0; // 0 by default when refreshing + $firstelem = reset($listofuserid); + if (isset($listofuserid[$firstelem['id']])) $listofuserid[$firstelem['id']]['transparency'] = (GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 0); // 0 by default when refreshing } print '
'; print $form->select_dolusers_forevent(($action == 'create' ? 'add' : 'update'), 'assignedtouser', 1, '', 0, '', '', 0, 0, 0, 'AND u.statut != 0', 1, $listofuserid, $listofcontactid, $listofotherid); print '
'; - /*if (in_array($user->id,array_keys($listofuserid))) - { - print '
'; - print $langs->trans("MyAvailability").': '.$langs->trans("Busy"); - print '
'; - }*/ print '
'.$langs->trans("ActionDoneBy").''; - print $form->select_dolusers(GETPOST("doneby") ?GETPOST("doneby") : (!empty($object->userdoneid) && $percent == 100 ? $object->userdoneid : 0), 'doneby', 1); + print $form->select_dolusers(GETPOSTISSET("doneby") ? GETPOST("doneby", 'int') : (!empty($object->userdoneid) && $percent == 100 ? $object->userdoneid : 0), 'doneby', 1); print '
'.$langs->trans("Categories").''; + print '
'.$langs->trans("Categories").''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACTIONCOMM, '', 'parent', 64, 0, 1); - print $form->multiselectarray('categories', $cate_arbo, GETPOST('categories', 'array'), '', 0, '', 0, '100%'); + print $form->multiselectarray('categories', $cate_arbo, GETPOST('categories', 'array'), '', 0, 'minwidth300 quatrevingtpercent', 0, 0); print "
'.$langs->trans("ActionOnCompany").''; - if (GETPOST('socid', 'int') > 0) - { + if (GETPOST('socid', 'int') > 0) { $societe = new Societe($db); $societe->fetch(GETPOST('socid', 'int')); print $societe->getNomUrl(1); @@ -1148,7 +1142,8 @@ if ($action == 'create') print '
'.$langs->trans("ActionOnContact").''; $preselectedids = GETPOST('socpeopleassigned', 'array'); if (GETPOST('contactid', 'int')) $preselectedids[GETPOST('contactid', 'int')] = GETPOST('contactid', 'int'); - print img_picto('', 'contact', 'class="paddingrightonly"').$form->selectcontacts(GETPOST('socid', 'int'), $preselectedids, 'socpeopleassigned[]', 1, '', '', 0, 'quatrevingtpercent', false, 0, array(), false, 'multiple', 'contactid'); + print img_picto('', 'contact', 'class="paddingrightonly"'); + print $form->selectcontacts(GETPOST('socid', 'int'), $preselectedids, 'socpeopleassigned[]', 1, '', '', 0, 'minwidth300 quatrevingtpercent', false, 0, array(), false, 'multiple', 'contactid'); print '
'.$langs->trans("Project").''; print img_picto('', 'project', 'class="paddingrightonly"'); - $numproject = $formproject->select_projects((!empty($societe->id) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'maxwidth500'); + print $formproject->select_projects((!empty($societe->id) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx'); print ' '; $urloption = '?action=create&donotclearsession=1'; @@ -1171,10 +1166,11 @@ if ($action == 'create') print "\n".''; + $out .= ''; $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter); - $out .= ' '; + $out .= ' '; $out .= '
'; } @@ -3282,6 +3280,7 @@ class Form } print ''; if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print ajax_combobox($htmlname); } /** @@ -3365,6 +3364,7 @@ class Form } print ''; if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print ajax_combobox('select_'.$htmlname); } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3460,6 +3460,7 @@ class Form } print ''; if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print ajax_combobox($htmlname); } @@ -3529,6 +3530,7 @@ class Form } print ''; if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print ajax_combobox('select'.$htmlname); } @@ -3565,6 +3567,107 @@ class Form return $return; } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load in cache list of transport mode + * + * @return int Nb of lines loaded, <0 if KO + */ + public function load_cache_transport_mode() + { + // phpcs:enable + global $langs; + + $num=count($this->cache_transport_mode); + if ($num > 0) return $num; // Cache already loaded + + dol_syslog(__METHOD__, LOG_DEBUG); + + $this->cache_transport_mode = array(); + + $sql = "SELECT rowid, code, label, active"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_transport_mode"; + $sql.= " WHERE entity IN (".getEntity('c_transport_mode').")"; + //if ($active >= 0) $sql.= " AND active = ".$active; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + // If traduction exist, we use it else we take the default label + $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid; + $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code; + $this->cache_transport_mode[$obj->rowid]['label']= $label; + $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active; + $i++; + } + + $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1); + + return $num; + } + else { + dol_print_error($this->db); + return -1; + } + } + + /** + * Return list of transport mode for intracomm report + * + * @param string $selected Id of the transport mode pre-selected + * @param string $htmlname Name of the select field + * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code + * @param int $empty 1=can be empty, 0 else + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $maxlength Max length of label + * @param int $active Active or not, -1 = all + * @param string $morecss Add more CSS on select tag + * @return void + */ + public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '') + { + global $langs,$user; + + dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG); + + $this->load_cache_transport_mode(); + + print ''; + if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } + /** * Return a HTML select list of shipping mode * @@ -3611,6 +3714,8 @@ class Form } print ""; if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + + print ajax_combobox('select'.$htmlname); } else { print $langs->trans("NoShippingMethodDefined"); } @@ -3809,6 +3914,7 @@ class Form $i++; } print ""; + print ajax_combobox('select'.$htmlname); } else { if ($status == 0) print ''.$langs->trans("NoActiveBankAccountDefined").''; else print ''.$langs->trans("NoBankAccountFound").''; @@ -4128,10 +4234,11 @@ class Form $more .= '
'; if ($i == 0) $more .= '
'.$input['label'].'
'; else $more .= '
 
'; - $more .= '
'.$selval.''; $more .= '
'."\n"; $i++; } @@ -4598,7 +4705,40 @@ class Form } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Show form with transport mode + * + * @param string $page Page + * @param int $selected Id mode pre-select + * @param string $htmlname Name of select html field + * @param int $active Active or not, -1 = all + * @param int $addempty 1=Add empty entry + * @return void + */ + public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0) + { + global $langs; + if ($htmlname != "none") + { + print '
'; + print ''; + print ''; + $this->selectTransportMode($selected, $htmlname, 2, $addempty, 0, 0, $active); + print ''; + print '
'; + } + else { + if ($selected) + { + $this->load_cache_transport_mode(); + print $this->cache_transport_mode[$selected]['label']; + } else { + print " "; + } + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Show form with multicurrency code * @@ -5315,6 +5455,7 @@ class Form } // Analysis of the pre-selection date + $reg = array(); if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage { // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' @@ -5459,7 +5600,6 @@ class Form } // Show date with combo selects else { - //$retstring.='
'; // Day $retstring .= ''; @@ -5503,11 +5643,13 @@ class Form } $retstring .= "\n"; } - //$retstring.='
'; } } - if ($d && $h) $retstring .= ($h == 2 ? '
' : ' '); + if ($d && $h) { + $retstring .= ($h == 2 ? '
' : ' '); + $retstring.=''; + } if ($h) { @@ -5525,10 +5667,13 @@ class Form for ($hour = $hourstart; $hour < $hourend; $hour++) { if (strlen($hour) < 2) $hour = "0".$hour; - $retstring .= ''; + $retstring .= ''; } $retstring .= ''; - if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; + //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; + if ($m) $retstring .= ":"; } if ($m) @@ -5546,6 +5691,10 @@ class Form $retstring .= ''; } + if ($d && $h) { + $retstring .= ''; + } + // Add a "Now" link if ($conf->use_javascript_ajax && $addnowlink) { @@ -5807,7 +5956,7 @@ class Form * @param int $disabled 1=Html component is disabled * @param string $selected_input_value Value of preselected input text (for use with ajax) * @return string Return HTML string - * @see selectForFormsList() select_thirdparty() + * @see selectForFormsList() select_thirdparty_list() */ public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '') { @@ -6982,9 +7131,10 @@ class Form * @param int $option 0 return yes/no, 1 return 1/0 * @param bool $disabled true or false * @param int $useempty 1=Add empty line + * @param int $addjscombo 1=Add js beautifier on combo box * @return string See option */ - public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) + public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0) { global $langs; @@ -7009,6 +7159,11 @@ class Form $resultyesno .= ''."\n"; } $resultyesno .= ''."\n"; + + if ($addjscombo) { + $resultyesno .= ajax_combobox($htmlname); + } + return $resultyesno; } @@ -7138,7 +7293,7 @@ class Form } if ($morehtml) { - $ret .= '
  • '.$morehtml.'
  • '; + $ret .= '
  • '.$morehtml.'
  • '; } if ($shownav && ($previous_ref || $next_ref)) { diff --git a/htdocs/core/class/html.formcompany.class.php b/htdocs/core/class/html.formcompany.class.php index b43df3753dc..f6e412e0958 100644 --- a/htdocs/core/class/html.formcompany.class.php +++ b/htdocs/core/class/html.formcompany.class.php @@ -375,7 +375,7 @@ class FormCompany extends Form $resql = $this->db->query($sql); if ($resql) { - print ''; $num = $this->db->num_rows($resql); $i = 0; if ($num) @@ -407,6 +407,7 @@ class FormCompany extends Form } } print ''; + print ajax_combobox($htmlname); } else { dol_print_error($this->db); } @@ -1003,6 +1004,7 @@ class FormCompany extends Form } } $out .= ''; + $out .= ajax_combobox($htmlidname); return $out; } diff --git a/htdocs/core/class/html.formexpensereport.class.php b/htdocs/core/class/html.formexpensereport.class.php index e8079b77ed6..516c6e4b59c 100644 --- a/htdocs/core/class/html.formexpensereport.class.php +++ b/htdocs/core/class/html.formexpensereport.class.php @@ -65,7 +65,7 @@ class FormExpenseReport $tmpep = new ExpenseReport($this->db); - print ''; if ($useempty) print ''; $arrayoflabels = $tmpep->statuts; if ($useshortlabel) $arrayoflabels = $tmpep->statuts_short; @@ -81,6 +81,7 @@ class FormExpenseReport print ''; } print ''; + print ajax_combobox($htmlname); } /** diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 2b98bac30c6..464dbafa375 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -115,7 +115,7 @@ class FormFile if (empty($usewithoutform)) // Try to avoid this and set instead the form by the caller. { // Add a param as GET parameter to detect when POST were cleaned by PHP because a file larger than post_max_size - $url .= (strpos('?', $url) === false ? '?' : '&').'uploadform=1'; + $url .= (strpos($url, '?') === false ? '?' : '&').'uploadform=1'; $out .= '
    '; $out .= ''; diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index e2749c5e183..200b50cd512 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -296,6 +296,7 @@ class FormMail extends Form * @param string $addfileaction Name of action when posting file attachments * @param string $removefileaction Name of action when removing file attachments * @return void + * @deprecated */ public function show_form($addfileaction = 'addfile', $removefileaction = 'removefile') { @@ -434,18 +435,20 @@ class FormMail extends Form { setEventMessages($this->error, $this->errors, 'errors'); } + $langs->trans("members"); foreach ($this->lines_model as $line) { - $langs->trans("members"); - if (preg_match('/\((.*)\)/', $line->label, $reg)) - { - $modelmail_array[$line->id] = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__ + $reg = array(); + if (preg_match('/\((.*)\)/', $line->label, $reg)) { + $labeltouse = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__ } else { - $modelmail_array[$line->id] = $line->label; + $labeltouse = $line->label; } - if ($line->lang) $modelmail_array[$line->id] .= ' ('.$line->lang.')'; - if ($line->private) $modelmail_array[$line->id] .= ' - '.$langs->trans("Private"); - //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' '; + + // We escape the $labeltouse to store it into $modelmail_array. + $modelmail_array[$line->id] = dol_escape_htmltag($labeltouse); + if ($line->lang) $modelmail_array[$line->id] .= ' '.picto_from_langcode($line->lang); + if ($line->private) $modelmail_array[$line->id] .= ' - '.dol_escape_htmltag($langs->trans("Private")).''; } } @@ -454,7 +457,8 @@ class FormMail extends Form { // If list of template is filled $out .= '
    '."\n"; - $out .= ''.$langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out .= ''.$langs->trans('SelectMailModel').': '; + $out .= $this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100', 1, '', 0, 1); if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1); $out .= '   '; $out .= ''; diff --git a/htdocs/core/class/html.formorder.class.php b/htdocs/core/class/html.formorder.class.php index d3dbe27ceac..1dcac0023c4 100644 --- a/htdocs/core/class/html.formorder.class.php +++ b/htdocs/core/class/html.formorder.class.php @@ -62,7 +62,7 @@ class FormOrder extends Form $options[$value] = $tmpsupplierorder->getLibStatut($short); } - print Form::selectarray($hmlname, $options, $selected, 1); + print Form::selectarray($hmlname, $options, $selected, 1, 0, 0, '', 0, 0, 0, '', '', 1); } /** diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index a6c458fc67b..5d3bd181753 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -38,738 +38,746 @@ */ class FormOther { - private $db; + private $db; - /** + /** * @var string Error code (or message) */ public $error; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML select list of export models - * - * @param string $selected Id modele pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $type Type des modeles recherches - * @param int $useempty Show an empty value in list - * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) - * @return void - */ - public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null) - { - // phpcs:enable - global $conf, $langs, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML select list of export models + * + * @param string $selected Id modele pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $type Type des modeles recherches + * @param int $useempty Show an empty value in list + * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) + * @return void + */ + public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null) + { + // phpcs:enable + global $conf, $langs, $user; - $sql = "SELECT rowid, label, fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; - $sql .= " WHERE type = '".$this->db->escape($type)."'"; + $sql = "SELECT rowid, label, fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; + $sql .= " WHERE type = '".$this->db->escape($type)."'"; if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql .= " ORDER BY label"; - $result = $this->db->query($sql); - if ($result) - { - print ''; + if ($useempty) + { + print ''; + } - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); - $label = $obj->label; - if ($obj->fk_user == 0) { - $label .= ' ('.$langs->trans("Everybody").')'; - } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { - $tmpuser = new User($this->db); - $tmpuser->fetch($obj->fk_user); - $label .= ' ('.$tmpuser->getFullName($langs).')'; - } + $label = $obj->label; + if ($obj->fk_user == 0) { + $label .= ' ('.$langs->trans("Everybody").')'; + } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { + $tmpuser = new User($this->db); + $tmpuser->fetch($obj->fk_user); + $label .= ' ('.$tmpuser->getFullName($langs).')'; + } - if ($selected == $obj->rowid) - { - print ''; - $i++; - } - print ""; - print ajax_combobox($htmlname); - } else { - dol_print_error($this->db); - } - } + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + print ajax_combobox($htmlname); + } else { + dol_print_error($this->db); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of export models - * - * @param string $selected Id modele pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $type Type des modeles recherches - * @param int $useempty Affiche valeur vide dans liste - * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) - * @return void - */ - public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null) - { - // phpcs:enable - global $conf, $langs, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of export models + * + * @param string $selected Id modele pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $type Type des modeles recherches + * @param int $useempty Affiche valeur vide dans liste + * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) + * @return void + */ + public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null) + { + // phpcs:enable + global $conf, $langs, $user; - $sql = "SELECT rowid, label, fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."import_model"; - $sql .= " WHERE type = '".$this->db->escape($type)."'"; - if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql .= " ORDER BY rowid"; - $result = $this->db->query($sql); - if ($result) - { - print ''; + if ($useempty) + { + print ''; + } - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); - $label = $obj->label; - if ($obj->fk_user == 0) { - $label .= ' ('.$langs->trans("Everybody").')'; - } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { - $tmpuser = new User($this->db); - $tmpuser->fetch($obj->fk_user); - $label .= ' ('.$tmpuser->getFullName($langs).')'; - } + $label = $obj->label; + if ($obj->fk_user == 0) { + $label .= ' ('.$langs->trans("Everybody").')'; + } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { + $tmpuser = new User($this->db); + $tmpuser->fetch($obj->fk_user); + $label .= ' ('.$tmpuser->getFullName($langs).')'; + } - if ($selected == $obj->rowid) - { - print ''; - $i++; - } - print ""; - print ajax_combobox($htmlname); - } else { - dol_print_error($this->db); - } - } + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + print ajax_combobox($htmlname); + } else { + dol_print_error($this->db); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of ecotaxes with label - * - * @param string $selected Preselected ecotaxes - * @param string $htmlname Name of combo list - * @return integer - */ - public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of ecotaxes with label + * + * @param string $selected Preselected ecotaxes + * @param string $htmlname Name of combo list + * @return integer + */ + public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id') + { + // phpcs:enable + global $langs; - $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; - $sql .= " c.label as country"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; - $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; + $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; + $sql .= " c.label as country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; + $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; - dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - print ''; - return 0; - } else { - dol_print_error($this->db); - return 1; - } - } + dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + print ''; + return 0; + } else { + dol_print_error($this->db); + return 1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of revenue stamp for country - * - * @param string $selected Value of preselected revenue stamp - * @param string $htmlname Name of combo list - * @param string $country_code Country Code - * @return string HTML select list - */ - public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of revenue stamp for country + * + * @param string $selected Value of preselected revenue stamp + * @param string $htmlname Name of combo list + * @param string $country_code Country Code + * @return string HTML select list + */ + public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '') + { + // phpcs:enable + global $langs; - $out = ''; + $out = ''; - $sql = "SELECT r.taux, r.revenuestamp_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid"; - $sql .= " AND c.code = '".$this->db->escape($country_code)."'"; + $sql = "SELECT r.taux, r.revenuestamp_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid"; + $sql .= " AND c.code = '".$this->db->escape($country_code)."'"; - dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $out .= ''; - return $out; - } else { - dol_print_error($this->db); - return ''; - } - } + dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $out .= ''; + return $out; + } else { + dol_print_error($this->db); + return ''; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select list to select a percent - * - * @param integer $selected pourcentage pre-selectionne - * @param string $htmlname nom de la liste deroulante - * @param int $disabled Disabled or not - * @param int $increment increment value - * @param int $start start value - * @param int $end end value - * @param int $showempty Add also an empty line - * @return string HTML select string - */ - public function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0) - { - // phpcs:enable - $return = ''; + if ($showempty) $return .= ''; - for ($i = $start; $i <= $end; $i += $increment) - { - if ($selected != '' && (int) $selected == $i) - { - $return .= ''; - } + for ($i = $start; $i <= $end; $i += $increment) + { + if ($selected != '' && (int) $selected == $i) + { + $return .= ''; + } - $return .= ''; + $return .= ''; - return $return; - } + return $return; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return select list for categories (to use in form search selectors) - * - * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. - * @param integer $selected Preselected value - * @param string $htmlname Name of combo list - * @param int $nocateg Show also an entry "Not categorized" - * @param int $showempty Add also an empty line - * @param string $morecss More CSS - * @return string Html combo list code - * @see select_all_categories() - */ - public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '') - { - // phpcs:enable - global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return select list for categories (to use in form search selectors) + * + * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. + * @param integer $selected Preselected value + * @param string $htmlname Name of combo list + * @param int $nocateg Show also an entry "Not categorized" + * @param int $showempty Add also an empty line + * @param string $morecss More CSS + * @return string Html combo list code + * @see select_all_categories() + */ + public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '') + { + // phpcs:enable + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - // For backward compatibility - if (is_numeric($type)) - { - dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); - } + // For backward compatibility + if (is_numeric($type)) + { + dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + } - // Load list of "categories" - $static_categs = new Categorie($this->db); - $tab_categs = $static_categs->get_full_arbo($type); + // Load list of "categories" + $static_categs = new Categorie($this->db); + $tab_categs = $static_categs->get_full_arbo($type); - $moreforfilter = ''; - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox('select_categ_'.$htmlname); - $moreforfilter .= $comboenhancement; - } + $moreforfilter = ''; + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox('select_categ_'.$htmlname); + $moreforfilter .= $comboenhancement; + } - // Print a select with each of them - $moreforfilter .= ''; + if ($showempty) $moreforfilter .= ''; // Should use -1 to say nothing - if (is_array($tab_categs)) - { - foreach ($tab_categs as $categ) - { - $moreforfilter .= ''; - } - $moreforfilter .= ''; + if (is_array($tab_categs)) + { + foreach ($tab_categs as $categ) + { + $moreforfilter .= ''; + } + $moreforfilter .= ''; - return $moreforfilter; - } + return $moreforfilter; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return select list for categories (to use in form search selectors) - * - * @param string $selected Preselected value - * @param string $htmlname Name of combo list (example: 'search_sale') - * @param User $user Object user - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param int $showempty 1=show also an empty value - * @param string $morecss More CSS - * @param int $norepresentative Show also an entry "Not categorized" - * @return string Html combo list code - */ - public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) - { - // phpcs:enable - global $conf, $langs, $hookmanager; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return select list for categories (to use in form search selectors) + * + * @param string $selected Preselected value + * @param string $htmlname Name of combo list (example: 'search_sale') + * @param User $user Object user + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param int $showempty 1=show also an empty value + * @param string $morecss More CSS + * @param int $norepresentative Show also an entry "Not categorized" + * @return string Html combo list code + */ + public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) + { + // phpcs:enable + global $conf, $langs, $hookmanager; - $langs->load('users'); + $langs->load('users'); - $out = ''; - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out = ''; + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox($htmlname); - if ($comboenhancement) - { - $out .= $comboenhancement; - } - } + $comboenhancement = ajax_combobox($htmlname); + if ($comboenhancement) + { + $out .= $comboenhancement; + } + } - $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectSalesRep', array(), $this, $action); + $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectSalesRep', array(), $this, $action); - // Select each sales and print them in a select input - $out .= ''; + if ($showempty) $out .= ''; - // Get list of users allowed to be viewed - $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login"; - $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u"; + // Get list of users allowed to be viewed + $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login"; + $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u"; - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { - $sql_usr .= " WHERE u.entity IS NOT NULL"; // Show all users - } else { - $sql_usr .= " WHERE EXISTS (SELECT ug.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug WHERE u.rowid = ug.fk_user AND ug.entity IN (".getEntity('usergroup')."))"; - $sql_usr .= " OR u.entity = 0"; // Show always superadmin - } - } else { - $sql_usr .= " WHERE u.entity IN (".getEntity('user').")"; - } + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql_usr .= " WHERE u.entity IS NOT NULL"; // Show all users + } else { + $sql_usr .= " WHERE EXISTS (SELECT ug.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug WHERE u.rowid = ug.fk_user AND ug.entity IN (".getEntity('usergroup')."))"; + $sql_usr .= " OR u.entity = 0"; // Show always superadmin + } + } else { + $sql_usr .= " WHERE u.entity IN (".getEntity('user').")"; + } - if (empty($user->rights->user->user->lire)) $sql_usr .= " AND u.rowid = ".$user->id; - if (!empty($user->socid)) $sql_usr .= " AND u.fk_soc = ".$user->socid; + if (empty($user->rights->user->user->lire)) $sql_usr .= " AND u.rowid = ".$user->id; + if (!empty($user->socid)) $sql_usr .= " AND u.fk_soc = ".$user->socid; - //Add hook to filter on user (for exemple on usergroup define in custom modules) - if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[0]; + //Add hook to filter on user (for exemple on usergroup define in custom modules) + if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[0]; - // Add existing sales representatives of thirdparty of external user - if (empty($user->rights->user->user->lire) && $user->socid) - { - $sql_usr .= " UNION "; - $sql_usr .= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login"; - $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + // Add existing sales representatives of thirdparty of external user + if (empty($user->rights->user->user->lire) && $user->socid) + { + $sql_usr .= " UNION "; + $sql_usr .= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login"; + $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { - $sql_usr .= " WHERE u2.entity IS NOT NULL"; // Show all users - } else { - $sql_usr .= " WHERE EXISTS (SELECT ug2.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug2 WHERE u2.rowid = ug2.fk_user AND ug2.entity IN (".getEntity('usergroup')."))"; - } - } else { - $sql_usr .= " WHERE u2.entity IN (".getEntity('user').")"; - } + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql_usr .= " WHERE u2.entity IS NOT NULL"; // Show all users + } else { + $sql_usr .= " WHERE EXISTS (SELECT ug2.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug2 WHERE u2.rowid = ug2.fk_user AND ug2.entity IN (".getEntity('usergroup')."))"; + } + } else { + $sql_usr .= " WHERE u2.entity IN (".getEntity('user').")"; + } - $sql_usr .= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->socid; + $sql_usr .= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->socid; - //Add hook to filter on user (for exemple on usergroup define in custom modules) - if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[1]; - } - $sql_usr .= " ORDER BY statut DESC, lastname ASC"; // Do not use 'ORDER BY u.statut' here, not compatible with the UNION. - //print $sql_usr;exit; + //Add hook to filter on user (for exemple on usergroup define in custom modules) + if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[1]; + } + $sql_usr .= " ORDER BY statut DESC, lastname ASC"; // Do not use 'ORDER BY u.statut' here, not compatible with the UNION. + //print $sql_usr;exit; - $resql_usr = $this->db->query($sql_usr); - if ($resql_usr) - { - while ($obj_usr = $this->db->fetch_object($resql_usr)) - { - $out .= ''; - } - $this->db->free($resql_usr); - } else { - dol_print_error($this->db); - } + $out .= ''; + } + $this->db->free($resql_usr); + } else { + dol_print_error($this->db); + } - if ($norepresentative) - { - $langs->load("companies"); - $out .= ''; - } + if ($norepresentative) + { + $langs->load("companies"); + $out .= ''; + } - $out .= ''; + $out .= ''; - return $out; - } + return $out; + } - /** - * Return list of project and tasks - * - * @param int $selectedtask Pre-selected task - * @param int $projectid Project id - * @param string $htmlname Name of html select - * @param int $modeproject 1 to restrict on projects owned by user - * @param int $modetask 1 to restrict on tasks associated to user - * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists - * @param int $useempty 0=Allow empty values - * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id + /** + * Return list of project and tasks + * + * @param int $selectedtask Pre-selected task + * @param int $projectid Project id + * @param string $htmlname Name of html select + * @param int $modeproject 1 to restrict on projects owned by user + * @param int $modetask 1 to restrict on tasks associated to user + * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists + * @param int $useempty 0=Allow empty values + * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id * @param string $filteronprojstatus Filter on project status ('-1'=no filter, '0,1'=Draft+Validated status) - * @param string $morecss More css - * @return void - */ - public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '') - { - global $user, $langs; + * @param string $morecss More css + * @return void + */ + public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '') + { + global $user, $langs; - require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - //print $modeproject.'-'.$modetask; - $task = new Task($this->db); - $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); - if ($tasksarray) - { - print ''; + //print $modeproject.'-'.$modetask; + $task = new Task($this->db); + $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); + if ($tasksarray) + { + print ''; - print ajax_combobox($htmlname); - } else { - print '
    '.$langs->trans("NoProject").'
    '; - } - } + print ajax_combobox($htmlname); + } else { + print '
    '.$langs->trans("NoProject").'
    '; + } + } - /** - * Write lines of a project (all lines of a project if parent = 0) - * - * @param int $inc Cursor counter - * @param int $parent Id of parent task we want to see - * @param array $lines Array of task lines - * @param int $level Level - * @param int $selectedtask Id selected task - * @param int $selectedproject Id selected project - * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id - * @return void - */ - private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0) - { - global $langs, $user, $conf; + /** + * Write lines of a project (all lines of a project if parent = 0) + * + * @param int $inc Cursor counter + * @param int $parent Id of parent task we want to see + * @param array $lines Array of task lines + * @param int $level Level + * @param int $selectedtask Id selected task + * @param int $selectedproject Id selected project + * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id + * @return void + */ + private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0) + { + global $langs, $user, $conf; - $lastprojectid = 0; + $lastprojectid = 0; - $numlines = count($lines); - for ($i = 0; $i < $numlines; $i++) { - if ($lines[$i]->fk_parent == $parent) { - //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines + $numlines = count($lines); + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_parent == $parent) { + //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines - // Break on a new project - if ($parent == 0) // We are on a task at first level - { - if ($lines[$i]->fk_project != $lastprojectid) // Break found on project - { - if ($i > 0) print ''; - print '\n"; + // Break on a new project + if ($parent == 0) // We are on a task at first level + { + if ($lines[$i]->fk_project != $lastprojectid) // Break found on project + { + if ($i > 0) print ''; + print '\n"; - $lastprojectid = $lines[$i]->fk_project; - $inc++; - } - } + $lastprojectid = $lines[$i]->fk_project; + $inc++; + } + } - $newdisablechildoftaskid = $disablechildoftaskid; + $newdisablechildoftaskid = $disablechildoftaskid; - // Print task - if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 - { - // Check if we must disable entry - $disabled = 0; - if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) - { - $disabled++; - if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too - } + // Print task + if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 + { + // Check if we must disable entry + $disabled = 0; + if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) + { + $disabled++; + if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too + } - print '\n"; - $inc++; - } + print '\n"; + $inc++; + } - $level++; - if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid); - $level--; - } - } - } + $level++; + if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid); + $level--; + } + } + } - /** - * Output a HTML thumb of color or a text if not defined. - * - * @param string $color String with hex (FFFFFF) or comma RGB ('255,255,255') - * @param string $textifnotdefined Text to show if color not defined - * @return string HTML code for color thumb - * @see selectColor() - */ - public static function showColor($color, $textifnotdefined = '') - { - $textcolor = 'FFF'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if (colorIsLight($color)) $textcolor = '000'; + /** + * Output a HTML thumb of color or a text if not defined. + * + * @param string $color String with hex (FFFFFF) or comma RGB ('255,255,255') + * @param string $textifnotdefined Text to show if color not defined + * @return string HTML code for color thumb + * @see selectColor() + */ + public static function showColor($color, $textifnotdefined = '') + { + $textcolor = 'FFF'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + if (colorIsLight($color)) $textcolor = '000'; - $color = colorArrayToHex(colorStringToArray($color, array()), ''); + $color = colorArrayToHex(colorStringToArray($color, array()), ''); if ($color) print ''; else print $textifnotdefined; - } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output a HTML code to select a color - * - * @param string $set_color Pre-selected color - * @param string $prefix Name of HTML field - * @param string $form_name Deprecated. Not used. - * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code - * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') - * @return void - * @deprecated Use instead selectColor - * @see selectColor() - */ - public function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '') - { - // phpcs:enable - print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors); - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Output a HTML code to select a color + * + * @param string $set_color Pre-selected color + * @param string $prefix Name of HTML field + * @param string $form_name Deprecated. Not used. + * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code + * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') + * @return void + * @deprecated Use instead selectColor + * @see selectColor() + */ + public function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '') + { + // phpcs:enable + print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors); + } - /** - * Output a HTML code to select a color. Field will return an hexa color like '334455'. - * - * @param string $set_color Pre-selected color - * @param string $prefix Name of HTML field - * @param string $form_name Deprecated. Not used. - * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code - * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') - * @param string $morecss Add css style into input field - * @return string - * @see showColor() - */ - public static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '') - { - // Deprecation warning - if ($form_name) { - dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING); - } + /** + * Output a HTML code to select a color. Field will return an hexa color like '334455'. + * + * @param string $set_color Pre-selected color + * @param string $prefix Name of HTML field + * @param string $form_name Deprecated. Not used. + * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code + * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') + * @param string $morecss Add css style into input field + * @param string $setpropertyonselect Set this property after selecting a color + * @return string + * @see showColor() + */ + public static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '', $setpropertyonselect = '') + { + // Deprecation warning + if ($form_name) { + dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING); + } - global $langs, $conf; + global $langs, $conf; - $out = ''; + $out = ''; - if (!is_array($arrayofcolors) || count($arrayofcolors) < 1) - { - $langs->load("other"); - if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax)) - { - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; - } - $out .= ''; - } else // In most cases, this is not used. We used instead function with no specific list of colors - { - if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax)) - { - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; - } - $out .= ''; - } + } + $out .= ''; + } - return $out; - } + return $out; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Creation d'un icone de couleur - * - * @param string $color Couleur de l'image - * @param string $module Nom du module - * @param string $name Nom de l'image - * @param int $x Largeur de l'image en pixels - * @param int $y Hauteur de l'image en pixels - * @return void - */ - public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12') - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Creation d'un icone de couleur + * + * @param string $color Couleur de l'image + * @param string $module Nom du module + * @param string $name Nom de l'image + * @param int $x Largeur de l'image en pixels + * @param int $y Hauteur de l'image en pixels + * @return void + */ + public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12') + { + // phpcs:enable + global $conf; - $file = $conf->$module->dir_temp.'/'.$name.'.png'; + $file = $conf->$module->dir_temp.'/'.$name.'.png'; - // On cree le repertoire contenant les icones - if (!file_exists($conf->$module->dir_temp)) - { - dol_mkdir($conf->$module->dir_temp); - } + // On cree le repertoire contenant les icones + if (!file_exists($conf->$module->dir_temp)) + { + dol_mkdir($conf->$module->dir_temp); + } - // On cree l'image en vraies couleurs - $image = imagecreatetruecolor($x, $y); + // On cree l'image en vraies couleurs + $image = imagecreatetruecolor($x, $y); - $color = substr($color, 1, 6); + $color = substr($color, 1, 6); - $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge - $vert = hexdec(substr($color, 2, 2)); //conversion du canal vert - $bleu = hexdec(substr($color, 4, 2)); //conversion du canal bleu + $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge + $vert = hexdec(substr($color, 2, 2)); //conversion du canal vert + $bleu = hexdec(substr($color, 4, 2)); //conversion du canal bleu - $couleur = imagecolorallocate($image, $rouge, $vert, $bleu); - //print $rouge.$vert.$bleu; - imagefill($image, 0, 0, $couleur); //on remplit l'image - // On cree la couleur et on l'attribue a une variable pour ne pas la perdre - ImagePng($image, $file); //renvoie une image sous format png - ImageDestroy($image); - } + $couleur = imagecolorallocate($image, $rouge, $vert, $bleu); + //print $rouge.$vert.$bleu; + imagefill($image, 0, 0, $couleur); //on remplit l'image + // On cree la couleur et on l'attribue a une variable pour ne pas la perdre + ImagePng($image, $file); //renvoie une image sous format png + ImageDestroy($image); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of week - * - * @param string $selected Preselected value - * @param string $htmlname Nom de la zone select - * @param int $useempty Affiche valeur vide dans liste - * @return string - */ - public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of week + * + * @param string $selected Preselected value + * @param string $htmlname Nom de la zone select + * @param int $useempty Affiche valeur vide dans liste + * @return string + */ + public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0) + { + // phpcs:enable + global $langs; - $week = array( - 0=>$langs->trans("Day0"), - 1=>$langs->trans("Day1"), - 2=>$langs->trans("Day2"), - 3=>$langs->trans("Day3"), - 4=>$langs->trans("Day4"), - 5=>$langs->trans("Day5"), - 6=>$langs->trans("Day6") - ); + $week = array( + 0=>$langs->trans("Day0"), + 1=>$langs->trans("Day1"), + 2=>$langs->trans("Day2"), + 3=>$langs->trans("Day3"), + 4=>$langs->trans("Day4"), + 5=>$langs->trans("Day5"), + 6=>$langs->trans("Day6") + ); - $select_week = ''; - return $select_week; - } + $select_week = ''; + return $select_week; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of month - * - * @param string $selected Preselected value - * @param string $htmlname Name of HTML select object - * @param int $useempty Show empty in list - * @param int $longlabel Show long label - * @param string $morecss More Css - * @return string - */ - public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'maxwidth50imp valignmiddle') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of month + * + * @param string $selected Preselected value + * @param string $htmlname Name of HTML select object + * @param int $useempty Show empty in list + * @param int $longlabel Show long label + * @param string $morecss More Css + * @return string + */ + public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'maxwidth50imp valignmiddle') + { + // phpcs:enable + global $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - if ($longlabel) $montharray = monthArray($langs, 0); // Get array - else $montharray = monthArray($langs, 1); + if ($longlabel) $montharray = monthArray($langs, 0); // Get array + else $montharray = monthArray($langs, 1); - $select_month = ''; - return $select_month; - } + $select_month = ''; + return $select_month; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of years - * - * @param string $selected Preselected value (''=current year, -1=none, year otherwise) - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param int $min_year Offset of minimum year into list (by default current year -10) - * @param int $max_year Offset of maximum year into list (by default current year + 5) - * @param int $offset Offset - * @param int $invert Invert - * @param string $option Option - * @param string $morecss More CSS - * @return string - */ - public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') - { - // phpcs:enable - print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss); - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of years + * + * @param string $selected Preselected value (''=current year, -1=none, year otherwise) + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param int $min_year Offset of minimum year into list (by default current year -10) + * @param int $max_year Offset of maximum year into list (by default current year + 5) + * @param int $offset Offset + * @param int $invert Invert + * @param string $option Option + * @param string $morecss More CSS + * @return string + */ + public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') + { + // phpcs:enable + print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss); + } - /** - * Return HTML combo list of years - * - * @param string $selected Preselected value (''=current year, -1=none, year otherwise) - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param int $min_year Offset of minimum year into list (by default current year -10) - * @param int $max_year Offset of maximum year into list (by default current year + 5) - * @param int $offset Offset - * @param int $invert Invert - * @param string $option Option - * @param string $morecss More css - * @return string - */ - public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') - { - $out = ''; + /** + * Return HTML combo list of years + * + * @param string $selected Preselected value (''=current year, -1=none, year otherwise) + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param int $min_year Offset of minimum year into list (by default current year -10) + * @param int $max_year Offset of maximum year into list (by default current year + 5) + * @param int $offset Offset + * @param int $invert Invert + * @param string $option Option + * @param string $morecss More css + * @param bool $addjscombo Add js combo + * @return string + */ + public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp', $addjscombo = false) + { + $out = ''; - $currentyear = date("Y") + $offset; - $max_year = $currentyear + $max_year; - $min_year = $currentyear - $min_year; - if (empty($selected) && empty($useempty)) $selected = $currentyear; + // Add code for jquery to use multiselect + if ($addjscombo) + { + // Enhance with select2 + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out .= ajax_combobox($htmlname); + } - $out .= '\n"; + $currentyear = date("Y") + $offset; + $max_year = $currentyear + $max_year; + $min_year = $currentyear - $min_year; + if (empty($selected) && empty($useempty)) $selected = $currentyear; - return $out; - } + $out .= '\n"; + + return $out; + } - /** - * Get array with HTML tabs with boxes of a particular area including personalized choices of user. - * Class 'Form' must be known. - * - * @param User $user Object User - * @param String $areacode Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes() + /** + * Get array with HTML tabs with boxes of a particular area including personalized choices of user. + * Class 'Form' must be known. + * + * @param User $user Object User + * @param String $areacode Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes() * @return array array('selectboxlist'=>, 'boxactivated'=>, 'boxlista'=>, 'boxlistb'=>) - */ - public static function getBoxesArea($user, $areacode) - { - global $conf, $langs, $db; + */ + public static function getBoxesArea($user, $areacode) + { + global $conf, $langs, $db; - include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; - $confuserzone = 'MAIN_BOXES_'.$areacode; + $confuserzone = 'MAIN_BOXES_'.$areacode; - // $boxactivated will be array of boxes enabled into global setup - // $boxidactivatedforuser will be array of boxes choosed by user + // $boxactivated will be array of boxes enabled into global setup + // $boxidactivatedforuser will be array of boxes choosed by user - $selectboxlist = ''; - $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) + $selectboxlist = ''; + $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) - $boxidactivatedforuser = array(); - foreach ($boxactivated as $box) - { - if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user - } + $boxidactivatedforuser = array(); + foreach ($boxactivated as $box) + { + if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user + } - // Define selectboxlist - $arrayboxtoactivatelabel = array(); - if (!empty($user->conf->$confuserzone)) - { - $boxorder = ''; - $langs->load("boxes"); // Load label of boxes - foreach ($boxactivated as $box) - { - if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user - $label = $langs->transnoentitiesnoconv($box->boxlabel); - //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; - if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') - { - $label = $label.' '; - } - $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list - } - foreach ($boxidactivatedforuser as $boxid) - { - if (empty($boxorder)) $boxorder .= 'A:'; + // Define selectboxlist + $arrayboxtoactivatelabel = array(); + if (!empty($user->conf->$confuserzone)) + { + $boxorder = ''; + $langs->load("boxes"); // Load label of boxes + foreach ($boxactivated as $box) + { + if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user + $label = $langs->transnoentitiesnoconv($box->boxlabel); + //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; + if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') + { + $label = $label.' '; + } + $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list + } + foreach ($boxidactivatedforuser as $boxid) + { + if (empty($boxorder)) $boxorder .= 'A:'; $boxorder .= $boxid.','; - } + } - //var_dump($boxidactivatedforuser); + //var_dump($boxidactivatedforuser); - // Class Form must have been already loaded - $selectboxlist .= ''."\n"; + // Class Form must have been already loaded + $selectboxlist .= ''."\n"; $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= ''; @@ -1054,19 +1071,19 @@ class FormOther $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1); - if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' '; - $selectboxlist .= ''; - if (!empty($conf->use_javascript_ajax)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $selectboxlist .= ajax_combobox("boxcombo"); - } - } + if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' '; + $selectboxlist .= ''; + if (!empty($conf->use_javascript_ajax)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $selectboxlist .= ajax_combobox("boxcombo"); + } + } - // Javascript code for dynamic actions - if (!empty($conf->use_javascript_ajax)) - { - $selectboxlist .= ''."\n"; - } + $selectboxlist .= ''."\n"; + } - // Define boxlista and boxlistb - $nbboxactivated = count($boxidactivatedforuser); + // Define boxlista and boxlistb + $nbboxactivated = count($boxidactivatedforuser); - if ($nbboxactivated) - { - // Load translation files required by the page - $langs->loadLangs(array("boxes", "projects")); + if ($nbboxactivated) + { + // Load translation files required by the page + $langs->loadLangs(array("boxes", "projects")); - $emptybox = new ModeleBoxes($db); + $emptybox = new ModeleBoxes($db); - $boxlista .= "\n\n"; + $boxlista .= "\n\n"; - // Define $box_max_lines - $box_max_lines = 5; - if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; + // Define $box_max_lines + $box_max_lines = 5; + if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; - $ii = 0; - foreach ($boxactivated as $key => $box) - { - if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + $ii = 0; + foreach ($boxactivated as $key => $box) + { + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 - if (preg_match('/^A/i', $box->box_order)) // column A - { - $ii++; - //print 'box_id '.$boxactivated[$ii]->box_id.' '; - //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; - // Show box - $box->loadBox($box_max_lines); - $boxlista .= $box->showBox(null, null, 1); - } - } + if (preg_match('/^A/i', $box->box_order)) // column A + { + $ii++; + //print 'box_id '.$boxactivated[$ii]->box_id.' '; + //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; + // Show box + $box->loadBox($box_max_lines); + $boxlista .= $box->showBox(null, null, 1); + } + } - if ($conf->browser->layout != 'phone') - { - $emptybox->box_id = 'A'; - $emptybox->info_box_head = array(); - $emptybox->info_box_contents = array(); - $boxlista .= $emptybox->showBox(array(), array(), 1); - } - $boxlista .= "\n"; + if ($conf->browser->layout != 'phone') + { + $emptybox->box_id = 'A'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlista .= $emptybox->showBox(array(), array(), 1); + } + $boxlista .= "\n"; - $boxlistb .= "\n\n"; + $boxlistb .= "\n\n"; - $ii = 0; - foreach ($boxactivated as $key => $box) - { - if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; - if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 - if (preg_match('/^B/i', $box->box_order)) // colonne B - { - $ii++; - //print 'box_id '.$boxactivated[$ii]->box_id.' '; - //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; - // Show box - $box->loadBox($box_max_lines); - $boxlistb .= $box->showBox(null, null, 1); - } - } + $ii = 0; + foreach ($boxactivated as $key => $box) + { + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 + if (preg_match('/^B/i', $box->box_order)) // colonne B + { + $ii++; + //print 'box_id '.$boxactivated[$ii]->box_id.' '; + //print 'box_order '.$boxactivated[$ii]->box_order.'
    '; + // Show box + $box->loadBox($box_max_lines); + $boxlistb .= $box->showBox(null, null, 1); + } + } - if ($conf->browser->layout != 'phone') - { - $emptybox->box_id = 'B'; - $emptybox->info_box_head = array(); - $emptybox->info_box_contents = array(); - $boxlistb .= $emptybox->showBox(array(), array(), 1); - } + if ($conf->browser->layout != 'phone') + { + $emptybox->box_id = 'B'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlistb .= $emptybox->showBox(array(), array(), 1); + } - $boxlistb .= "\n"; - } + $boxlistb .= "\n"; + } - return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); - } + return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select list of a dictionary - * - * @param string $htmlname Name of select zone - * @param string $dictionarytable Dictionary table - * @param string $keyfield Field for key - * @param string $labelfield Label field - * @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 - * @return void - */ - public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '') - { - // phpcs:enable - global $langs, $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return a HTML select list of a dictionary + * + * @param string $htmlname Name of select zone + * @param string $dictionarytable Dictionary table + * @param string $keyfield Field for key + * @param string $labelfield Label field + * @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 + * @return void + */ + public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '') + { + // phpcs:enable + global $langs, $conf; - $langs->load("admin"); + $langs->load("admin"); - $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; - $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; - $sql .= " ORDER BY ".$labelfield; + $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; + $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; + $sql .= " ORDER BY ".$labelfield; - dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) - { - print ''; + if ($useempty == 1 || ($useempty == 2 && $num > 1)) + { + print ''; + } - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid || $selected == $obj->$keyfield) - { - print ''; - $i++; - } - print ""; - } else { - print $langs->trans("DictionaryEmpty"); - } - } else { - dol_print_error($this->db); - } - } + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + if ($selected == $obj->rowid || $selected == $obj->$keyfield) + { + print ''; + $i++; + } + print ""; + } else { + print $langs->trans("DictionaryEmpty"); + } + } else { + dol_print_error($this->db); + } + } - /** + /** * Return an html string with a select combo box to choose yes or no * * @param string $htmlname Name of html select field @@ -1278,7 +1295,7 @@ class FormOther * @param int $useempty 1=Add empty line * @return string See option */ - public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) + public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) { global $langs; diff --git a/htdocs/core/class/html.formprojet.class.php b/htdocs/core/class/html.formprojet.class.php index 6fad72862c7..1e5558546da 100644 --- a/htdocs/core/class/html.formprojet.class.php +++ b/htdocs/core/class/html.formprojet.class.php @@ -170,7 +170,7 @@ class FormProjets if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY)) $sql .= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)"; elseif ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all') // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma. { - $sql .= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)"; + $sql .= " AND (p.fk_soc IN (".$socid.", ".((int) $conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY).") OR p.fk_soc IS NULL)"; } } if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey); @@ -261,7 +261,8 @@ class FormProjets 'key' => (int) $obj->rowid, 'value' => $obj->ref, 'ref' => $obj->ref, - 'label' => $labeltoshow, + 'labelx' => $labeltoshow, + 'label' => ((bool) $disabled) ? ''.$labeltoshow.'' : $labeltoshow, 'disabled' => (bool) $disabled ); } @@ -297,7 +298,7 @@ class FormProjets * @param int $maxlength Maximum length of label * @param int $option_only Return only html options lines without the select tag * @param string $show_empty Add an empty line ('1' or string to show for empty line) - * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable) + * @param int $discard_closed Discard closed projects (0=Keep, 1=hide completely, 2=Disable) * @param int $forcefocus Force focus on field (works with javascript only) * @param int $disabled Disabled * @param string $morecss More css added to the select component @@ -348,12 +349,12 @@ class FormProjets if ($resql) { // Use select2 selector - if (!empty($conf->use_javascript_ajax)) + if (empty($option_only) && !empty($conf->use_javascript_ajax)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus); $out .= $comboenhancement; - $morecss = 'minwidth200imp maxwidth500'; + $morecss = 'minwidth200 maxwidth500'; } if (empty($option_only)) { @@ -368,6 +369,7 @@ class FormProjets } else $out .= ' '; $out .= ''; } + $num = $this->db->num_rows($resql); $i = 0; if ($num) @@ -388,6 +390,18 @@ class FormProjets $labeltoshow = ''; + $disabled = 0; + if ($obj->fk_statut == Project::STATUS_DRAFT) + { + $disabled = 1; + } elseif ($obj->fk_statut == Project::STATUS_CLOSED) + { + if ($discard_closed == 2) $disabled = 1; + } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) + { + $disabled = 1; + } + if ($showproject == 'all') { $labeltoshow .= dol_trunc($obj->ref, 18); // Project ref diff --git a/htdocs/core/class/html.formpropal.class.php b/htdocs/core/class/html.formpropal.class.php index e1653444960..730133eae27 100644 --- a/htdocs/core/class/html.formpropal.class.php +++ b/htdocs/core/class/html.formpropal.class.php @@ -102,7 +102,7 @@ class FormPropal } } - print ''; if ($showempty) print ''; foreach ($listofstatus as $key => $obj) @@ -135,5 +135,7 @@ class FormPropal $i++; } print ''; + + print ajax_combobox($htmlname); } } diff --git a/htdocs/core/class/html.formsocialcontrib.class.php b/htdocs/core/class/html.formsocialcontrib.class.php index b5adfdba82f..e3a063b0d69 100644 --- a/htdocs/core/class/html.formsocialcontrib.class.php +++ b/htdocs/core/class/html.formsocialcontrib.class.php @@ -59,17 +59,18 @@ class FormSocialContrib * @param int $maxlen Max length of text in combo box * @param int $help Add or not the admin help picto * @param string $morecss Add more CSS on select + * @param int $noerrorifempty No print error if list is empty for the country * @return void */ - public function select_type_socialcontrib($selected = '', $htmlname = 'actioncode', $useempty = 0, $maxlen = 40, $help = 1, $morecss = 'minwidth300') + public function select_type_socialcontrib($selected = '', $htmlname = 'actioncode', $useempty = 0, $maxlen = 40, $help = 1, $morecss = 'minwidth300', $noerrorifempty = 0) { // phpcs:enable global $conf, $db, $langs, $user, $mysoc; if (empty($mysoc->country_id) && empty($mysoc->country_code)) { - dol_print_error('', 'Call to select_type_socialcontrib with mysoc country not yet defined'); - exit; + print $langs->trans("ErrorSetupOfCountryMustBeDone"); + return; } if (!empty($mysoc->country_id)) @@ -110,7 +111,7 @@ class FormSocialContrib if ($user->admin && $help) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); if (!empty($conf->use_javascript_ajax)) print ajax_combobox($htmlname); } else { - print $langs->trans("ErrorNoSocialContributionForSellerCountry", $mysoc->country_code); + if (empty($noerrorifempty)) print $langs->trans("ErrorNoSocialContributionForSellerCountry", $mysoc->country_code); } } else { dol_print_error($this->db); diff --git a/htdocs/core/class/menubase.class.php b/htdocs/core/class/menubase.class.php index 3c0c6bd9389..8695ef88ef4 100644 --- a/htdocs/core/class/menubase.class.php +++ b/htdocs/core/class/menubase.class.php @@ -173,6 +173,7 @@ class Menubase global $conf, $langs; // Clean parameters + if (!isset($this->enabled)) $this->enabled = '1'; $this->menu_handler = trim($this->menu_handler); $this->module = trim($this->module); $this->type = trim($this->type); diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index cb290a49c07..8af9f7bbc25 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -90,7 +90,7 @@ abstract class DoliDB implements Database public function idate($param) { // TODO GMT $param should be gmt, so we should add tzouptut to 'gmt' - return dol_print_date($param, "%Y-%m-%d %H:%M:%S"); + return dol_print_date($param, "%Y-%m-%d %H:%M:%S", 'tzserver'); } /** @@ -106,12 +106,17 @@ abstract class DoliDB implements Database /** * Sanitize a string for SQL forging * - * @param string $stringtosanitize String to escape + * @param string $stringtosanitize String to escape + * @param int $allowsimplequote Allow simple quote * @return string String escaped */ - public function sanitize($stringtosanitize) + public function sanitize($stringtosanitize, $allowsimplequote = 0) { - return preg_replace('/[^a-z0-9_\-\.,]/i', '', $stringtosanitize); + if ($allowsimplequote) { + return preg_replace('/[^a-z0-9_\-\.,\']/i', '', $stringtosanitize); + } else { + return preg_replace('/[^a-z0-9_\-\.,]/i', '', $stringtosanitize); + } } /** diff --git a/htdocs/core/db/pgsql.class.php b/htdocs/core/db/pgsql.class.php index 3c49bcf6f4b..d24b4e98189 100644 --- a/htdocs/core/db/pgsql.class.php +++ b/htdocs/core/db/pgsql.class.php @@ -234,8 +234,11 @@ class DoliDBPgsql extends DoliDB // on update defaulted by now $line = preg_replace('/(\s*)tms(\s*)timestamp/i', '\\1tms timestamp without time zone DEFAULT now() NOT NULL', $line); + // nuke DEFAULT CURRENT_TIMESTAMP + $line = preg_replace('/(\s*)DEFAULT(\s*)CURRENT_TIMESTAMP/i', '\\1', $line); + // nuke ON UPDATE CURRENT_TIMESTAMP - $line = preg_replace('/(\s*)on(\s*)update(\s*)CURRENT_TIMESTAMP/i', '\\1', $line); + $line = preg_replace('/(\s*)ON(\s*)UPDATE(\s*)CURRENT_TIMESTAMP/i', '\\1', $line); // unique index(field1,field2) if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i', $line)) diff --git a/htdocs/core/js/lib_notification.js.php b/htdocs/core/js/lib_notification.js.php index a95e3556405..8ecca4da2df 100644 --- a/htdocs/core/js/lib_notification.js.php +++ b/htdocs/core/js/lib_notification.js.php @@ -77,10 +77,10 @@ if (!($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root.'/' || $_SERVER['HTTP data: { time_js_next_test: time_js_next_test, forcechecknow: 1, token: 'notrequired' }, dataType: "json", success: function (result) { - console.log(result); + //console.log(result); var arrayofpastreminders = Object.values(result.pastreminders); - console.log("arrayofpastreminders.length"+arrayofpastreminders.length); if (arrayofpastreminders && arrayofpastreminders.length > 0) { + console.log("Retreived "+arrayofpastreminders.length+" reminders to do."); var audio = null; global->AGENDA_REMINDER_BROWSER_SOUND)) { @@ -145,7 +145,7 @@ if (!($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root.'/' || $_SERVER['HTTP data: { time_js_next_test: time_js_next_test, token: 'notrequired' } }); } else { - console.log("No past reminder found, next try at "+time_js_next_test); + console.log("No reminder to do found, next search at "+time_js_next_test); } } }); diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index 038b4be27a6..49ababf4a25 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -45,7 +45,7 @@ function versiontostring($versionarray) /** * Compare 2 versions (stored into 2 arrays). * To check if Dolibarr version is lower than (x,y,z), do "if versioncompare(versiondolibarrarray(), array(x.y.z)) <= 0" - * For example: if (versioncompare(versiondolibarrarray(),array(4,0,-4)) >= 0) is true if version is 4.0 alpha or higher. + * For example: if (versioncompare(versiondolibarrarray(),array(4,0,-5)) >= 0) is true if version is 4.0 alpha or higher. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,0)) >= 0) is true if version is 4.0 final or higher. * For example: if (versioncompare(versiondolibarrarray(),array(4,0,1)) >= 0) is true if version is 4.0.1 or higher. * Alternative way to compare: if ((float) DOL_VERSION >= 4.0) is true if version is 4.0 alpha or higher (works only to compare first and second level) diff --git a/htdocs/core/lib/agenda.lib.php b/htdocs/core/lib/agenda.lib.php index 43408a38373..0a4d57658d7 100644 --- a/htdocs/core/lib/agenda.lib.php +++ b/htdocs/core/lib/agenda.lib.php @@ -157,7 +157,7 @@ function print_actions_filter($form, $canedit, $status, $year, $month, $day, $sh */ function show_array_actions_to_do($max = 5) { - global $langs, $conf, $user, $db, $bc, $socid; + global $langs, $conf, $user, $db, $socid; $now = dol_now(); @@ -171,7 +171,7 @@ function show_array_actions_to_do($max = 5) $sql .= " ".MAIN_DB_PREFIX."c_actioncomm as c ON c.id = a.fk_action"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE a.entity = ".$conf->entity; + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($socid) $sql .= " AND s.rowid = ".$socid; @@ -223,7 +223,7 @@ function show_array_actions_to_do($max = 5) $datep2 = $db->jdate($obj->dp2); // Date - print '
    '.dol_print_date($datep, 'day').' '; + print ''.dol_print_date($datep, 'day').' '; $late = 0; if ($obj->percent == 0 && $datep && $datep < time()) $late = 1; if ($obj->percent == 0 && !$datep && $datep2 && $datep2 < time()) $late = 1; @@ -256,7 +256,7 @@ function show_array_actions_to_do($max = 5) */ function show_array_last_actions_done($max = 5) { - global $langs, $conf, $user, $db, $bc, $socid; + global $langs, $conf, $user, $db, $socid; $now = dol_now(); @@ -267,7 +267,7 @@ function show_array_last_actions_done($max = 5) $sql .= " ".MAIN_DB_PREFIX."c_actioncomm as c ON c.id = a.fk_action "; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE a.entity = ".$conf->entity; + $sql .= " WHERE a.entity IN (".getEntity('agenda').")"; $sql .= " AND (a.percent >= 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($socid) $sql .= " AND s.rowid = ".$socid; @@ -315,11 +315,11 @@ function show_array_last_actions_done($max = 5) print ''.dol_print_date($db->jdate($obj->da2), 'day'); + print ''.dol_print_date($db->jdate($obj->da2), 'day'); print "".$staticaction->LibStatut($obj->percent, 3)."'.$staticaction->LibStatut($obj->percent, 3)."
    '; + print ''; if ($sortfield) $options .= "&sortfield=".urlencode($sortfield); if ($sortorder) $options .= "&sortorder=".urlencode($sortorder); // Show navigation bar @@ -5575,7 +5624,7 @@ function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = $temp = preg_replace('/]*>/i', "\n", $stringtoclean); // We remove entities BEFORE stripping (in case of a separator char is encoded and not the other, the strip will fails) - $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto); + $temp = dol_html_entity_decode($temp, ENT_COMPAT|ENT_HTML5, $pagecodeto); if ($strip_tags) { $temp = strip_tags($temp); @@ -5604,13 +5653,14 @@ function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = * Clean a string to keep only desirable HTML tags. * * @param string $stringtoclean String to clean - * @param boolean $cleanalsosomestyles Remove absolute/fixed positioning from inline styles - * @param boolean $removeclassattribute Remove the class attribute from tags + * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles + * @param int $removeclassattribute Remove the class attribute from tags + * @param int $cleanalsojavascript Remove also occurence of (javascript:' * @return string String cleaned * * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags() */ -function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1) +function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0) { $allowed_tags = array( "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link", @@ -5620,22 +5670,29 @@ function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $allowed_tags_string = join("><", $allowed_tags); $allowed_tags_string = '<'.$allowed_tags_string.'>'; - if ($cleanalsosomestyles) { - $stringtoclean = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $stringtoclean); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless - } - if ($removeclassattribute) { - $stringtoclean = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $stringtoclean); - } - // TODO Remove '/href=("|\'|)javascript/' string ? + $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0); + $stringtoclean = preg_replace('/:/i', ':', $stringtoclean); $temp = strip_tags($stringtoclean, $allowed_tags_string); + if ($cleanalsosomestyles) { // Clean for remaining html tags + $stringtoclean = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $temp); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless + } + if ($removeclassattribute) { // Clean for remaining html tags + $stringtoclean = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp); + } + + // Remove 'javascript:' that we should not find into a text with + if ($cleanalsojavascript) { + $temp = preg_replace('/javascript\s*:/i', '', $temp); + } + return $temp; } /** * Clean a string from some undesirable HTML tags. - * Note. Not enough secured as dol_string_onlythesehtmltags(). + * Note. Not as secured as dol_string_onlythesehtmltags(). * * @param string $stringtoclean String to clean * @param array $disallowed_tags Array of tags not allowed @@ -5779,7 +5836,7 @@ function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UT */ function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8') { - $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT, $pagecodeto); + $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT|ENT_HTML5, $pagecodeto); $ret = preg_replace('/'."\r\n".'/i', "
    ", $ret); $ret = preg_replace('/'."\r\n".'/i', "\r\n", $ret); $ret = preg_replace('/'."\n".'/i', "\n", $ret); @@ -5803,7 +5860,7 @@ function dol_htmlcleanlastbr($stringtodecode) * Replace html_entity_decode functions to manage errors * * @param string $a Operand a - * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes) + * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...) * @param string $c Operand c * @param string $keepsomeentities Entities but &, <, >, " are not converted. * @return string String decoded @@ -7800,7 +7857,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) $numnewcrit = price2num($newcrit); if (is_numeric($numnewcrit)) { - $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric + $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric } else { $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false } @@ -7808,7 +7865,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) } } elseif ($mode == 2 || $mode == -2) { - $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer + $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : ''); $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)"; if ($mode == -2) $newres .= ' OR '.$field.' IS NULL'; @@ -7828,7 +7885,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) $listofcodes .= "'".$db->escape($val)."'"; } } - $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes).")"; + $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")"; $i2++; // a criteria was added to string } if ($mode == -3) $newres .= ' OR '.$field.' IS NULL'; @@ -8336,7 +8393,7 @@ function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = ' /** - * Function dolGetStatus + * Output the badge of a status. * * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility * @param string $statusLabelShort Short label of badge no html @@ -8344,7 +8401,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 for future : recommended rather than adding more function arguments + * @param array $params Various params. Example: array('tooltip'=>'...', 'badgeParams'=>...) * @return string Html status string */ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array()) @@ -8413,7 +8470,7 @@ function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $st $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort); $dolGetBadgeParams['attr']['class'] = 'badge-status'; - $dolGetBadgeParams['attr']['title'] = $statusLabel; + $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : $params['tooltip']; if ($displayMode == 3) { $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams); @@ -8946,8 +9003,8 @@ function readfileLowMemory($fullpath_original_file_osencoded, $method = -1) if ($method == -1) { $method = 0; - if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1; - if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2; + if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1; + if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2; } // Be sure we don't have output buffering enabled to have readfile working correctly diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 7cc14060aac..0c06d845843 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -66,7 +66,7 @@ function jsUnEscape($source) $pos++; } } - return dol_html_entity_decode($decodedStr, ENT_COMPAT); + return dol_html_entity_decode($decodedStr, ENT_COMPAT|ENT_HTML5); } @@ -2384,3 +2384,77 @@ function price2fec($amount) return $output; } + +/** + * Check the syntax of some PHP code. + * + * @param string $code PHP code to check. + * @return boolean|array If false, then check was successful, otherwise an array(message,line) of errors is returned. + */ +function phpSyntaxError($code) +{ + if (!defined("CR")) define("CR", "\r"); + if (!defined("LF")) define("LF", "\n"); + if (!defined("CRLF")) define("CRLF", "\r\n"); + + $braces=0; + $inString=0; + foreach (token_get_all(' + * Copyright (C) 2015 ATM Consulting + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/lib/intracommreport.lib.php + * \ingroup Intracomm report + * \brief Library of intracomm report functions + */ + +/** + * Prepare array with list of admin tabs + * + * @return array Array of tabs to show + */ +function intracommReportAdminPrepareHead() +{ + global $langs, $conf; + + $langs->load("intracommreport"); + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/intracommreport/admin/intracommreport.php'; + $head[$h][1] = $langs->trans("Parameters"); + $head[$h][2] = 'general'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'intracommreport_admin'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'intracommreport_admin', 'remove'); + return $head; +} + +/** + * Prepare array with list of tabs + * + * @param Object $object Object related to tabs + * + * @return array Array of tabs to show + */ +function intracommReportPrepareHead($object) +{ + global $langs, $conf; + + $langs->load("intracommreport"); + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/intracommreport/card.php?rowid='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'intracommreport'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'intracommreport', 'remove'); + return $head; +} diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index 4fb593e354d..601dad3275d 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -29,30 +29,30 @@ function payment_prepare_head(Paiement $object) { - global $langs, $conf; + global $langs, $conf; - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("Payment"); - $head[$h][2] = 'payment'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("Payment"); + $head[$h][2] = 'payment'; + $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment'); - $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment', 'remove'); - return $head; + return $head; } /** @@ -64,30 +64,30 @@ function payment_prepare_head(Paiement $object) */ function bankline_prepare_head($id) { - global $langs, $conf; + global $langs, $conf; - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id; - $head[$h][1] = $langs->trans('BankTransaction'); - $head[$h][2] = 'bankline'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id; + $head[$h][1] = $langs->trans('BankTransaction'); + $head[$h][2] = 'bankline'; + $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline'); - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove'); - return $head; + return $head; } /** @@ -109,11 +109,11 @@ function payment_supplier_prepare_head(Paiement $object) $head[$h][2] = 'payment'; $h++; - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_supplier'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_supplier'); $head[$h][0] = DOL_URL_ROOT.'/fourn/paiement/info.php?id='.$object->id; $head[$h][1] = $langs->trans('Info'); @@ -170,7 +170,7 @@ function showOnlinePaymentUrl($type, $ref) global $langs; // Load translation files required by the page - $langs->loadLangs(array('payment', 'stripe')); + $langs->loadLangs(array('payment', 'stripe')); $servicename = $langs->transnoentitiesnoconv('Online'); @@ -194,7 +194,7 @@ function showOnlinePaymentUrl($type, $ref) */ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_tag', $localorexternal = 0) { - global $conf, $dolibarr_main_url_root; + global $conf, $dolibarr_main_url_root; $ref = str_replace(' ', '', $ref); $out = ''; @@ -209,7 +209,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag if ($type == 'free') { - $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; @@ -218,7 +218,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag //if ($mode) $out.='&noidempotency=1'; } elseif ($type == 'order') { - $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'order_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -234,7 +234,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } } elseif ($type == 'invoice') { - $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'invoice_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -250,7 +250,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } } elseif ($type == 'contractline') { - $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'contractline_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -266,7 +266,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } } elseif ($type == 'member' || $type == 'membersubscription') { - $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'member_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -283,7 +283,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } if ($type == 'donation') { - $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'donation_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -319,82 +319,82 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag */ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, $suffix = '', $object = null) { - global $conf; + global $conf; - // Juridical status - $line1 = ""; - if ($fromcompany->forme_juridique_code) - { - $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); - } - // Capital - if ($fromcompany->capital) - { - $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); - } - // Prof Id 1 - if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) - { - $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; - } - // Prof Id 2 - if ($fromcompany->idprof2) - { - $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; - } + // Juridical status + $line1 = ""; + if ($fromcompany->forme_juridique_code) + { + $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); + } + // Capital + if ($fromcompany->capital) + { + $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); + } + // Prof Id 1 + if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) + { + $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; + } + // Prof Id 2 + if ($fromcompany->idprof2) + { + $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; + } - // Second line of company infos - $line2 = ""; - // Prof Id 3 - if ($fromcompany->idprof3) - { - $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; - } - // Prof Id 4 - if ($fromcompany->idprof4) - { - $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; - } - // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { - $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; - } + // Second line of company infos + $line2 = ""; + // Prof Id 3 + if ($fromcompany->idprof3) + { + $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; + } + // Prof Id 4 + if ($fromcompany->idprof4) + { + $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; + } + // IntraCommunautary VAT + if ($fromcompany->tva_intra != '') + { + $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; + } - print '
    '; + print '
    '; - print '
    '."\n"; - if ($addformmessage) - { - print ''; - print '
    '; + print '
    '."\n"; + if ($addformmessage) + { + print ''; + print '
    '; - $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; - if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); + $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; + if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); + elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); - // Add other message if VAT exists - if ($object->total_vat != 0 || $object->total_tva != 0) - { - $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix; - if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); - } - } + // Add other message if VAT exists + if ($object->total_vat != 0 || $object->total_tva != 0) + { + $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix; + if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); + elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); + } + } - print '

    '."\n"; - print $fromcompany->name.'
    '; - print $line1; - if (strlen($line1.$line2) > 50) print '
    '; - else print ' - '; - print $line2; - print '
    '."\n"; + print '

    '."\n"; + print $fromcompany->name.'
    '; + print $line1; + if (strlen($line1.$line2) > 50) print '
    '; + else print ' - '; + print $line2; + print '
    '."\n"; } diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 6232afe962e..4156b89a2ab 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -122,7 +122,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') define('K_SMALL_RATIO', 2 / 3); define('K_THAI_TOPCHARS', true); define('K_TCPDF_CALLS_IN_HTML', true); - if (! empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) { + if (!empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) { define('K_TCPDF_THROW_EXCEPTION_ERROR', true); } else { define('K_TCPDF_THROW_EXCEPTION_ERROR', false); @@ -1260,7 +1260,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, // Manage HTML entities description test because $prodser->description is store with htmlentities but $desc no $textwasmodified = false; if (!empty($desc) && dol_textishtml($desc) && !empty($prodser->description) && dol_textishtml($prodser->description)) { - $textwasmodified = (strpos(dol_html_entity_decode($desc, ENT_QUOTES | ENT_HTML401), dol_html_entity_decode($prodser->description, ENT_QUOTES | ENT_HTML401)) !== false); + $textwasmodified = (strpos(dol_html_entity_decode($desc, ENT_QUOTES|ENT_HTML5), dol_html_entity_decode($prodser->description, ENT_QUOTES|ENT_HTML5)) !== false); } else { $textwasmodified = ($desc == $prodser->description); } @@ -1959,9 +1959,9 @@ function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0) { if ($object->lines[$i]->special_code == 3) { - return $outputlangs->transnoentities("Option"); + $result .= $outputlangs->transnoentities("Option"); } - if (empty($hidedetails) || $hidedetails > 1) + elseif (empty($hidedetails) || $hidedetails > 1) { $total_ht = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht); if ($object->lines[$i]->situation_percent > 0) @@ -2017,7 +2017,25 @@ function pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails = 0) if ($object->lines[$i]->special_code == 3) { $result .= $outputlangs->transnoentities("Option"); - } elseif (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * ($object->lines[$i]->total_ht) + ($object->lines[$i]->total_ht) * ($object->lines[$i]->tva_tx) / 100, 0, $outputlangs); + } + elseif (empty($hidedetails) || $hidedetails > 1) + { + $total_ttc = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ttc : $object->lines[$i]->total_ttc); + if ($object->lines[$i]->situation_percent > 0) + { + // TODO Remove this. The total should be saved correctly in database instead of being modified here. + $prev_progress = 0; + $progress = 1; + if (method_exists($object->lines[$i], 'get_prev_progress')) + { + $prev_progress = $object->lines[$i]->get_prev_progress($object->id); + $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; + } + $result .= price($sign * ($total_ttc / ($object->lines[$i]->situation_percent / 100)) * $progress, 0, $outputlangs); + } else { + $result .= price($sign * $total_ttc, 0, $outputlangs); + } + } } return $result; } @@ -2140,11 +2158,11 @@ function pdf_getLinkedObjects($object, $outputlangs) if (empty($object->linkedObjects['commande']) && $object->element != 'commande') // There is not already a link to order and object is not the order, so we show also info with order { $elementobject->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); - if (! empty($elementobject->linkedObjectsIds['commande'])){ + if (!empty($elementobject->linkedObjectsIds['commande'])) { include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $order = new Commande($db); $ret = $order->fetch(reset($elementobject->linkedObjectsIds['commande'])); - if ($ret < 1) { $order=null; } + if ($ret < 1) { $order = null; } } } if (!is_object($order)) diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php index dfc57313add..8c0253e927c 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -346,6 +346,7 @@ function product_lot_admin_prepare_head() function show_stats_for_company($product, $socid) { global $conf, $langs, $user, $db; + $form = new Form($db); $nblines = 0; @@ -356,25 +357,7 @@ function show_stats_for_company($product, $socid) print '
    '.$langs->trans("TotalQuantity").'
    '; - print ''.img_object('', 'mrp').' '.$langs->trans("MO").''; - print ''; - print $product->stats_mo['suppliers']; - print ''; - print $product->stats_mo['nb']; - print ''; - print $product->stats_mo['qty']; - print '
    '; + print ''.img_object('', 'mrp').' '.$langs->trans("BOM").''; + print ''; + + print ''; + print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("QtyToProduce")); + print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("ToConsume")); + print ''; + print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("QtyToProduce")); + print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("ToConsume")); + print '
    '; + print ''.img_object('', 'mrp').' '.$langs->trans("MO").''; + print ''; + print $form->textwithpicto($product->stats_mo['customers_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_mo['customers_consumed'], $langs->trans("QtyAlreadyConsumed")); + print $form->textwithpicto($product->stats_mo['customers_toproduce'], $langs->trans("QtyToProduce")); + print $form->textwithpicto($product->stats_mo['customers_produced'], $langs->trans("QtyAlreadyProduced")); + print ''; + print $form->textwithpicto($product->stats_mo['nb_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_mo['nb_consumed'], $langs->trans("QtyAlreadyConsumed")); + print $form->textwithpicto($product->stats_mo['nb_toproduce'], $langs->trans("QtyToProduce")); + print $form->textwithpicto($product->stats_mo['nb_produced'], $langs->trans("QtyAlreadyProduced")); + print ''; + print $form->textwithpicto($product->stats_mo['qty_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_mo['qty_consumed'], $langs->trans("QtyAlreadyConsumed")); + print $form->textwithpicto($product->stats_mo['qty_toproduce'], $langs->trans("QtyToProduce")); + print $form->textwithpicto($product->stats_mo['qty_produced'], $langs->trans("QtyAlreadyProduced")); + print '
    '; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1, array()), ''), 'THEME_ELDY_TOPMENU_BACK1', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1, array()), ''), 'THEME_ELDY_TOPMENU_BACK1', 'formcolor', 1, '', '', 'colorbackhmenu1').' '; } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1, array()), ''); if ($color) print ''; @@ -612,7 +613,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1, array()), ''), 'THEME_ELDY_VERMENU_BACK1', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1, array()), ''), 'THEME_ELDY_VERMENU_BACK1', 'formcolor', 1, '', '', 'colorbackvmenu1').' '; } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1, array()), ''); if ($color) print ''; @@ -635,7 +636,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLENOTAB, array()), ''), 'THEME_ELDY_TEXTTITLENOTAB', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLENOTAB, array()), ''), 'THEME_ELDY_TEXTTITLENOTAB', 'formcolor', 1, '', '', 'colortexttitlenotab').' '; } else { print $formother->showColor($conf->global->THEME_ELDY_TEXTTITLENOTAB, $langs->trans("Default")); } @@ -657,7 +658,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKTITLE1, array()), ''), 'THEME_ELDY_BACKTITLE1', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKTITLE1, array()), ''), 'THEME_ELDY_BACKTITLE1', 'formcolor', 1, '', '', 'colorbacktitle1').' '; } else { print $formother->showColor($conf->global->THEME_ELDY_BACKTITLE1, $langs->trans("Default")); } @@ -679,7 +680,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLE, array()), ''), 'THEME_ELDY_TEXTTITLE', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLE, array()), ''), 'THEME_ELDY_TEXTTITLE', 'formcolor', 1, '', '', 'colortexttitle').' '; } else { print $formother->showColor($conf->global->THEME_ELDY_TEXTTITLE, $langs->trans("Default")); } @@ -701,7 +702,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLELINK, array()), ''), 'THEME_ELDY_TEXTTITLELINK', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLELINK, array()), ''), 'THEME_ELDY_TEXTTITLELINK', 'formcolor', 1, '', '', 'colortexttitlelink').' '; } else { print $formother->showColor($conf->global->THEME_ELDY_TEXTTITLELINK, $langs->trans("Default")); } @@ -724,7 +725,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1, array()), ''), 'THEME_ELDY_LINEIMPAIR1', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1, array()), ''), 'THEME_ELDY_LINEIMPAIR1', 'formcolor', 1, '', '', 'colorbacklinepair2').' '; } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1, array()), ''); if ($color) print ''; @@ -747,7 +748,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1, array()), ''), 'THEME_ELDY_LINEPAIR1', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1, array()), ''), 'THEME_ELDY_LINEPAIR1', 'formcolor', 1, '', '', 'colorbacklineimpair2').' '; } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1, array()), ''); if ($color) print ''; @@ -790,7 +791,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK, array()), ''), 'THEME_ELDY_TEXTLINK', 'formcolor', 1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK, array()), ''), 'THEME_ELDY_TEXTLINK', 'formcolor', 1, '', '', 'colortextlink').' '; } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK, array()), ''); if ($color) print ''; @@ -831,7 +832,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) { if ($conf->global->THEME_ELDY_USE_HOVER == '1') $color = colorArrayToHex(colorStringToArray($colorbacklinepairhover)); else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_HOVER, array()), ''); - print $formother->selectColor($color, 'THEME_ELDY_USE_HOVER', 'formcolor', 1).' '; + print $formother->selectColor($color, 'THEME_ELDY_USE_HOVER', 'formcolor', 1, '', '', 'colorbacklinepairhover').' '; } else { if ($conf->global->THEME_ELDY_USE_HOVER == '1') $color = colorArrayToHex(colorStringToArray($colorbacklinepairhover)); else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_HOVER, array()), ''); @@ -871,7 +872,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) { if ($conf->global->THEME_ELDY_USE_CHECKED == '1') $color = 'e6edf0'; else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_CHECKED, array()), ''); - print $formother->selectColor($color, 'THEME_ELDY_USE_CHECKED', 'formcolor', 1).' '; + print $formother->selectColor($color, 'THEME_ELDY_USE_CHECKED', 'formcolor', 1, '', '', 'colorbacklinepairchecked').' '; } else { if ($conf->global->THEME_ELDY_USE_CHECKED == '1') $color = 'e6edf0'; else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_CHECKED, array()), ''); diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql index 25ef112b39b..818198fc035 100644 --- a/htdocs/core/menus/init_menu_auguria.sql +++ b/htdocs/core/menus/init_menu_auguria.sql @@ -289,10 +289,12 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left --insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2708__+MAX_llx_menu__, 'accountancy', '', 2705__+MAX_llx_menu__, '/accountancy/journal/expensereportsjournal.php?mainmenu=accountancy&leftmenu=accountancy_journal&id_journal=6', 'ExpenseReportJournal', 2, 'main', '$user->rights->compta->resultat->lire || $user->rights->accounting->comptarapport->lire', '', 0, 2, __ENTITY__); --insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2709__+MAX_llx_menu__, 'accountancy', '', 2705__+MAX_llx_menu__, '/accountancy/journal/purchasesjournal.php?mainmenu=accountancy&leftmenu=accountancy_journal&id_journal=2', 'PurchasesJournal', 2, 'main', '$user->rights->compta->resultat->lire || $user->rights->accounting->comptarapport->lire', '', 0, 3, __ENTITY__); --insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2706__+MAX_llx_menu__, 'accountancy', '', 2705__+MAX_llx_menu__, '/accountancy/journal/sellsjournal.php?mainmenu=accountancy&leftmenu=accountancy_journal&id_journal=1', 'SellsJournal', 2, 'main', '$user->rights->compta->resultat->lire || $user->rights->accounting->comptarapport->lire', '', 0, 4, __ENTITY__); - -- General Ledger - insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2430__+MAX_llx_menu__, 'accountancy', 'bookkeeping', 2400__+MAX_llx_menu__, '/accountancy/bookkeeping/list.php?mainmenu=accountancy&leftmenu=accountancy_bookeeping', 'Bookkeeping', 1, 'accountancy', '$user->rights->accounting->mouvements->lire', '', 0, 15, __ENTITY__); -- Balance - insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2435__+MAX_llx_menu__, 'accountancy', 'balance', 2400__+MAX_llx_menu__, '/accountancy/bookkeeping/balance.php?mainmenu=accountancy&leftmenu=accountancy_balance', 'AccountBalance', 1, 'accountancy', '$user->rights->accounting->mouvements->lire', '', 0, 16, __ENTITY__); + insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2430__+MAX_llx_menu__, 'accountancy', 'balance', 2400__+MAX_llx_menu__, '/accountancy/bookkeeping/balance.php?mainmenu=accountancy&leftmenu=accountancy_balance', 'AccountBalance', 1, 'accountancy', '$user->rights->accounting->mouvements->lire', '', 0, 10, __ENTITY__); + -- General Ledger + insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2432__+MAX_llx_menu__, 'accountancy', 'bookkeeping', 2400__+MAX_llx_menu__, '/accountancy/bookkeeping/listbyaccount.php?mainmenu=accountancy&leftmenu=accountancy_bookeeping', 'Bookkeeping', 1, 'accountancy', '$user->rights->accounting->mouvements->lire', '', 0, 12, __ENTITY__); + -- Journals + insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2434__+MAX_llx_menu__, 'accountancy', 'bookkeeping', 2400__+MAX_llx_menu__, '/accountancy/bookkeeping/list.php?mainmenu=accountancy&leftmenu=accountancy_bookeeping', 'Journals', 1, 'accountancy', '$user->rights->accounting->mouvements->lire', '', 0, 15, __ENTITY__); -- Export accounting documents insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->comptabilite->enabled || $conf->accounting->enabled', __HANDLER__, 'left', 2436__+MAX_llx_menu__, 'accountancy', 'accountancy_files', 2400__+MAX_llx_menu__, '/compta/accounting-files.php?mainmenu=accountancy&leftmenu=accountancy_files', 'AccountantFiles', 1, 'accountancy', '$user->rights->compta->resultat->lire || $user->rights->accounting->mouvements->lire', '', 0, 17, __ENTITY__); -- Reports diff --git a/htdocs/core/menus/standard/auguria.lib.php b/htdocs/core/menus/standard/auguria.lib.php index 8bde6d6fa61..a124759faa8 100644 --- a/htdocs/core/menus/standard/auguria.lib.php +++ b/htdocs/core/menus/standard/auguria.lib.php @@ -551,7 +551,7 @@ function print_left_auguria_menu($db, $menu_array_before, $menu_array_after, &$t { print '
    '.$langs->trans('GCP_Name').''.$langs->trans('GCP_displayName').''.$langs->trans('GCP_Id').''.$langs->trans('GCP_OwnerName').''.$langs->trans('GCP_State').''.$langs->trans('GCP_connectionStatus').''.$langs->trans('GCP_Type').''.$langs->trans("Select").'
    '.print_r($list,true).'
    '.$printer_det['name'].''.$printer_det['displayName'].''.$printer_det['id'].''.$printer_det['ownerName'].''.$printer_det['status'].''.$langs->trans('STATE_'.$printer_det['connectionStatus']).''.$langs->trans('TYPE_'.$printer_det['type']).''; - if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) - { - $html .= img_picto($langs->trans("Default"), 'on'); - } else $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; - $html .= '
    '.$langs->trans('GCP_Name').''.$langs->trans('GCP_displayName').''.$langs->trans('GCP_Id').''.$langs->trans('GCP_OwnerName').''.$langs->trans('GCP_State').''.$langs->trans('GCP_connectionStatus').''.$langs->trans('GCP_Type').''.$langs->trans("Select").'
    '.print_r($list,true).'
    '.$printer_det['name'].''.$printer_det['displayName'].''.$printer_det['id'].''.$printer_det['ownerName'].''.$printer_det['status'].''.$langs->trans('STATE_'.$printer_det['connectionStatus']).''.$langs->trans('TYPE_'.$printer_det['type']).''; + if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) + { + $html .= img_picto($langs->trans("Default"), 'on'); + } else $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; + $html .= '
    '.print_r($response, true).'
    '.print_r($response, true).'
    '.print_r($response, true).'
    '.print_r($response, true).'
    '; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''."\n"; + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + } + // Getting Jobs + // Send a request with api + try { + $response = $apiService->request(self::PRINTERS_GET_JOBS); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + $responsedata = json_decode($response, true); + //$html .= '
    '.print_r($responsedata,true).'
    '; + $html .= '
    '; + $html .= '
    '.$langs->trans("Id").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Printer").''.$langs->trans("Filename").''.$langs->trans("Status").''.$langs->trans("Cancel").'
    '; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''."\n"; - $jobs = $responsedata['jobs']; - //$html .= '
    '.print_r($jobs['0'],true).'
    '; - if (is_array($jobs)) { - foreach ($jobs as $value) { - $html .= ''; - $html .= ''; - $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour'); - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - } - } else { - $html .= ''; - $html .= ''; - $html .= ''; - } - $html .= '
    '.$langs->trans("Id").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Printer").''.$langs->trans("Filename").''.$langs->trans("Status").''.$langs->trans("Cancel").'
    '.$value['id'].''.$dates.''.$value['ownerId'].''.$value['printerName'].''.$value['title'].''.$value['status'].' 
    '.$langs->trans("None").'
    '; - $html .= ''; + $jobs = $responsedata['jobs']; + //$html .= '
    '.print_r($jobs['0'],true).'
    '; + if (is_array($jobs)) { + foreach ($jobs as $value) { + $html .= '
    '.$value['id'].''.$dates.''.$value['ownerId'].''.$value['printerName'].''.$value['title'].''.$value['status'].' 
    '.$langs->trans("None").'
    '; + $html .= ''; - $this->resprint = $html; + $this->resprint = $html; - return $error; - } + return $error; + } } diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php index c67789b1814..a74286e4cdc 100644 --- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php @@ -173,8 +173,8 @@ class pdf_azur extends ModelePDFPropales $this->posxqty = 135; $this->posxunit = 151; } else { - $this->posxtva = 110; - $this->posxup = 126; + $this->posxtva = 106; + $this->posxup = 122; $this->posxqty = 145; $this->posxunit = 162; } diff --git a/htdocs/core/modules/propale/doc/pdf_cyan.modules.php b/htdocs/core/modules/propale/doc/pdf_cyan.modules.php index 8563c845d2b..324f52c1ca0 100644 --- a/htdocs/core/modules/propale/doc/pdf_cyan.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_cyan.modules.php @@ -57,7 +57,7 @@ class pdf_cyan extends ModelePDFPropales public $description; /** - * @var string Save the name of generated file as the main doc when generating a doc with this template + * @var int Save the name of generated file as the main doc when generating a doc with this template */ public $update_main_doc_field; @@ -119,6 +119,11 @@ class pdf_cyan extends ModelePDFPropales */ public $emetteur; + /** + * @var array of document table collumns + */ + public $cols; + /** * Constructor @@ -164,11 +169,13 @@ class pdf_cyan extends ModelePDFPropales if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined // Define position of columns - $this->posxdesc = $this->marge_gauche + 1; + $this->posxdesc = $this->marge_gauche + 1; // used for notes ans other stuff $this->tabTitleHeight = 5; // default height + // Use new system for position of columns, view $this->defineColumnField() + $this->tva = array(); $this->localtax1 = array(); $this->localtax2 = array(); @@ -197,7 +204,7 @@ class pdf_cyan extends ModelePDFPropales // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; - // Load traductions files required by page + // Load translation files required by page $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { @@ -344,16 +351,16 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right - // Does we have at least one line with discount $this->atleastonediscount - foreach ($object->lines as $line) { - if ($line->remise_percent) { - $this->atleastonediscount = true; - break; + // Set $this->atleastonediscount if you have at least one discount + for ($i = 0; $i < $nblines; $i++) + { + if ($object->lines[$i]->remise_percent) + { + $this->atleastonediscount++; } } - // New page $pdf->AddPage(); if (!empty($tplidx)) $pdf->useTemplate($tplidx); @@ -365,7 +372,7 @@ class pdf_cyan extends ModelePDFPropales $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) //print $heightforinfotot + $heightforsignature + $heightforfreetext + $heightforfooter;exit; - $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs); + $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); $pdf->SetFont('', '', $default_font_size - 1); $pdf->MultiCell(0, 3, ''); // Set interline to 3 $pdf->SetTextColor(0, 0, 0); @@ -397,7 +404,7 @@ class pdf_cyan extends ModelePDFPropales } } - // Affiche notes + // Displays notes $notetoshow = empty($object->note_public) ? '' : $object->note_public; if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { @@ -454,7 +461,7 @@ class pdf_cyan extends ModelePDFPropales { $pdf->rollbackTransaction(true); - // prepar pages to receive notes + // prepare pages to receive notes while ($pagenb < $pageposafternote) { $pdf->AddPage(); $pagenb++; @@ -488,7 +495,7 @@ class pdf_cyan extends ModelePDFPropales } - // apply note frame to previus pages + // apply note frame to previous pages $i = $pageposbeforenote; while ($i < $pageposafternote) { $pdf->setPage($i); @@ -544,10 +551,10 @@ class pdf_cyan extends ModelePDFPropales $height_note = 0; } - // Use new auto collum system + // Use new auto column system $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - // Simulation de tableau pour connaitre la hauteur de la ligne de titre + // tab simulation to know line height $pdf->startTransaction(); $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); $pdf->rollbackTransaction(true); @@ -582,7 +589,6 @@ class pdf_cyan extends ModelePDFPropales { $pdf->AddPage('', '', true); if (!empty($tplidx)) $pdf->useTemplate($tplidx); - //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); $pdf->setPage($pageposbefore + 1); $curY = $tab_top_newpage; @@ -656,7 +662,7 @@ class pdf_cyan extends ModelePDFPropales $pdf->setPage($pageposafter); $curY = $tab_top_newpage; } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font // VAT Rate if ($this->getColumnStatus('vat')) @@ -700,7 +706,7 @@ class pdf_cyan extends ModelePDFPropales $nexY = max($pdf->GetY(), $nexY); } - // Total HT line + // Total excl tax line (HT) if ($this->getColumnStatus('totalexcltax')) { $total_excl_tax = pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails); @@ -708,6 +714,14 @@ class pdf_cyan extends ModelePDFPropales $nexY = max($pdf->GetY(), $nexY); } + // Total with tax line (TTC) + if ($this->getColumnStatus('totalincltax')) + { + $total_incl_tax = pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails); + $this->printStdColumnContent($pdf, $curY, 'totalincltax', $total_incl_tax); + $nexY = max($pdf->GetY(), $nexY); + } + // Extrafields if (!empty($object->lines[$i]->array_options)) { foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { @@ -732,8 +746,7 @@ class pdf_cyan extends ModelePDFPropales $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook - - // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva + // Collection of totals by value of vat in $this->tva["rate"] = total_tva if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; else $tvaligne = $object->lines[$i]->total_tva; @@ -826,13 +839,13 @@ class pdf_cyan extends ModelePDFPropales $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforsignature - $heightforfooter + 1; } - // Affiche zone infos + // Display infos area $posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); - // Affiche zone totaux + // Display total zone $posy = $this->drawTotalTable($pdf, $object, 0, $bottomlasttab, $outputlangs); - // Affiche zone versements + // Display payment area /* if ($deja_regle || $amount_credit_notes_included || $amount_deposits_included) { @@ -1121,10 +1134,10 @@ class pdf_cyan extends ModelePDFPropales // If payment mode not forced or forced to VIR, show payment with BAN if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'VIR') { - if (!empty($object->fk_account) || !empty($object->fk_bank) || !empty($conf->global->FACTURE_RIB_NUMBER)) + if ($object->fk_account > 0 || $object->fk_bank > 0 || !empty($conf->global->FACTURE_RIB_NUMBER)) { - $bankid = (empty($object->fk_account) ? $conf->global->FACTURE_RIB_NUMBER : $object->fk_account); - if (!empty($object->fk_bank)) $bankid = $object->fk_bank; // For backward compatibility when object->fk_account is forced with object->fk_bank + $bankid = ($object->fk_account <= 0 ? $conf->global->FACTURE_RIB_NUMBER : $object->fk_account); + if ($object->fk_bank > 0) $bankid = $object->fk_bank; // For backward compatibility when object->fk_account is forced with object->fk_bank $account = new Account($this->db); $account->fetch($bankid); @@ -1154,15 +1167,23 @@ class pdf_cyan extends ModelePDFPropales */ protected function drawTotalTable(&$pdf, $object, $deja_regle, $posy, $outputlangs) { - global $conf, $mysoc; + global $conf, $mysoc, $hookmanager; $default_font_size = pdf_getPDFFontSize($outputlangs); + $outputlangsbis = null; + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + $default_font_size--; + } + $tab2_top = $posy; $tab2_hl = 4; $pdf->SetFont('', '', $default_font_size - 1); - // Tableau total + // Total table $col1x = 120; $col2x = 170; if ($this->page_largeur < 210) // To work with US executive format { @@ -1173,13 +1194,6 @@ class pdf_cyan extends ModelePDFPropales $useborder = 0; $index = 0; - $outputlangsbis = null; - if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { - $outputlangsbis = new Translate('', $conf); - $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); - $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); - } - // Total HT $pdf->SetFillColor(255, 255, 255); $pdf->SetXY($col1x, $tab2_top + 0); @@ -1387,6 +1401,7 @@ class pdf_cyan extends ModelePDFPropales if ($deja_regle > 0) { + // Already paid + Deposits $index++; $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); @@ -1440,9 +1455,10 @@ class pdf_cyan extends ModelePDFPropales * @param int $hidetop 1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title * @param int $hidebottom Hide bottom bar of array * @param string $currency Currency code + * @param Translate $outputlangsbis Langs object bis * @return void */ - protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '') + protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '', $outputlangsbis = null) { global $conf; @@ -1460,6 +1476,10 @@ class pdf_cyan extends ModelePDFPropales if (empty($hidetop)) { $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) { + $titre .= ' - '.$outputlangsbis->transnoentities("AmountInCurrency", $outputlangsbis->transnoentitiesnoconv("Currency".$currency)); + } + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); @@ -1490,9 +1510,10 @@ class pdf_cyan extends ModelePDFPropales * @param Object $object Object to show * @param int $showaddress 0=no, 1=yes * @param Translate $outputlangs Object lang for output + * @param Translate $outputlangsbis Object lang for output bis * @return void */ - protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs) + protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $outputlangsbis = null) { global $conf, $langs; @@ -1512,8 +1533,10 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); + $w = 100; + $posy = $this->marge_haute; - $posx = $this->page_largeur - $this->marge_droite - 100; + $posx = $this->page_largeur - $this->marge_droite - $w; $pdf->SetXY($this->marge_gauche, $posy); @@ -1537,12 +1560,12 @@ class pdf_cyan extends ModelePDFPropales } else { $pdf->SetTextColor(200, 0, 0); $pdf->SetFont('', 'B', $default_font_size - 2); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); } } else { $text = $this->emetteur->name; - $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); + $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); } } @@ -1550,7 +1573,7 @@ class pdf_cyan extends ModelePDFPropales $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); $title = $outputlangs->transnoentities("PdfCommercialProposalTitle"); - $pdf->MultiCell(100, 4, $title, '', 'R'); + $pdf->MultiCell($w, 4, $title, '', 'R'); $pdf->SetFont('', 'B', $default_font_size); @@ -1567,7 +1590,7 @@ class pdf_cyan extends ModelePDFPropales $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); } if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) @@ -1597,7 +1620,7 @@ class pdf_cyan extends ModelePDFPropales $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Date")." : ".dol_print_date($object->date, "day", false, $outputlangs, true), '', 'R'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("Date")." : ".dol_print_date($object->date, "day", false, $outputlangs, true), '', 'R'); $posy += 4; $pdf->SetXY($posx, $posy); @@ -1609,7 +1632,7 @@ class pdf_cyan extends ModelePDFPropales $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); } // Get contact @@ -1623,7 +1646,7 @@ class pdf_cyan extends ModelePDFPropales $posy += 4; $pdf->SetXY($posx, $posy); $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell(100, 3, $langs->trans("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); + $pdf->MultiCell($w, 3, $langs->transnoentities("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); } } @@ -1632,7 +1655,7 @@ class pdf_cyan extends ModelePDFPropales $top_shift = 0; // Show list of linked objects $current_y = $pdf->getY(); - $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size); + $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); if ($current_y < $pdf->getY()) { $top_shift = $pdf->getY() - $current_y; @@ -1703,9 +1726,10 @@ class pdf_cyan extends ModelePDFPropales $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $object); // Show recipient - $widthrecbox = 100; + $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format - $posy = 42 + $top_shift; + $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; + $posy += $top_shift; $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; @@ -1719,7 +1743,7 @@ class pdf_cyan extends ModelePDFPropales // Show recipient name $pdf->SetXY($posx + 2, $posy + 3); $pdf->SetFont('', 'B', $default_font_size); - $pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L'); + $pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L'); $posy = $pdf->getY(); @@ -1840,7 +1864,7 @@ class pdf_cyan extends ModelePDFPropales 'align' => 'L', // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label // 'label' => ' ', // the final label - 'padding' => array(0.5, 1, 0.5, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left ), 'content' => array( 'align' => 'L', @@ -1848,6 +1872,7 @@ class pdf_cyan extends ModelePDFPropales ), ); + // Image of product $rank = $rank + 10; $this->cols['photo'] = array( 'rank' => $rank, @@ -1939,13 +1964,24 @@ class pdf_cyan extends ModelePDFPropales $this->cols['totalexcltax'] = array( 'rank' => $rank, 'width' => 26, // in mm - 'status' => true, + 'status' => empty($conf->global->PDF_PROPAL_HIDE_PRICE_EXCL_TAX) ? true : false, 'title' => array( 'textkey' => 'TotalHT' ), 'border-left' => true, // add left line separator ); + $rank = $rank + 1010; // add a big offset to be sure is the last col because default extrafield rank is 100 + $this->cols['totalincltax'] = array( + 'rank' => $rank, + 'width' => 26, // in mm + 'status' => empty($conf->global->PDF_PROPAL_SHOW_PRICE_INCL_TAX) ? false : true, + 'title' => array( + 'textkey' => 'TotalTTC' + ), + 'border-left' => true, // add left line separator + ); + // Add extrafields cols if (!empty($object->lines)) { $line = reset($object->lines); diff --git a/htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php index 80a222d9a6c..83733dc1d33 100644 --- a/htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php +++ b/htdocs/core/modules/supplier_invoice/doc/pdf_canelle.modules.php @@ -134,7 +134,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $this->name = "canelle"; $this->description = $langs->trans('SuppliersInvoiceModel'); - // Dimension page + // Page dimensions $this->type = 'pdf'; $formatarray = pdf_getFormat(); $this->page_largeur = $formatarray['width']; @@ -145,12 +145,12 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION - $this->option_modereg = 1; // Affiche mode reglement - $this->option_condreg = 1; // Affiche conditions reglement - $this->option_codeproduitservice = 1; // Affiche code produit-service - $this->option_multilang = 1; // Dispo en plusieurs langues + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages // Define column position $this->posxdesc = $this->marge_gauche + 1; @@ -489,7 +489,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $pdf->SetXY($this->postotalht, $curY); $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 3, $total_excl_tax, 0, 'R', 0); - // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva + // Collection of totals by VAT value in $this->tva["taux"]=total_tva if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; else $tvaligne = $object->lines[$i]->total_tva; @@ -668,7 +668,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $this->atleastoneratenotnull = 0; foreach ($this->tva as $tvakey => $tvaval) { - if ($tvakey > 0) // On affiche pas taux 0 + if ($tvakey > 0) // We do not display rate 0 { $this->atleastoneratenotnull++; @@ -1209,7 +1209,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices } //Recipient name - // On peut utiliser le nom de la societe du contact + // We can use the name of the contact's company if ($usecontact && !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) { $thirdparty = $object->contact; } else { diff --git a/htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php b/htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php index b96f2f83a76..f6e27499dc2 100644 --- a/htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php +++ b/htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php @@ -142,13 +142,13 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_tva = 1; // Gere option tva FACTURE_TVAOPTION - $this->option_modereg = 1; // Affiche mode reglement - $this->option_condreg = 1; // Affiche conditions reglement - $this->option_codeproduitservice = 1; // Affiche code produit-service - $this->option_multilang = 1; // Dispo en plusieurs langues - $this->option_escompte = 0; // Affiche si il y a eu escompte + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages + $this->option_escompte = 0; // Displays if there has been a discount $this->option_credit_note = 0; // Support credit notes $this->option_freetext = 1; // Support add of a personalised text $this->option_draft_watermark = 1; // Support add of a watermark on drafts diff --git a/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php index adccb15892b..388ee06f7a9 100644 --- a/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php +++ b/htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php @@ -139,8 +139,8 @@ class pdf_standard extends ModelePDFSuppliersPayments $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; - $this->option_logo = 1; // Affiche logo - $this->option_multilang = 1; // Dispo en plusieurs langues + $this->option_logo = 1; // Display logo + $this->option_multilang = 1; // Available in several languages // Define column position $this->posxdate = $this->marge_gauche + 1; @@ -168,7 +168,7 @@ class pdf_standard extends ModelePDFSuppliersPayments $this->atleastoneratenotnull = 0; $this->atleastonediscount = 0; - // Recupere emetteur + // Get source company $this->emetteur = $mysoc; if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined } @@ -462,13 +462,13 @@ class pdf_standard extends ModelePDFSuppliersPayments $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; } - // Affiche zone cheèque + // Display check zone $posy = $this->_tableau_cheque($pdf, $object, $bottomlasttab, $outputlangs); // Affiche zone totaux //$posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); - // Pied de page + // Footer page $this->_pagefoot($pdf, $object, $outputlangs); if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); diff --git a/htdocs/core/tpl/bloc_comment.tpl.php b/htdocs/core/tpl/bloc_comment.tpl.php index edb675e45d6..e78a5a7734e 100644 --- a/htdocs/core/tpl/bloc_comment.tpl.php +++ b/htdocs/core/tpl/bloc_comment.tpl.php @@ -38,21 +38,21 @@ print "\n"; if ($action !== 'editcomment') { - print ''; + print ''; - // Description - print ''; + // Description + print ''; - $desc = GETPOST('comment_description'); + $desc = GETPOST('comment_description'); - $doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); + print $doleditor->Create(1); - print ''; + print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } print ''; @@ -96,47 +96,47 @@ if (!empty($object->comments)) print '
    '; print '
    '; - if ($action === 'editcomment' && $comment->id == $idcomment) - { - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - } + if ($action === 'editcomment' && $comment->id == $idcomment) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } - print '
    '; - if ($action === 'editcomment' && $comment->id == $idcomment) - { - $doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); - print $doleditor->Create(1); - } else { - print $comment->description; - } + print '
    '; + if ($action === 'editcomment' && $comment->id == $idcomment) + { + $doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); + print $doleditor->Create(1); + } else { + print $comment->description; + } print '
    '; // End comment-description - if ($action === 'editcomment' && $comment->id == $idcomment) - { - print ''; - print ''; + if ($action === 'editcomment' && $comment->id == $idcomment) + { + print ''; + print ''; - print ''; - } else { - if ($fk_user == $user->id || $user->admin == 1) - { - print ''; - print img_picto('', 'edit.png'); - print ''; - } - if (($first && $fk_user == $user->id) || $user->admin == 1) { - print ''; - print img_picto('', 'delete.png'); - print ''; - } - } + print ''; + } else { + if ($fk_user == $user->id || $user->admin == 1) + { + print ''; + print img_picto('', 'edit.png'); + print ''; + } + if (($first && $fk_user == $user->id) || $user->admin == 1) { + print ''; + print img_picto('', 'delete.png'); + print ''; + } + } - print '
    '; // End comment-table + print '
    '; // End comment-table print '
    '; // End comment-right print ''; // End comment diff --git a/htdocs/core/tpl/filemanager.tpl.php b/htdocs/core/tpl/filemanager.tpl.php index b980ca40cef..43ddd86fb99 100644 --- a/htdocs/core/tpl/filemanager.tpl.php +++ b/htdocs/core/tpl/filemanager.tpl.php @@ -74,18 +74,18 @@ print '
    '; // Toolbar if ($permtoadd) { - print ''; + print ''; print ''; print ''; } else { - print ''; + print ''; print ''; print ''; } if ($module == 'ecm') { $tmpurl = ((!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) ? '#' : ($_SERVER["PHP_SELF"].'?action=refreshmanual'.($module ? '&module='.$module : '').($section ? '&section='.$section : ''))); - print ''; + print ''; print ''; print ''; } diff --git a/htdocs/core/tpl/objectline_edit.tpl.php b/htdocs/core/tpl/objectline_edit.tpl.php index bf5b87d0037..61be629b2ae 100644 --- a/htdocs/core/tpl/objectline_edit.tpl.php +++ b/htdocs/core/tpl/objectline_edit.tpl.php @@ -312,20 +312,22 @@ if (! empty($usemargins) && $user->rights->margins->creer) ?> /* Some js test when we click on button "Add" */ jQuery(document).ready(function() { - global->DISPLAY_MARGIN_RATES)) { ?> + global->DISPLAY_MARGIN_RATES)) { + ?> $("input[name='np_marginRate']:first").blur(function(e) { return checkFreeLine(e, "np_marginRate"); }); - global->DISPLAY_MARK_RATES)) { ?> + global->DISPLAY_MARK_RATES)) { + ?> $("input[name='np_markRate']:first").blur(function(e) { return checkFreeLine(e, "np_markRate"); }); - + }); /* TODO This does not work for number with thousand separator that is , */ diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php index 386bedad910..15637dc4a61 100644 --- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php +++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php @@ -809,7 +809,7 @@ class InterfaceActionsAuto extends DolibarrTriggers } } - $object->actionmsg = $langs->transnoentities("Author").': '.$user->login."\n".$object->actionmsg; + $object->actionmsg = dol_concatdesc($langs->transnoentities("Author").': '.$user->login, $object->actionmsg); dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); diff --git a/htdocs/cron/class/cronjob.class.php b/htdocs/cron/class/cronjob.class.php index 10a2659f6a5..c5acbcf16bd 100644 --- a/htdocs/cron/class/cronjob.class.php +++ b/htdocs/cron/class/cronjob.class.php @@ -1285,9 +1285,9 @@ class Cronjob extends CommonObject elseif ($lastresult) $moretext .= ' ('.$langs->trans("Error").')'; $this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled').$moretext; - $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Enabled').$moretext; + $this->labelStatus[self::STATUS_ENABLED] = $langs->trans('Scheduled').$moretext; $this->labelStatusShort[self::STATUS_DISABLED] = $langs->trans('Disabled'); - $this->labelStatusShort[self::STATUS_ENABLED] = $langs->trans('Enabled'); + $this->labelStatusShort[self::STATUS_ENABLED] = $langs->trans('Scheduled'); } $statusType = 'status4'; diff --git a/htdocs/cron/list.php b/htdocs/cron/list.php index 927c1d1014f..cea8ce39016 100644 --- a/htdocs/cron/list.php +++ b/htdocs/cron/list.php @@ -372,7 +372,7 @@ print ' '; print ' '; print ' '; print ''; -print $form->selectarray('search_status', array('0'=>$langs->trans("Disabled"), '1'=>$langs->trans("Enabled")), $search_status, 1); +print $form->selectarray('search_status', array('0'=>$langs->trans("Disabled"), '1'=>$langs->trans("Scheduled")), $search_status, 1); print ''; $searchpicto = $form->showFilterButtons(); print $searchpicto; diff --git a/htdocs/debugbar/class/DataCollector/DolMemoryCollector.php b/htdocs/debugbar/class/DataCollector/DolMemoryCollector.php index b6525633481..6ec58ea6720 100644 --- a/htdocs/debugbar/class/DataCollector/DolMemoryCollector.php +++ b/htdocs/debugbar/class/DataCollector/DolMemoryCollector.php @@ -15,13 +15,13 @@ class DolMemoryCollector extends MemoryCollector */ public function collect() { - global $langs; + global $conf, $langs; $this->updatePeakUsage(); return array( 'peak_usage' => $this->peakUsage, //'peak_usage_str' => $this->getDataFormatter()->formatBytes($this->peakUsage, 2) - 'peak_usage_str' => $this->peakUsage.' '.$langs->trans("bytes") + 'peak_usage_str' => (empty($conf->dol_optimize_smallscreen) ? dol_print_size($this->peakUsage, 0) : dol_print_size($this->peakUsage, 1)) ); } diff --git a/htdocs/debugbar/class/DataCollector/DolibarrCollector.php b/htdocs/debugbar/class/DataCollector/DolibarrCollector.php index a03575f88e8..b1b31bc9154 100644 --- a/htdocs/debugbar/class/DataCollector/DolibarrCollector.php +++ b/htdocs/debugbar/class/DataCollector/DolibarrCollector.php @@ -59,14 +59,19 @@ class DolibarrCollector extends DataCollector implements Renderable, AssetProvid protected function getDolibarrInfo() { global $conf, $langs; + global $dolibarr_main_prod, $dolibarr_nocsrfcheck; $info = $langs->trans('Version').': '.DOL_VERSION.'
    '; $info .= $langs->trans('Theme').': '.$conf->theme.'
    '; $info .= $langs->trans('Locale').': '.$conf->global->MAIN_LANG_DEFAULT.'
    '; $info .= $langs->trans('Currency').': '.$conf->currency.'
    '; - $info .= $langs->trans('DolEntity').': '.$conf->entity.'
    '; - $info .= $langs->trans('ListLimit').': '.($conf->liste_limit ?: $conf->global->MAIN_SIZE_LISTE_LIMIT).'
    '; - $info .= $langs->trans('MaxSizeForUploadedFiles').': '.$conf->global->MAIN_UPLOAD_DOC.''; + $info .= $langs->trans('Entity').': '.$conf->entity.'
    '; + $info .= $langs->trans('MaxSizeList').': '.($conf->liste_limit ?: $conf->global->MAIN_SIZE_LISTE_LIMIT).'
    '; + $info .= $langs->trans('MaxSizeForUploadedFiles').': '.$conf->global->MAIN_UPLOAD_DOC.'
    '; + $info .= '$dolibarr_main_prod = '.$dolibarr_main_prod.'
    '; + $info .= '$dolibarr_nocsrfcheck = '.$dolibarr_nocsrfcheck.'
    '; + $info .= 'MAIN_SECURITY_CSRF_WITH_TOKEN = '.$conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN.'
    '; + $info .= 'MAIN_FEATURES_LEVEL = '.$conf->global->MAIN_FEATURES_LEVEL.'
    '; return $info; } @@ -79,6 +84,7 @@ class DolibarrCollector extends DataCollector implements Renderable, AssetProvid protected function getMailInfo() { global $conf, $langs; + global $dolibarr_mailing_limit_sendbyweb; $info = $langs->trans('Method').': '.$conf->global->MAIN_MAIL_SENDMODE.'
    '; $info .= $langs->trans('Server').': '.$conf->global->MAIN_MAIL_SMTP_SERVER.'
    '; @@ -86,7 +92,8 @@ class DolibarrCollector extends DataCollector implements Renderable, AssetProvid $info .= $langs->trans('ID').': '.$conf->global->MAIN_MAIL_SMTPS_ID.'
    '; $info .= $langs->trans('Pwd').': '.preg_replace('/./', '*', $conf->global->MAIN_MAIL_SMTPS_PW).'
    '; $info .= $langs->trans('TLS/STARTTLS').': '.$conf->global->MAIN_MAIL_EMAIL_TLS.' / '.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'
    '; - $info .= $langs->trans('MAIN_DISABLE_ALL_MAILS').': '.($conf->global->MAIN_DISABLE_ALL_MAILS ? $langs->trans('Yes') : $langs->trans('No')).''; + $info .= $langs->trans('MAIN_DISABLE_ALL_MAILS').': '.($conf->global->MAIN_DISABLE_ALL_MAILS ? $langs->trans('Yes') : $langs->trans('No')).'
    '; + $info .= 'dolibarr_mailing_limit_sendbyweb = '.$dolibarr_mailing_limit_sendbyweb.'
    '; return $info; } diff --git a/htdocs/document.php b/htdocs/document.php index bc0cc1eb933..a608dfe820e 100644 --- a/htdocs/document.php +++ b/htdocs/document.php @@ -173,7 +173,7 @@ $refname = basename(dirname($original_file)."/"); if (empty($modulepart)) accessforbidden('Bad value for parameter modulepart'); // Check security and set return info with full path of file -$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname); +$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $user, $refname); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index 3ccaa573e8c..b9ec7ebcaa7 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -167,14 +167,14 @@ class Don extends CommonObject { global $langs; $langs->load("donations"); - $this->labelStatus[-1] = $langs->trans("Canceled"); - $this->labelStatus[0] = $langs->trans("DonationStatusPromiseNotValidated"); - $this->labelStatus[1] = $langs->trans("DonationStatusPromiseValidated"); - $this->labelStatus[2] = $langs->trans("DonationStatusPaid"); - $this->labelStatusShort[-1] = $langs->trans("Canceled"); - $this->labelStatusShort[0] = $langs->trans("DonationStatusPromiseNotValidatedShort"); - $this->labelStatusShort[1] = $langs->trans("DonationStatusPromiseValidatedShort"); - $this->labelStatusShort[2] = $langs->trans("DonationStatusPaidShort"); + $this->labelStatus[-1] = $langs->transnoentitiesnoconv("Canceled"); + $this->labelStatus[0] = $langs->transnoentitiesnoconv("DonationStatusPromiseNotValidated"); + $this->labelStatus[1] = $langs->transnoentitiesnoconv("DonationStatusPromiseValidated"); + $this->labelStatus[2] = $langs->transnoentitiesnoconv("DonationStatusPaid"); + $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv("Canceled"); + $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("DonationStatusPromiseNotValidatedShort"); + $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("DonationStatusPromiseValidatedShort"); + $this->labelStatusShort[2] = $langs->transnoentitiesnoconv("DonationStatusPaidShort"); } $statusType = 'status'.$status; diff --git a/htdocs/don/payment/card.php b/htdocs/don/payment/card.php index 26f540969ee..d3ecbe2a107 100644 --- a/htdocs/don/payment/card.php +++ b/htdocs/don/payment/card.php @@ -69,42 +69,6 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->don->supp } } -// Create payment -if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->don->creer) -{ - $db->begin(); - - $result = $object->valide(); - - if ($result > 0) - { - $db->commit(); - - $donations = array(); // TODO Get all id of donation linked to this payment - foreach ($donations as $id) - { - $donation = new Don($db); - $donation->fetch($id); - - $outputlangs = $langs; - if (!empty(GETPOST('lang_id'))) - { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang(GETPOST('lang_id')); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $donation->generateDocument($donation->model_pdf, $outputlangs); - } - } - - header('Location: card.php?id='.$object->id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $db->rollback(); - } -} - /* * View @@ -132,14 +96,6 @@ if ($action == 'delete') print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } -/* - * Confirm validation of the payment - */ -if ($action == 'valide') -{ - print $form->formconfirm('card.php?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide', '', 0, 2); -} - dol_banner_tab($object, 'id', '', 1, 'rowid', 'id'); @@ -148,13 +104,6 @@ print '
    '; print ''; -// Ref -/*print ''; -*/ - // Date print ''; diff --git a/htdocs/don/payment/payment.php b/htdocs/don/payment/payment.php index 3983765d904..1a50677f51a 100644 --- a/htdocs/don/payment/payment.php +++ b/htdocs/don/payment/payment.php @@ -177,6 +177,19 @@ if ($action == 'create') print load_fiche_titre($langs->trans("DoPayment")); + if (!empty($conf->use_javascript_ajax)) + { + print "\n".''."\n"; + } + print ''; print ''; print ''; @@ -257,6 +270,8 @@ if ($action == 'create') if ($sumpaid < $objp->amount) { $namef = "amount_".$objp->id; + if (!empty($conf->use_javascript_ajax)) + print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".price($objp->amount - $sumpaid)."'"); print ''; } else { print '-'; diff --git a/htdocs/ecm/class/ecmdirectory.class.php b/htdocs/ecm/class/ecmdirectory.class.php index 25673c65c6c..dc39550c0cf 100644 --- a/htdocs/ecm/class/ecmdirectory.class.php +++ b/htdocs/ecm/class/ecmdirectory.class.php @@ -35,7 +35,7 @@ class EcmDirectory extends CommonObject /** * @var string Name of table without prefix where object is stored */ - public $table_element='ecm_directories'; + public $table_element = 'ecm_directories'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png diff --git a/htdocs/ecm/file_card.php b/htdocs/ecm/file_card.php index 483335093e9..d5a66ca4134 100644 --- a/htdocs/ecm/file_card.php +++ b/htdocs/ecm/file_card.php @@ -44,8 +44,8 @@ $socid = GETPOST("socid", "int"); // Security check if ($user->socid > 0) { - $action = ''; - $socid = $user->socid; + $action = ''; + $socid = $user->socid; } $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -62,14 +62,14 @@ if (!$sortfield) $sortfield = "label"; $section = GETPOST("section", 'alpha'); if (!$section) { - dol_print_error('', 'Error, section parameter missing'); - exit; + dol_print_error('', 'Error, section parameter missing'); + exit; } $urlfile = GETPOST("urlfile"); if (!$urlfile) { - dol_print_error('', "ErrorParamNotDefined"); - exit; + dol_print_error('', "ErrorParamNotDefined"); + exit; } // Load ecm object @@ -77,8 +77,8 @@ $ecmdir = new EcmDirectory($db); $result = $ecmdir->fetch(GETPOST("section", 'alpha')); if (!$result > 0) { - dol_print_error($db, $ecmdir->error); - exit; + dol_print_error($db, $ecmdir->error); + exit; } $relativepath = $ecmdir->getRelativePath(); $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; @@ -114,67 +114,67 @@ if ($result < 0) if ($cancel) { - $action = ''; - if ($backtopage) - { - header("Location: ".$backtopage); - exit; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section).($module ? '&module='.urlencode($module) : '')); - exit; - } + $action = ''; + if ($backtopage) + { + header("Location: ".$backtopage); + exit; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section).($module ? '&module='.urlencode($module) : '')); + exit; + } } // Rename file if ($action == 'update') { - $error = 0; + $error = 0; - $oldlabel = GETPOST('urlfile', 'alpha'); - $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha')); + $oldlabel = GETPOST('urlfile', 'alpha'); + $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha')); $shareenabled = GETPOST('shareenabled', 'alpha'); - //$db->begin(); + //$db->begin(); - $olddir = $ecmdir->getRelativePath(0); // Relative to ecm - $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document - $newdirrelativetodocument = 'ecm/'.$olddir; - $olddir = $conf->ecm->dir_output.'/'.$olddir; - $newdir = $olddir; + $olddir = $ecmdir->getRelativePath(0); // Relative to ecm + $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document + $newdirrelativetodocument = 'ecm/'.$olddir; + $olddir = $conf->ecm->dir_output.'/'.$olddir; + $newdir = $olddir; - $oldfile = $olddir.$oldlabel; - $newfile = $newdir.$newlabel; - $newfileformove = $newfile; - // If old file end with .noexe, new file must also end with .noexe - if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) { - $newfileformove .= '.noexe'; - } - //var_dump($oldfile);var_dump($newfile);exit; + $oldfile = $olddir.$oldlabel; + $newfile = $newdir.$newlabel; + $newfileformove = $newfile; + // If old file end with .noexe, new file must also end with .noexe + if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) { + $newfileformove .= '.noexe'; + } + //var_dump($oldfile);var_dump($newfile);exit; - // Now we update index of file - $db->begin(); - //print $oldfile.' - '.$newfile; - if ($newlabel != $oldlabel) - { - $result = dol_move($oldfile, $newfileformove); // This include update of database - if (!$result) - { - $langs->load('errors'); - setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors'); - $error++; - } + // Now we update index of file + $db->begin(); + //print $oldfile.' - '.$newfile; + if ($newlabel != $oldlabel) + { + $result = dol_move($oldfile, $newfileformove); // This include update of database + if (!$result) + { + $langs->load('errors'); + setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors'); + $error++; + } - // Reload object after the move - $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel); - if ($result < 0) - { - dol_print_error($db, $object->error, $object->errors); - exit; - } - } + // Reload object after the move + $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel); + if ($result < 0) + { + dol_print_error($db, $object->error, $object->errors); + exit; + } + } - if (!$error) - { + if (!$error) + { if ($shareenabled) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -217,23 +217,23 @@ if ($action == 'update') setEventMessages($object->error, $object->errors, 'warnings'); } } - } + } - if (!$error) - { - $db->commit(); + if (!$error) + { + $db->commit(); - $urlfile = $newlabel; - // If old file end with .noexe, new file must also end with .noexe - if (preg_match('/\.noexe$/', $newfileformove)) { - $urlfile .= '.noexe'; - } + $urlfile = $newlabel; + // If old file end with .noexe, new file must also end with .noexe + if (preg_match('/\.noexe$/', $newfileformove)) { + $urlfile .= '.noexe'; + } - header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section)); - exit; - } else { - $db->rollback(); - } + header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section)); + exit; + } else { + $db->rollback(); + } } @@ -381,7 +381,7 @@ if (!empty($object->share)) } print ''; print ''; -print $object->showOptionals($extrafields, ($action == 'edit'?'edit':'view')); +print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view')); print '
    '; -print $form->showrefnav($object,'id','',1,'rowid','id'); -print '
    '.$langs->trans('Date').''.dol_print_date($object->datep, 'day').'
    '; print '
    '; @@ -392,20 +392,20 @@ dol_fiche_end(); if ($action == 'edit') { - print '
    '; - print ''; - print '     '; - print ''; - print '
    '; + print '
    '; + print ''; + print '     '; + print ''; + print '
    '; - print ''; + print ''; } // Confirmation de la suppression d'une ligne categorie if ($action == 'delete_file') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1); } if ($action != 'edit') @@ -413,11 +413,11 @@ if ($action != 'edit') // Actions buttons print '
    '; - if ($user->rights->ecm->setup) - { - print ''.$langs->trans('Edit').''; - } - /* + if ($user->rights->ecm->setup) + { + print ''.$langs->trans('Edit').''; + } + /* if ($user->rights->ecm->setup) { print ''.$langs->trans('Delete').''; diff --git a/htdocs/ecm/index_auto.php b/htdocs/ecm/index_auto.php index 05d454b8198..e8bf1465fb5 100644 --- a/htdocs/ecm/index_auto.php +++ b/htdocs/ecm/index_auto.php @@ -352,7 +352,7 @@ print '
    '; // Toolbar $url = ((!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) ? '#' : ($_SERVER["PHP_SELF"].'?action=refreshmanual'.($module ? '&module='.$module : '').($section ? '&section='.$section : ''))); -print ''; +print ''; print ''; print ''; diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index 9b6a07a5435..bdf79081fe2 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -11,7 +11,7 @@ * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2018 Nicolas ZABOURI - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2020 Frédéric France * Copyright (C) 2020 Lenin Rivas * * This program is free software; you can redistribute it and/or modify @@ -82,6 +82,13 @@ class Expedition extends CommonObject public $socid; + /** + * @var string Customer ref + * @deprecated + * @see $ref_customer + */ + public $ref_client; + /** * @var string Customer ref */ diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index 3f9de5533fc..37bee98d73f 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -408,7 +408,7 @@ if ($resql) $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; @@ -417,7 +417,7 @@ if ($resql) $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter .= '
    '; } - if (!empty($conf->categorie->enabled)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index 2e826cb4080..4579c1a3e8f 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -214,6 +214,8 @@ if (empty($reshook)) if ($action == 'add' && $user->rights->expensereport->creer) { + $error = 0; + $object = new ExpenseReport($db); $object->date_debut = $date_start; @@ -222,6 +224,19 @@ if (empty($reshook)) $object->fk_user_author = GETPOST('fk_user_author', 'int'); if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id; + // Check that expense report is for a user inside the hierarchy or advanced permission for all is set + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->writeall_advance))) { + $error++; + setEventMessages($langs->trans("NotEnoughPermission"), null, 'errors'); + } else { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)) { + if (! in_array($object->fk_user_author, $childids)) { + $error++; + setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors'); + } + } + } + $fuser = new User($db); $fuser->fetch($object->fk_user_author); @@ -1354,6 +1369,7 @@ if (empty($reshook)) $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Card"); $helpurl = "EN:Module_Expense_Reports"; + llxHeader("", $title, $helpurl); $form = new Form($db); diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index b32e95597e8..f020680c110 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -4,7 +4,7 @@ * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2018 Nicolas ZABOURI * Copyright (c) 2018 Frédéric France - * Copyright (C) 2016-2018 Ferran Marcet + * Copyright (C) 2016-2020 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -405,7 +405,7 @@ class ExpenseReport extends CommonObject $this->id = 0; $this->ref = ''; $this->status = 0; - $this->fk_statut = 0; // deprecated + $this->fk_statut = 0; // deprecated // Clear fields $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. @@ -601,7 +601,7 @@ class ExpenseReport extends CommonObject $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); } - $this->lines = array(); + $this->fetch_optionals(); $result = $this->fetch_lines(); @@ -1353,7 +1353,7 @@ class ExpenseReport extends CommonObject $sql .= ' WHERE rowid = '.$this->id; if ($this->db->query($sql)) { - $this->fk_statut = 99; // deprecated + $this->fk_statut = 99; // deprecated $this->status = 99; $this->fk_user_refuse = $fuser->id; $this->detail_refuse = $details; diff --git a/htdocs/expensereport/payment/card.php b/htdocs/expensereport/payment/card.php index 9bc50341973..718e96b12b0 100644 --- a/htdocs/expensereport/payment/card.php +++ b/htdocs/expensereport/payment/card.php @@ -70,42 +70,6 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expensere } } -// Create payment -if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->expensereport->creer) -{ - $db->begin(); - - $result = $object->valide(); - - if ($result > 0) - { - $db->commit(); - - $factures = array(); // TODO Get all id of invoices linked to this payment - foreach ($factures as $invoiceid) - { - $fac = new Facture($db); - $fac->fetch($invoiceid); - - $outputlangs = $langs; - if (!empty($_REQUEST['lang_id'])) - { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($_REQUEST['lang_id']); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $fac->generateDocument($fac->model_pdf, $outputlangs); - } - } - - header('Location: card.php?id='.$object->id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $db->rollback(); - } -} - /* * View @@ -127,15 +91,6 @@ if ($action == 'delete') print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } -/* - * Confirm validation of the payment - */ -if ($action == 'valide') -{ - $facid = $_GET['facid']; - print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide', '', 0, 2); -} - $linkback = ''; // $linkback = '' . $langs->trans("BackToList") . ''; diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index 70e04d46cbb..d7075d86e1b 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -459,7 +459,7 @@ if ($step == 1 || !$datatoexport) print ''; if ($objexport->array_export_perms[$key]) { - print ''.img_picto($langs->trans("NewExport"), 'filenew').''; + print ''.img_picto($langs->trans("NewExport"), 'next', 'class="fa-15x"').''; } else { print $langs->trans("NotEnoughPermissions"); } diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 650fdc2be15..e4afe4b0452 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -202,16 +202,16 @@ if (empty($reshook)) } } elseif ($action == 'add' && $user->rights->ficheinter->creer) { - $object->socid = $socid; - $object->duration = GETPOST('duration', 'int'); - $object->fk_project = GETPOST('projectid', 'int'); - $object->fk_contrat = GETPOST('contratid', 'int'); - $object->author = $user->id; - $object->description = GETPOST('description', 'restricthtml'); - $object->ref = $ref; - $object->model_pdf = GETPOST('model', 'alpha'); - $object->note_private = GETPOST('note_private', 'restricthtml'); - $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->socid = $socid; + $object->duration = GETPOST('duration', 'int'); + $object->fk_project = GETPOST('projectid', 'int'); + $object->fk_contrat = GETPOST('contratid', 'int'); + $object->author = $user->id; + $object->description = GETPOST('description', 'restricthtml'); + $object->ref = $ref; + $object->model_pdf = GETPOST('model', 'alpha'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->note_public = GETPOST('note_public', 'restricthtml'); if ($object->socid > 0) { @@ -251,7 +251,7 @@ if (empty($reshook)) $extrafields = new ExtraFields($db); $array_options = $extrafields->getOptionalsFromPost($object->table_element); - $object->array_options = $array_options; + $object->array_options = $array_options; $id = $object->create($user); @@ -356,12 +356,12 @@ if (empty($reshook)) $result = $object->addline( $user, - $id, - $desc, - $date_intervention, - $duration, - $array_options - ); + $id, + $desc, + $date_intervention, + $duration, + $array_options + ); if ($result < 0) { @@ -371,44 +371,44 @@ if (empty($reshook)) } } } - } else { + } else { $mesg = $srcobject->error; - $error++; - } - } else { + $error++; + } + } else { $mesg = $object->error; - $error++; - } - } else { - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) { - $error++; - $action = 'create'; - } + $error++; + } + } else { + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) { + $error++; + $action = 'create'; + } - if (!$error) - { - // Extrafields - $array_options = $extrafields->getOptionalsFromPost($object->table_element); + if (!$error) + { + // Extrafields + $array_options = $extrafields->getOptionalsFromPost($object->table_element); - $object->array_options = $array_options; + $object->array_options = $array_options; - $result = $object->create($user); - if ($result > 0) - { - $id = $result; // Force raffraichissement sur fiche venant d'etre cree - } else { - $langs->load("errors"); - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'create'; - } - } - } - } else { + $result = $object->create($user); + if ($result > 0) + { + $id = $result; // Force raffraichissement sur fiche venant d'etre cree + } else { + $langs->load("errors"); + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } + } + } else { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")); - $action = 'create'; - } + $action = 'create'; + } } elseif ($action == 'update' && $user->rights->ficheinter->creer) { $object->socid = $socid; @@ -482,14 +482,14 @@ if (empty($reshook)) $extrafields->fetch_name_optionals_label($object->table_element_line); $array_options = $extrafields->getOptionalsFromPost($object->table_element_line); - $result = $object->addline( + $result = $object->addline( $user, - $id, - $desc, - $date_intervention, - $duration, - $array_options - ); + $id, + $desc, + $date_intervention, + $duration, + $array_options + ); // Define output language $outputlangs = $langs; @@ -545,14 +545,14 @@ if (empty($reshook)) // Classify Done elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) { - $result = $object->setStatut(3); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setStatut(3); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Reopen @@ -591,9 +591,9 @@ if (empty($reshook)) $date_inter = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); $duration = convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')); - $objectline->datei = $date_inter; - $objectline->desc = $desc; - $objectline->duration = $duration; + $objectline->datei = $date_inter; + $objectline->desc = $desc; + $objectline->duration = $duration; // Extrafields $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -601,11 +601,11 @@ if (empty($reshook)) $objectline->array_options = $array_options; $result = $objectline->update($user); - if ($result < 0) - { - dol_print_error($db); - exit; - } + if ($result < 0) + { + dol_print_error($db); + exit; + } // Define output language $outputlangs = $langs; @@ -817,11 +817,11 @@ if ($action == 'create') $subelement = $regs[2]; } - if ($element == 'project') - { - $projectid = GETPOST('originid', 'int'); - } else { - // For compatibility + if ($element == 'project') + { + $projectid = GETPOST('originid', 'int'); + } else { + // For compatibility if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } @@ -904,20 +904,20 @@ if ($action == 'create') $langs->load("project"); - print ''.$langs->trans("Project").''; - /* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty + print ''.$langs->trans("Project").''; + /* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty if ($societe->fournisseur==1) $numprojet=select_projects(-1,$_POST["projectid"],'projectid'); else $numprojet=select_projects($societe->id,$_POST["projectid"],'projectid'); */ - $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); - if ($numprojet == 0) - { - print '   '; - } - print ''; - } + $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); + if ($numprojet == 0) + { + print '   '; + } + print ''; + } // Contract if ($conf->contrat->enabled) @@ -932,53 +932,53 @@ if ($action == 'create') print ''; } - // Model - print ''; - print ''.$langs->trans("DefaultModel").''; - print ''; - $liste = ModelePDFFicheinter::liste_modeles($db); - print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); - print ""; + // Model + print ''; + print ''.$langs->trans("DefaultModel").''; + print ''; + $liste = ModelePDFFicheinter::liste_modeles($db); + print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); + print ""; - // Public note - print ''; - print ''.$langs->trans('NotePublic').''; - print ''; - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - //print ''; - print ''; + // Public note + print ''; + print ''.$langs->trans('NotePublic').''; + print ''; + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + //print ''; + print ''; - // Private note - if (empty($user->socid)) - { - print ''; - print ''.$langs->trans('NotePrivate').''; - print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - //print ''; - print ''; - } + // Private note + if (empty($user->socid)) + { + print ''; + print ''.$langs->trans('NotePrivate').''; + print ''; + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + //print ''; + print ''; + } - // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook)) + // Other attributes + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } - // Show link to origin object - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { - $newclassname = $classname; - if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; - print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; + // Show link to origin object + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) + { + $newclassname = $classname; + if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; + print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; - // Amount - /* Hide amount because we only copy services so amount may differ than source + // Amount + /* Hide amount because we only copy services so amount may differ than source print '' . $langs->trans('AmountHT') . '' . price($objectsrc->total_ht) . ''; print '' . $langs->trans('AmountVAT') . '' . price($objectsrc->total_tva) . ""; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE @@ -1000,14 +1000,14 @@ if ($action == 'create') print '' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . ""; } */ - } + } - print ''; + print ''; - if (is_object($objectsrc)) - { - print ''; - print ''; + if (is_object($objectsrc)) + { + print ''; + print ''; } elseif ($origin == 'project' && !empty($projectid)) { print ''; } @@ -1016,8 +1016,8 @@ if ($action == 'create') print '
    '; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
    '; print ''; @@ -1058,8 +1058,8 @@ if ($action == 'create') print '
    '; print ''; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
    '; print ''; @@ -1172,46 +1172,46 @@ if ($action == 'create') // Project if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->ficheinter->creer) - { - if ($action != 'classify') { - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - } - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
    '; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= '
    '; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($user->rights->ficheinter->creer) + { + if ($action != 'classify') { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + } + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } } $morehtmlref .= '
    '; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) { @@ -1269,47 +1269,47 @@ if ($action == 'create') $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1, 1); } else { if ($object->fk_contrat) - { - $contratstatic = new Contrat($db); - $contratstatic->fetch($object->fk_contrat); - //print ''.$projet->title.''; - print $contratstatic->getNomUrl(0, '', 1); - } else { - print " "; - } + { + $contratstatic = new Contrat($db); + $contratstatic->fetch($object->fk_contrat); + //print ''.$projet->title.''; + print $contratstatic->getNomUrl(0, '', 1); + } else { + print " "; + } } print ''; print ''; } - // Other attributes - $cols = 2; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print '
    '; + print ''; - print '
    '; - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { - // Duration - print ''; - print ''; - print ''; - } + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + // Duration + print ''; + print ''; + print ''; + } print "
    '.$langs->trans("TotalDuration").''.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
    '.$langs->trans("TotalDuration").''.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
    "; print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; - print '

    '; + print '

    '; if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) @@ -1464,25 +1464,25 @@ if ($action == 'create') // Date d'intervention print ''; - if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { - print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention"); - } else { - print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention"); - } + if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { + print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention"); + } else { + print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention"); + } print ''; - // Duration - print ''; - if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { - $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) - $selectmode = 'text'; - $form->select_duration('duration', $objp->duree, 0, $selectmode); - } - print ''; + // Duration + print ''; + if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { + $selectmode = 'select'; + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) + $selectmode = 'text'; + $form->select_duration('duration', $objp->duree, 0, $selectmode); + } + print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''."\n"; @@ -1514,13 +1514,13 @@ if ($action == 'create') print ''; } - print ''; - print ''; // ancre - print $langs->trans('Description').''; - print ''.$langs->trans('Date').''; - print ''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').''; - print ' '; - print "\n"; + print ''; + print ''; // ancre + print $langs->trans('Description').''; + print ''.$langs->trans('Date').''; + print ''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').''; + print ' '; + print "\n"; } print ''."\n"; @@ -1530,43 +1530,43 @@ if ($action == 'create') print ''.($i + 1).''; } - print ''; - // editeur wysiwyg - if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); - $doleditor->Create(); - } - print ''; + print ''; + // editeur wysiwyg + if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); + $doleditor->Create(); + } + print ''; - // Date intervention - print ''; + // Date intervention + print ''; $now = dol_now(); $timearray = dol_getdate($now); if (!GETPOST('diday', 'int')) { - $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); - } else { - $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); - } - if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { - print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); - } else { - print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter"); - } + $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); + } else { + $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); + } + if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { + print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); + } else { + print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter"); + } print ''; - // Duration - print ''; - if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { - $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { - $selectmode = 'text'; - } - $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode); - } - print ''; + // Duration + print ''; + if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { + $selectmode = 'select'; + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { + $selectmode = 'text'; + } + $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode); + } + print ''; - print ''; + print ''; print ''; //Line extrafield @@ -1601,22 +1601,22 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { if ($user->socid == 0) { - if ($action != 'editdescription' && ($action != 'presend')) { - // Validate - if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { - print ''; - } - } + if ($action != 'editdescription' && ($action != 'presend')) { + // Validate + if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { + print ''; + } + } - // Modify - if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate))) + // Modify + if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate))) { print '
    '; if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) print $langs->trans("Modify"); @@ -1625,7 +1625,7 @@ if ($action == 'create') } // Reopen - if ($object->statut > Fichinter::STATUS_CLOSED) + if ($object->statut >= Fichinter::STATUS_CLOSED) { if ($user->rights->ficheinter->creer) { @@ -1645,7 +1645,7 @@ if ($action == 'create') } // create intervention model - if ($conf->global->MAIN_FEATURES_LEVEL >= 2 && $object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer && (count($object->lines) > 0)) { + if ($conf->global->MAIN_FEATURES_LEVEL >= 1 && $object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer && (count($object->lines) > 0)) { print ''; @@ -1684,7 +1684,7 @@ if ($action == 'create') } // Done - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED) + if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED) { print ''; } diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php index 818c1763786..c9e689ffd4c 100644 --- a/htdocs/fichinter/class/fichinterrec.class.php +++ b/htdocs/fichinter/class/fichinterrec.class.php @@ -250,12 +250,11 @@ class FichinterRec extends Fichinter */ public function fetch($rowid = 0, $ref = '', $ref_ext = '') { - $sql = 'SELECT f.titre, f.fk_soc'; + $sql = 'SELECT f.titre as title, f.fk_soc'; $sql .= ', f.datec, f.duree, f.fk_projet, f.fk_contrat, f.description'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.auto_validate'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinter_rec as f'; if ($rowid > 0) $sql .= ' WHERE f.rowid='.$rowid; elseif ($ref) $sql .= " WHERE f.titre='".$this->db->escape($ref)."'"; @@ -268,8 +267,9 @@ class FichinterRec extends Fichinter $obj = $this->db->fetch_object($result); $this->id = $rowid; - $this->titre = $obj->titre; - $this->ref = $obj->titre; + $this->titre = $obj->title; + $this->title = $obj->title; + $this->ref = $obj->title; $this->description = $obj->description; $this->datec = $obj->datec; $this->duration = $obj->duree; diff --git a/htdocs/fichinter/class/fichinterstats.class.php b/htdocs/fichinter/class/fichinterstats.class.php index 1355c7a97cf..608b7d75f25 100644 --- a/htdocs/fichinter/class/fichinterstats.class.php +++ b/htdocs/fichinter/class/fichinterstats.class.php @@ -64,7 +64,6 @@ class FichinterStats extends Stats $this->userid = $userid; $this->cachefilesuffix = $mode; - $this->where .= " c.entity = ".$conf->entity; if ($mode == 'customer') { $object = new Fichinter($this->db); @@ -75,6 +74,8 @@ class FichinterStats extends Stats //$this->where.= " AND c.fk_statut > 0"; // Not draft and not cancelled } if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + $this->where .= ($this->where ? ' AND ' : '')."c.entity IN (".getEntity('fichinter').')'; + if ($this->socid) { $this->where .= " AND c.fk_soc = ".$this->socid; diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 9aeef877bab..1ad41c08da0 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -417,6 +417,20 @@ if ($object->id > 0) $boxstat .= ''.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.''; $boxstat .= '
    '; if ($link) $boxstat .= ''; + + $tmp = $object->getOutstandingBills('supplier', 1); + $outstandingOpenedLate = $tmp['opened']; + if ($outstandingOpened != $outstandingOpenedLate && !empty($outstandingOpenedLate)) { + $text = $langs->trans("CurrentOutstandingBillLate"); + $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; + $icon = 'bill'; + if ($link) $boxstat .= ''; + $boxstat .= '
    '; + $boxstat .= '' . img_object("", $icon) . ' ' . $text . '
    '; + $boxstat .= ''.price($outstandingOpenedLate, 1, $langs, 1, -1, -1, $conf->currency) . $warn . ''; + $boxstat .= '
    '; + if ($link) $boxstat .= '
    '; + } } $boxstat .= ''; diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 3d6d2c2f837..3ae4e45964c 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -1292,7 +1292,7 @@ class CommandeFournisseur extends CommonOrder $sql .= ", ".$conf->entity; $sql .= ", ".$this->socid; $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null"); - $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", '".$this->db->idate($date)."'"; $sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null"); $sql .= ", ".$user->id; $sql .= ", ".self::STATUS_DRAFT; @@ -1554,7 +1554,7 @@ class CommandeFournisseur extends CommonOrder include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (!$qty) $qty = 1; + if (empty($qty)) $qty = 0; if (!$info_bits) $info_bits = 0; if (empty($txtva)) $txtva = 0; if (empty($txlocaltax1)) $txlocaltax1 = 0; @@ -1660,13 +1660,13 @@ class CommandeFournisseur extends CommonOrder { $qty = $prod->packaging; } else { - if (($qty % $prod->packaging) > 0) + if (!empty($prod->packaging) && ($qty % $prod->packaging) > 0) { $coeff = intval($qty / $prod->packaging) + 1; $qty = $prod->packaging * $coeff; - setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs'); } } + setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs'); } } else { $product_type = $type; @@ -2526,7 +2526,6 @@ class CommandeFournisseur extends CommonOrder $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (!$qty) $qty = 1; $pu = price2num($pu); $pu_ht_devise = price2num($pu_ht_devise); $txtva = price2num($txtva); @@ -3292,11 +3291,6 @@ class CommandeFournisseurLigne extends CommonOrderLine */ public $fk_facture; - /** - * @var string supplier order line label - */ - public $label; - public $rang = 0; public $special_code = 0; @@ -3317,7 +3311,6 @@ class CommandeFournisseurLigne extends CommonOrderLine */ public $ref_supplier; public $remise; - public $product_libelle; /** @@ -3345,7 +3338,7 @@ class CommandeFournisseurLigne extends CommonOrderLine $sql .= ' cd.remise, cd.remise_percent, cd.subprice,'; $sql .= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,'; $sql .= ' cd.total_localtax1, cd.total_localtax2,'; - $sql .= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,'; + $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; $sql .= ' cd.date_start, cd.date_end, cd.fk_unit,'; $sql .= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc'; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) @@ -3388,8 +3381,9 @@ class CommandeFournisseurLigne extends CommonOrderLine $this->special_code = $objp->special_code; $this->ref = $objp->product_ref; + $this->product_ref = $objp->product_ref; - $this->product_libelle = $objp->product_libelle; + $this->product_label = $objp->product_label; $this->product_desc = $objp->product_desc; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 0c0e32a2055..1761215705b 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -38,6 +38,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php'; require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; + /** * Class to manage suppliers invoices */ @@ -95,12 +98,18 @@ class FactureFournisseur extends CommonInvoice */ public $ref; - public $label; - public $libelle; // @deprecated - - public $product_ref; + /** + * @var string Ref supplier + */ public $ref_supplier; + + /** + * @var string Label of invoice + */ + public $label; + public $socid; + //Check constants for types public $type = self::TYPE_STANDARD; @@ -702,7 +711,7 @@ class FactureFournisseur extends CommonInvoice $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; // deprecated + $this->modelpdf = $obj->model_pdf; // deprecated $this->import_key = $obj->import_key; //Incoterms @@ -765,7 +774,7 @@ class FactureFournisseur extends CommonInvoice $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn '; $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit'; $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc'; - $sql .= ', fk_code_ventilation, f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc'; + $sql .= ', f.fk_code_ventilation, f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; $sql .= ' WHERE fk_facture_fourn='.$this->id; @@ -827,7 +836,7 @@ class FactureFournisseur extends CommonInvoice // Accountancy $line->code_ventilation = $obj->fk_code_ventilation; - $line->fk_accounting_account = $obj->fk_code_ventilation; + $line->fk_accounting_account = $obj->fk_code_ventilation; // Multicurrency $line->fk_multicurrency = $obj->fk_multicurrency; @@ -2286,7 +2295,7 @@ class FactureFournisseur extends CommonInvoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice - $label = ''.$langs->trans("SupplierInvoice").''; + $label = img_picto('', $this->picto).' '.$langs->trans("SupplierInvoice").''; if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("InvoiceReplace").''; elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; elseif ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; @@ -2301,7 +2310,7 @@ class FactureFournisseur extends CommonInvoice if (!empty($this->total_ht)) $label .= '
    '.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); if (!empty($this->total_tva)) - $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + $label .= '
    '.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); if (!empty($this->total_ttc)) $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($moretitle) $label .= ' - '.$moretitle; diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 8752d17a5d8..924734f69c5 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -272,7 +272,7 @@ class ProductFournisseur extends Product $charges = price2num($charges, 'MU'); $qty = price2num($qty, 'MS'); $unitBuyPrice = price2num($buyprice / $qty, 'MU'); - $packaging = ($this->packaging < $qty) ? $qty : $this->packaging; + $packaging = price2num((($this->packaging < $qty) ? $qty : $this->packaging), 'MS'); $error = 0; $now = dol_now(); diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 419d5c7a559..7cbe020142f 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -406,7 +406,7 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (!GETPOST('qty')) + if (GETPOST('qty', 'int') == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; @@ -666,7 +666,7 @@ if (empty($reshook)) $productsupplier = new ProductFournisseur($db); if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { - if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) + if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty', 'int')), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } @@ -719,7 +719,7 @@ if (empty($reshook)) $lineid, $_POST['product_desc'], $ht, - $_POST['qty'], + GETPOST('qty', 'int'), $_POST['remise_percent'], $vat_rate, $localtax1_rate, diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index 7a11d22aa53..c3d0a897362 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -1165,13 +1165,13 @@ if ($id > 0 || !empty($ref)) { if ($action == 'editline' && $lineid == $objp->dispatchlineid) { print '
    - + - '; + '; } - print ''; + print ''; if (!empty($conf->reception->enabled)) { print ''; @@ -1290,7 +1290,7 @@ if ($id > 0 || !empty($ref)) { print ''; } - if ($action != 'editline' ||  && $lineid != $objp->dispatchlineid) + if ($action != 'editline' || $lineid != $objp->dispatchlineid) { print ''; print 'dispatchlineid .'#line_'. $objp->dispatchlineid . '">'; diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index a1dfb78a2c5..830d391ad9c 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -364,30 +364,30 @@ if (empty($reshook)) { $fk_parent_line = 0; } - $result = $objecttmp->addline( + $result = $objecttmp->addline( $desc, $lines[$i]->subprice, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, - $lines[$i]->qty, - $lines[$i]->fk_product, + $lines[$i]->qty, + $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, - 'HT', - $product_type, - $lines[$i]->rang, - false, - $lines[$i]->array_options, - $lines[$i]->fk_unit, - $objecttmp->origin_id, - $lines[$i]->pa_ht, - $lines[$i]->ref_supplier, - $lines[$i]->special_code, - $fk_parent_line + 'HT', + $product_type, + $lines[$i]->rang, + false, + $lines[$i]->array_options, + $lines[$i]->fk_unit, + $objecttmp->origin_id, + $lines[$i]->pa_ht, + $lines[$i]->ref_supplier, + $lines[$i]->special_code, + $fk_parent_line ); if ($result > 0) { @@ -686,7 +686,7 @@ if ($resql) $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), - 'presend'=>$langs->trans("SendByMail"), + 'presend'=>$langs->trans("SendByMail"), ); if ($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); @@ -782,7 +782,7 @@ if ($resql) $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; @@ -977,7 +977,7 @@ if ($resql) if (!empty($arrayfields['cf.billed']['checked'])) { print ''; - print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); + print $form->selectyesno('search_billed', $search_billed, 1, 0, 1, 1); print ''; } // Action column @@ -1293,14 +1293,14 @@ if ($resql) $db->free($resql); - $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - print ''."\n"; - print '
    '; + print ''."\n"; + print '
    '; - print ''."\n"; + print ''."\n"; $hidegeneratedfilelistifempty = 1; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index b0f178c6fc4..56f2bef6c6a 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -8,8 +8,8 @@ * Copyright (C) 2013-2015 Philippe Grand * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2016 Marcos García - * Copyright (C) 2016-2017 Alexandre Spangaro - * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2016-2020 Alexandre Spangaro + * Copyright (C) 2018 Frédéric France * Copyright (C) 2019 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -153,21 +153,21 @@ if (empty($reshook)) // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) { - $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. + $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. - if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); - $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); + if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); + $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); - $result = $objectutil->createFromClone($user, $id); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); - exit; - } else { - $langs->load("errors"); - setEventMessages($objectutil->error, $objectutil->errors, 'errors'); - $action = ''; - } + $result = $objectutil->createFromClone($user, $id); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + exit; + } else { + $langs->load("errors"); + setEventMessages($objectutil->error, $objectutil->errors, 'errors'); + $action = ''; + } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse'); @@ -347,6 +347,12 @@ if (empty($reshook)) $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } + // transport mode + if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) + { + $result=$object->setTransportMode(GETPOST('transport_mode_id', 'int')); + } + // Set label elseif ($action == 'setlabel' && $usercancreate) { @@ -660,7 +666,8 @@ if (empty($reshook)) $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); - $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->transport_mode_id = GETPOST('transport_mode_id', 'int'); // Proprietes particulieres a facture de remplacement $object->fk_facture_source = GETPOST('fac_replacement'); @@ -725,7 +732,8 @@ if (empty($reshook)) $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); - $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->transport_mode_id = GETPOST('transport_mode_id', 'int'); // Proprietes particulieres a facture avoir $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : ''; @@ -838,6 +846,7 @@ if (empty($reshook)) $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); + $object->transport_mode_id = GETPOST('transport_mode_id'); // Auto calculation of date due if not filled by user if (empty($object->date_echeance)) $object->date_echeance = $object->calculate_date_lim_reglement(); @@ -1041,7 +1050,7 @@ if (empty($reshook)) $object->fetch($id); $object->fetch_thirdparty(); - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); if (GETPOST('price_ht') != '') { @@ -1077,17 +1086,17 @@ if (empty($reshook)) $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $tva_tx)) - $info_bits |= 0x01; + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $tva_tx)) + $info_bits |= 0x01; - // Define vat_rate - $tva_tx = str_replace('*', '', $tva_tx); - $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + // Define vat_rate + $tva_tx = str_replace('*', '', $tva_tx); + $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - $remise_percent = GETPOST('remise_percent'); + $remise_percent = GETPOST('remise_percent'); $pu_ht_devise = GETPOST('multicurrency_subprice'); // Extrafields Lines @@ -1100,12 +1109,12 @@ if (empty($reshook)) } } - $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); - if ($result >= 0) - { - unset($_POST['label']); - unset($_POST['fourn_ref']); - unset($_POST['date_starthour']); + $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); + if ($result >= 0) + { + unset($_POST['label']); + unset($_POST['fourn_ref']); + unset($_POST['date_starthour']); unset($_POST['date_startmin']); unset($_POST['date_startsec']); unset($_POST['date_startday']); @@ -1250,7 +1259,7 @@ if (empty($reshook)) // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { - $desc = $productsupplier->desc_supplier; + $desc = $productsupplier->desc_supplier; } else $desc = $productsupplier->description; if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); @@ -1301,8 +1310,8 @@ if (empty($reshook)) $array_options, $productsupplier->fk_unit, 0, - $pu_ht_devise, - $ref_supplier, + $pu_ht_devise, + $ref_supplier, '' ); } @@ -1430,34 +1439,34 @@ if (empty($reshook)) if (!$ventilExportCompta) { - // On verifie si aucun paiement n'a ete effectue + // On verifie si aucun paiement n'a ete effectue if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) - { - $idwarehouse = GETPOST('idwarehouse'); + { + $idwarehouse = GETPOST('idwarehouse'); - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); - } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); - } + $qualified_for_stock_change = 0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change = $object->hasProductsOrServices(2); + } else { + $qualified_for_stock_change = $object->hasProductsOrServices(1); + } - // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - if (!$idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action = ''; - } - } + // Check parameters + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (!$idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action = ''; + } + } - $object->setDraft($user, $idwarehouse); + $object->setDraft($user, $idwarehouse); // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) @@ -1687,6 +1696,7 @@ if ($action == 'create') $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0)); $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; + $transport_mode_id = (!empty($objectsrc->transport_mode_id) ? $objectsrc->transport_mode_id : (!empty($soc->transport_mode_id) ? $soc->transport_mode_id : 0)); if (!empty($conf->multicurrency->enabled)) { @@ -1705,6 +1715,7 @@ if ($action == 'create') } else { $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; + $transport_mode_id = $societe->transport_mode_supplier_id; $fk_account = $societe->fk_account; $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp); @@ -1771,9 +1782,9 @@ if ($action == 'create') print ''; // Ref supplier - print ''.$langs->trans('RefSupplier').'id > 0) print ' autofocus'; - print '>'; + print ''.$langs->trans('RefSupplier').'id > 0) print ' autofocus'; + print '>'; print ''; print ''.$langs->trans('Type').''; @@ -2053,13 +2064,22 @@ if ($action == 'create') print ''; } + // Intracomm report + if (!empty($conf->intracommreport->enabled)) + { + $langs->loadLangs(array("intracommreport")); + print '' . $langs->trans('IntracommReportTransportMode') . ''; + $form->selectModeTransport(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id'); + print ''; + } + // Public note print ''.$langs->trans('NotePublic').''; print ''; $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print ''; - // print ''; + // print ''; print ''; // Private note @@ -2109,7 +2129,7 @@ if ($action == 'create') } } - echo ''; + print ''; print ''.$langs->trans('AmountHT').''.price($objectsrc->total_ht).''; print ''.$langs->trans('AmountVAT').''.price($objectsrc->total_tva).""; if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 @@ -2241,8 +2261,8 @@ if ($action == 'create') { // Create an array for form $formquestion = array( - array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), - array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) + array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), + array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) ); // Ask confirmation to clone $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250); @@ -2279,59 +2299,59 @@ if ($action == 'create') $qualified_for_stock_change = $object->hasProductsOrServices(1); } - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct = new FormProduct($db); - $warehouse = new Entrepot($db); - $warehouse_array = $warehouse->list_array(); - if (count($warehouse_array) == 1) { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); - $value = ''; - } else { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); - } - $formquestion = array( - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) - ); - } + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) + ); + } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1); - } + } - // Confirmation edit (back to draft) - if ($action == 'edit') - { - $formquestion = array(); + // Confirmation edit (back to draft) + if ($action == 'edit') + { + $formquestion = array(); - $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); - } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); - } - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct = new FormProduct($db); - $warehouse = new Entrepot($db); - $warehouse_array = $warehouse->list_array(); - if (count($warehouse_array) == 1) { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); - $value = ''; - } else { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); - } - $formquestion = array( - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) - ); - } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); + $qualified_for_stock_change = 0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change = $object->hasProductsOrServices(2); + } else { + $qualified_for_stock_change = $object->hasProductsOrServices(1); + } + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) + ); + } + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); } // Confirmation set paid @@ -2369,109 +2389,109 @@ if ($action == 'create') print $formconfirm; - // Supplier invoice card - $linkback = ''.$langs->trans("BackToList").''; + // Supplier invoice card + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
    '; - // Ref supplier - $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1); - $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($usercancreate) - { - if ($action != 'classify') { - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - } - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
    '; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= '
    '; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } - } - $morehtmlref .= '
    '; + $morehtmlref = '
    '; + // Ref supplier + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($usercancreate) + { + if ($action != 'classify') { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + } + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } + $morehtmlref .= '
    '; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; - // Type - print ''; + $facidavoir = $object->getListIdAvoirFromInvoice(); + if (count($facidavoir) > 0) + { + print ' ('.$langs->transnoentities("InvoiceHasAvoir"); + $i = 0; + foreach ($facidavoir as $id) + { + if ($i == 0) print ' '; + else print ','; + $facavoir = new FactureFournisseur($db); + $facavoir->fetch($id); + print $facavoir->getNomUrl(1); + } + print ')'; + } + if (isset($facidnext) && $facidnext > 0) + { + $facthatreplace = new FactureFournisseur($db); + $facthatreplace->fetch($facidnext); + print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $discount = new DiscountAbsolute($db); + $result = $discount->fetch(0, 0, $object->id); + if ($result > 0) { + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'
    '; + } + } + print ''; - // Relative and absolute discounts + // Relative and absolute discounts print ''; - // Label - print ''; - print ''; - print ''; - print ''; + // Label + print ''; + print ''; + print ''; + print ''; - $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0); + $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0); - // Date - print ''; + // Date + print ''; // Default terms of the settlement $langs->load('bills'); @@ -2632,6 +2652,30 @@ if ($action == 'create') print ''; } + // Intracomm report + if (!empty($conf->intracommreport->enabled)) { + $langs->loadLangs(array("intracommreport")); + print ''; + + print ''; + } + // Other attributes $cols = 2; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; @@ -3033,7 +3077,7 @@ if ($action == 'create') // modified by hook if (empty($reshook)) { - // Modify a validated invoice with no payments + // Modify a validated invoice with no payments if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) { // We check if lines of invoice are not already transfered into accountancy @@ -3078,17 +3122,17 @@ if ($action == 'create') } } - // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { - print ''; // must use facid because id is for payment id not invoice - } + // Make payments + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + { + print ''; // must use facid because id is for payment id not invoice + } - // Classify paid - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { - print ''; + // Classify paid + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + { + print ''; //print ''.$langs->trans('ClassifyPaid').''; } @@ -3124,21 +3168,21 @@ if ($action == 'create') } } - // Validate - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) - { - if (count($object->lines)) - { + // Validate + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) + { + if (count($object->lines)) + { if ($usercanvalidate) - { - print ''; - } else { - print ''; - } - } - } + { + print ''; + } else { + print ''; + } + } + } // Create event /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page. @@ -3161,30 +3205,30 @@ if ($action == 'create') } } - // Delete + // Delete $isErasable = $object->is_erasable(); if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions) - { - //var_dump($isErasable); - if ($isErasable == -4) { - print ''; - } elseif ($isErasable == -3) { // Should never happen with supplier invoice - print ''; - } elseif ($isErasable == -2) { // Should never happen with supplier invoice - print ''; - } elseif ($isErasable == -1) { - print ''; - } elseif ($isErasable <= 0) // Any other cases - { - print ''; - } else { - print ''; - } - } - print ''; + { + //var_dump($isErasable); + if ($isErasable == -4) { + print ''; + } elseif ($isErasable == -3) { // Should never happen with supplier invoice + print ''; + } elseif ($isErasable == -2) { // Should never happen with supplier invoice + print ''; + } elseif ($isErasable == -1) { + print ''; + } elseif ($isErasable <= 0) // Any other cases + { + print ''; + } else { + print ''; + } + } + print ''; - if ($action != 'confirm_edit') - { + if ($action != 'confirm_edit') + { print '
    '; /* diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 39bb12c1ed1..f43ef300b01 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -94,56 +94,56 @@ if ($object->id > 0) $totalpaye = $object->getSommePaiement(); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
    '; - // Ref supplier - $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); - $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref .= ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
    '; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= ''; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } - } - $morehtmlref .= '
    '; + $morehtmlref = '
    '; + // Ref supplier + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($user->rights->facture->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= ''; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } + $morehtmlref .= '
    '; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); - print '
    '; - print '
    '; + print '
    '; + print '
    '; // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); @@ -215,15 +215,15 @@ if ($object->id > 0) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 + if ($mysoc->localtax1_assuj == "1") //Localtax1 { - print '
    '; + print ''; print ''; print ''; } - if ($societe->localtax2_assuj == "1") //Localtax2 + if ($mysoc->localtax2_assuj == "1") //Localtax2 { - print ''; + print ''; print ''; print ''; } @@ -252,16 +252,14 @@ if ($object->id > 0) $permission = $user->rights->fournisseur->facture->creer; $permtoedit = $user->rights->fournisseur->facture->creer; $param = '&facid='.$object->id; - + + $defaulttpldir = '/core/tpl'; $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); foreach ($dirtpls as $module => $reldir) { - if (!empty($module)) - { + if (!empty($module)) { $tpl = dol_buildpath($reldir.'/document_actions_post_headers.tpl.php'); - } - else - { + } else { $tpl = DOL_DOCUMENT_ROOT.$reldir.'/document_actions_post_headers.tpl.php'; } @@ -272,9 +270,8 @@ if ($object->id > 0) } if ($res) break; } - } else { - print $langs->trans('ErrorUnknown'); + print $langs->trans('ErrorUnknown'); } // End of page diff --git a/htdocs/fourn/facture/index.php b/htdocs/fourn/facture/index.php index df32ee1b19a..c3272544371 100644 --- a/htdocs/fourn/facture/index.php +++ b/htdocs/fourn/facture/index.php @@ -51,7 +51,7 @@ $maxOpenCount = empty($conf->global->MAIN_MAXLIST_OVERLOAD) ? 500 : $conf->glob llxHeader("", $langs->trans("SupplierInvoicesArea"), 'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); -print load_fiche_titre($langs->trans("SupplierInvoicesArea"), '', 'invoicing'); +print load_fiche_titre($langs->trans("SupplierInvoicesArea"), '', 'bill'); print '
    '; diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 66e94d461a4..ff2da87d716 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -67,7 +67,7 @@ if ($user->socid > 0) $socid = $user->socid; } -$mode = GETPOST("mode"); +$mode = GETPOST("mode", 'aZ09'); $search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_label = GETPOST("search_label", "alpha"); @@ -92,6 +92,7 @@ $search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', $search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha'); $search_status = GETPOST('search_status', 'int'); $search_paymentmode = GETPOST('search_paymentmode', 'int'); +$search_paymentcond = GETPOST('search_paymentcond', 'int'); $search_town = GETPOST('search_town', 'alpha'); $search_zip = GETPOST('search_zip', 'alpha'); $search_state = GETPOST("search_state"); @@ -165,7 +166,8 @@ $arrayfields = array( 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), + 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>1, 'position'=>50), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1, 'position'=>52), 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1, 'position'=>105), 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0, 'position'=>110), 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj == "1", 'position'=>95), @@ -240,6 +242,7 @@ if (empty($reshook)) $search_multicurrency_montant_ttc = ''; $search_status = ''; $search_paymentmode = ''; + $search_paymentcond = ''; $search_town = ''; $search_zip = ""; $search_state = ""; @@ -367,7 +370,8 @@ if ($search_multicurrency_montant_vat != '') $sql .= natural_search('f.multicurr if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); if ($search_login) $sql .= natural_search('u.login', $search_login); if ($search_status != '' && $search_status >= 0) $sql .= " AND f.fk_statut = ".$db->escape($search_status); -if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode.""; +if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".((int) $search_paymentmode); +if ($search_paymentcond > 0) $sql .= " AND f.fk_cond_reglement = ".((int) $search_paymentcond); $sql .= dolSqlDateFilter("f.datef", $day, $month, $year); $sql .= dolSqlDateFilter("f.date_lim_reglement", $day_lim, $month_lim, $year_lim); if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; @@ -385,7 +389,7 @@ if ($filter && $filter != -1) $sql .= ' AND '.$db->escape(trim($filt[0])).' = '.$db->escape(trim($filt[1])); } } -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); +if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale); if ($search_user > 0) { $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; @@ -595,7 +599,7 @@ if ($resql) $moreforfilter .= '
    '; } // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; @@ -720,11 +724,18 @@ if ($resql) print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); print ''; } + // Condition of payment + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) + { + print '
    '; + } // Payment mode if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print ''; } if (!empty($arrayfields['f.total_ht']['checked'])) @@ -848,7 +859,7 @@ if ($resql) { print ''; } // Action column @@ -873,6 +884,7 @@ if ($resql) if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, '', $sortfield, $sortorder, 'right '); @@ -1096,6 +1108,14 @@ if ($resql) if (!$i) $totalarray['nbfield']++; } + // Payment condition + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } // Payment mode if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index 65b8936a592..bd5950151eb 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -245,7 +245,7 @@ if (empty($reshook)) { $action = 'create'; } - // Le reste propre a cette action s'affiche en bas de page. + // All the next of this action is displayed at the page's bottom. } @@ -292,7 +292,7 @@ if (empty($reshook)) $thirdparty = new Societe($db); if ($socid > 0) $thirdparty->fetch($socid); - // Creation de la ligne paiement + // Creation of payment line $paiement = new PaiementFourn($db); $paiement->datepaye = $datepaye; $paiement->amounts = $amounts; // Array of amounts @@ -521,7 +521,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql .= " WHERE f.entity = ".$conf->entity; $sql .= ' AND f.fk_soc = '.$object->socid; $sql .= ' AND f.paye = 0'; - $sql .= ' AND f.fk_statut = 1'; // Statut=0 => non validee, Statut=2 => annulee + $sql .= ' AND f.fk_statut = 1'; // Status=0 => unvalidated, Status=2 => canceled if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { $sql .= ' AND f.type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation @@ -756,7 +756,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } } - // Bouton Enregistrer + // Save Button if ($action != 'add_paiement') { print '
    '.$langs->trans("ClosePaidInvoicesAutomatically"); @@ -787,255 +787,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } else dol_print_error($db); } -/* - * Show list - */ -if (empty($action) || $action == 'list') -{ - $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; - $sortfield = GETPOST("sortfield", 'alpha'); - $sortorder = GETPOST("sortorder", 'alpha'); - $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); - if (empty($page) || $page == -1) { $page = 0; } - $offset = $limit * $page; - $pageprev = $page - 1; - $pagenext = $page + 1; - if (!$sortorder) $sortorder = 'DESC'; - if (!$sortfield) $sortfield = 'p.datep'; - - $sql = 'SELECT p.rowid as pid, p.ref, p.datep as dp, p.amount as pamount, p.num_paiement,'; - $sql .= ' s.rowid as socid, s.nom as name,'; - $sql .= ' c.code as paiement_type, c.libelle as paiement_libelle,'; - $sql .= ' ba.rowid as bid, ba.label,'; - if (!$user->rights->societe->client->voir) $sql .= ' sc.fk_soc, sc.fk_user,'; - $sql .= ' SUM(pf.amount)'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; - if (!$user->rights->societe->client->voir) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE f.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid > 0) $sql .= ' AND f.fk_soc = '.$socid; - $sql .= dolSqlDateFilter('p.datep', $day, $month, $year); - if ($search_ref) $sql .= natural_search('p.rowid', $search_ref); - if ($search_account > 0) $sql .= " AND b.fk_account=".$search_account; - if ($search_paymenttype != "") $sql .= " AND c.code='".$db->escape($search_paymenttype)."'"; - if ($search_payment_num != '') $sql .= natural_search('p.num_paiement', $search_payment_num); - if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); - if ($search_company) $sql .= natural_search('s.nom', $search_company); - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; - $sql .= " GROUP BY p.rowid, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, c.code, c.libelle, ba.rowid, ba.label"; - if (!$user->rights->societe->client->voir) $sql .= ", sc.fk_soc, sc.fk_user"; - // Add where from extra fields - - $sql .= $db->order($sortfield, $sortorder); - - $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } - } - - $sql .= $db->plimit($limit + 1, $offset); - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - - $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($day) $param .= ($day ? "&day=".urlencode($day) : ""); - if ($month) $param .= ($month ? "&month=".urlencode($month) : ""); - if ($year) $param .= ($year ? "&year=".urlencode($year) : ""); - if ($search_ref) $param .= ($search_ref ? "&search_ref=".urlencode($search_ref) : ""); - if ($search_company) $param .= ($search_company ? "&search_company=".urlencode($search_company) : ""); - if ($search_amount != '') $param .= ($search_amount ? "&search_amount=".urlencode($search_amount) : ""); - if ($search_payment_num) $param .= ($search_payment_num ? "&search_payment_num=".urlencode($search_payment_num) : ""); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - // Add $param from extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - - $massactionbutton = $form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); - - print '
    '; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 1); - - $moreforfilter = ''; - - $parameters = array(); - $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; - - if ($moreforfilter) - { - print '
    '; - print $moreforfilter; - print '
    '; - } - - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '
    '; - print '
    '.$langs->trans('Type').''; - print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { - $facreplaced = new FactureFournisseur($db); - $facreplaced->fetch($object->fk_facture_source); - print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; - } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { - $facusing = new FactureFournisseur($db); - $facusing->fetch($object->fk_facture_source); - print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; - } + // Type + print '
    '.$langs->trans('Type').''; + print $object->getLibType(); + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) + { + $facreplaced = new FactureFournisseur($db); + $facreplaced->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + { + $facusing = new FactureFournisseur($db); + $facusing->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; + } - $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { - print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; - $facavoir = new FactureFournisseur($db); - $facavoir->fetch($id); - print $facavoir->getNomUrl(1); - } - print ')'; - } - if (isset($facidnext) && $facidnext > 0) - { - $facthatreplace = new FactureFournisseur($db); - $facthatreplace->fetch($facidnext); - print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; - } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $discount = new DiscountAbsolute($db); - $result = $discount->fetch(0, 0, $object->id); - if ($result > 0) { - print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'
    '; - } - } - print '
    '.$langs->trans('Discounts'); print ''; @@ -2482,18 +2502,18 @@ if ($action == 'create') print '
    '.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).''.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'
    '.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).''.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'
    '.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').''; - print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker'); - print '
    '.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').''; + print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker'); + print '
    '; + print ''; + if ($action != 'editmode' && $user->rights->fournisseur->facture->creer) { + print ''; + } + print '
    '; + print $langs->trans('IntracommReportTransportMode'); + print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
    '; + print '
    '; + if ($action == 'editmode') + { + $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'transport_mode_id', 1, 1); + } + else { + $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'none'); + } + print '
    '.$langs->transcountry("AmountLT1", $societe->country_code).'
    '.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'
    '.$langs->transcountry("AmountLT2", $societe->country_code).'
    '.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'
    '; + $form->select_conditions_paiements($search_paymentcond, 'search_paymentcond', -1, 1, 1, 'maxwidth100'); + print ''; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 10); + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 20, 1, 'maxwidth100'); print ''; $liststatus = array('0'=>$langs->trans("Draft"), '1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); - print $form->selectarray('search_status', $liststatus, $search_status, 1); + print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', '', 1); print ''; + $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', '', -1); + print '
    '."\n"; - - // Lines for filters fields - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->banque->enabled)) - { - print ''; - } - print ''; - print ''; - print "\n"; - - print ''; - print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Date", $_SERVER["PHP_SELF"], 'dp', '', $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Type", $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Numero", $_SERVER["PHP_SELF"], "p.num_paiement", "", $param, "", $sortfield, $sortorder); - if (!empty($conf->banque->enabled)) - { - print_liste_field_titre("Account", $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); - } - print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); - - $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); - $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); - print "\n"; - - $paymentfournstatic = new PaiementFourn($db); - - $i = 0; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); - - $paymentfournstatic->id = $objp->pid; - $paymentfournstatic->ref = $objp->ref; - $paymentfournstatic->datepaye = $objp->dp; - - print ''; - - // Ref payment - print ''; - if (!$i) $totalarray['nbfield']++; - - // Date - $dateformatforpayment = 'day'; - if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; - print '\n"; - if (!$i) $totalarray['nbfield']++; - - // Thirdparty - print ''; - if (!$i) $totalarray['nbfield']++; - - // Type - $payment_type = $langs->trans("PaymentType".$objp->paiement_type) != ("PaymentType".$objp->paiement_type) ? $langs->trans("PaymentType".$objp->paiement_type) : $objp->paiement_libelle; - print '\n"; - if (!$i) $totalarray['nbfield']++; - - // Payment number - print ''; - if (!$i) $totalarray['nbfield']++; - - // Account - if (!empty($conf->banque->enabled)) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - - // Amount - print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'amount'; - $totalarray['val']['amount'] += $objp->pamount; - - // Ref invoice - /*$invoicesupplierstatic->ref=$objp->ref_supplier; - $invoicesupplierstatic->id=$objp->facid; - print '';*/ - - print ''; - if (!$i) $totalarray['nbfield']++; - - print ''; - $i++; - } - - // Show total line - include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - - print "
    '; - print ''; - print ''; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); - print ''; - print ''; - print ''; - $form->select_types_paiements($search_paymenttype, 'search_paymenttype', '', 2, 1, 1); - print ''; - print ''; - print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1); - print ''; - print ''; - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print '
    '; - print $paymentfournstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp), $dateformatforpayment)."'; - if ($objp->socid) print ''.img_object($langs->trans('ShowCompany'), 'company').' '.dol_trunc($objp->name, 32).''; - else print ' '; - print ''.$payment_type.' '.dol_trunc($objp->num_paiement, 32)."'.$objp->num_paiement.''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).''; - else print ' '; - print ''.price($objp->pamount).''; - print $invoicesupplierstatic->getNomUrl(1); - print '
    "; - print "
    "; - print "\n"; - } else { - dol_print_error($db); - } -} - // End of page llxFooter(); $db->close(); diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index ffe4c95bf51..9d842481188 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -74,7 +74,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse if ($result > 0) { $db->commit(); - header('Location: '.DOL_URL_ROOT.'/fourn/facture/paiement.php'); + header('Location: '.DOL_URL_ROOT.'/fourn/paiement/list.php'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -82,7 +82,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse } } -if ($action == 'confirm_valide' && $confirm == 'yes' && +if ($action == 'confirm_validate' && $confirm == 'yes' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->facture->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) ) @@ -90,7 +90,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $db->begin(); $object->fetch($id); - if ($object->valide() >= 0) + if ($object->validate() >= 0) { $db->commit(); header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); @@ -128,7 +128,7 @@ if ($action == 'setdatep' && !empty($_POST['datepday'])) // Build document $upload_dir = $conf->fournisseur->payment->dir_output; -// TODO: get the appropriate permisson +// TODO: get the appropriate permission $permissiontoadd = true; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; @@ -151,7 +151,7 @@ dol_fiche_head($head, 'payment', $langs->trans('SupplierPayment'), -1, 'payment' if ($result > 0) { /* - * Confirmation de la suppression du paiement + * Confirmation of payment's delete */ if ($action == 'delete') { @@ -159,14 +159,14 @@ if ($result > 0) } /* - * Confirmation de la validation du paiement + * Confirmation of payment's validation */ - if ($action == 'valide') + if ($action == 'validate') { - print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide'); + print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_validate'); } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref'); @@ -181,7 +181,7 @@ if ($result > 0) print $form->showrefnav($object,'id','',1,'rowid','ref'); print '';*/ - // Date payment + // Date of payment print ''.$form->editfieldkey("Date", 'datep', $object->date, $object, $object->statut == 0 && $user->rights->fournisseur->facture->creer).''; print $form->editfieldval("Date", 'datep', $object->date, $object, $object->statut == 0 && $user->rights->fournisseur->facture->creer, 'datehourpicker', '', null, $langs->trans('PaymentDateUpdateSucceeded')); print ''; @@ -251,9 +251,10 @@ if ($result > 0) print '
    '; /** - * Liste des factures + * List of seller's invoices */ - $sql = 'SELECT f.rowid, f.ref, f.ref_supplier, f.total_ttc, pf.amount, f.rowid as facid, f.paye, f.fk_statut, s.nom as name, s.rowid as socid'; + $sql = 'SELECT f.rowid, f.rowid as facid, f.ref, f.ref_supplier, f.type, f.paye, f.total_ht, f.total_tva, f.total_ttc, f.datef as date, f.fk_statut as status,'; + $sql .= ' pf.amount, s.nom as name, s.rowid as socid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf,'.MAIN_DB_PREFIX.'facture_fourn as f,'.MAIN_DB_PREFIX.'societe as s'; $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid'; $sql .= ' AND pf.fk_paiementfourn = '.$object->id; @@ -285,6 +286,13 @@ if ($result > 0) $facturestatic->id = $objp->facid; $facturestatic->ref = ($objp->ref ? $objp->ref : $objp->rowid); + $facturestatic->date = $db->jdate($objp->date); + $facturestatic->type = $objp->type; + $facturestatic->total_ht = $objp->total_ht; + $facturestatic->total_tva = $objp->total_tva; + $facturestatic->total_ttc = $objp->total_ttc; + $facturestatic->statut = $objp->status; + $facturestatic->alreadypaid = -1; // unknown print ''; // Ref @@ -300,7 +308,7 @@ if ($result > 0) // Payed print ''.price($objp->amount).''; // Status - print ''.$facturestatic->LibStatut($objp->paye, $objp->fk_statut, 6, 1).''; + print ''.$facturestatic->LibStatut($objp->paye, $objp->status, 6, 1).''; print "\n"; if ($objp->paye == 1) @@ -324,7 +332,7 @@ if ($result > 0) /* - * Boutons Actions + * Actions Buttons */ print '
    '; @@ -335,7 +343,7 @@ if ($result > 0) if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->facture->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) { - print ''.$langs->trans('Valid').''; + print ''.$langs->trans('Valid').''; } } } diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php new file mode 100644 index 00000000000..0310a75fe57 --- /dev/null +++ b/htdocs/fourn/paiement/list.php @@ -0,0 +1,446 @@ + + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2004-2020 Laurent Destailleur + * Copyright (C) 2004 Christophe Combelles + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> + * Copyright (C) 2015 Marcos García + * Copyright (C) 2015 Juanjo Menent + * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2018 Frédéric France + * Copyright (C) 2020 Tobias Sekan + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/fourn/paiment/list.php +* \ingroup fournisseur,facture + * \brief Payment list for supplier invoices + */ + +require '../../main.inc.php'; + +// Security check +if ($user->socid) $socid = $user->socid; + +// doesn't work :-( +// restrictedArea($user, 'fournisseur'); + +// doesn't work :-( +// require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +// $object = new PaiementFourn($db); +// restrictedArea($user, $object->element); + +if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} + +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + + +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills', 'banks', 'compta')); + +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'vendorpaymentlist'; + +$socid = GETPOST('socid', 'int'); + +$search_ref = GETPOST('search_ref', 'alpha'); +$search_day = GETPOST('search_day', 'int'); +$search_month = GETPOST('search_month', 'int'); +$search_year = GETPOST('search_year', 'int'); +$search_company = GETPOST('search_company', 'alpha'); +$search_payment_type = GETPOST('search_payment_type'); +$search_cheque_num = GETPOST('search_cheque_num', 'alpha'); +$search_bank_account = GETPOST('search_bank_account', 'int'); +$search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on '< x' + +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST('page', 'int'); + +if (empty($page) || $page == -1) $page = 0; // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "p.datep"; + +$search_all = trim(GETPOSTISSET("search_all") ? GETPOSTISSET("search_all", 'alpha') : GETPOST('sall')); + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array( + 'p.ref'=>"RefPayment", + 's.nom'=>"ThirdParty", + 'p.num_paiement'=>"Numero", + 'p.amount'=>"Amount", +); + +$arrayfields = array( + 'p.ref' =>array('label'=>"RefPayment", 'checked'=>1, 'position'=>10), + 'p.datep' =>array('label'=>"Date", 'checked'=>1, 'position'=>20), + 's.nom' =>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30), + 'c.libelle' =>array('label'=>"Type", 'checked'=>1, 'position'=>40), + 'p.num_paiement' =>array('label'=>"Numero", 'checked'=>1, 'position'=>50, 'tooltip'=>"ChequeOrTransferNumber"), + 'ba.label' =>array('label'=>"Account", 'checked'=>1, 'position'=>60, 'enable'=>(!empty($conf->banque->enabled))), + 'p.amount' =>array('label'=>"Amount", 'checked'=>1, 'position'=>70), +); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('paymentsupplierlist')); +$object = new PaiementFourn($db); + +/* +* Actions +*/ + +$parameters = array('socid'=>$socid); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) { + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + $search_ref = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; + $search_company = ''; + $search_payment_type = ''; + $search_cheque_num = ''; + $search_bank_account = ''; + $search_amount = ''; + } +} + +/* + * View + */ + +llxHeader('', $langs->trans('ListPayment')); + +$form = new Form($db); +$formother = new FormOther($db); +$companystatic = new Societe($db); +$paymentfournstatic = new PaiementFourn($db); + +$sql = 'SELECT p.rowid, p.ref, p.datep, p.amount as pamount, p.num_paiement'; +$sql .= ', s.rowid as socid, s.nom as name, s.email'; +$sql .= ', c.code as paiement_type, c.libelle as paiement_libelle'; +$sql .= ', ba.rowid as bid, ba.label'; +if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; +$sql .= ', SUM(pf.amount)'; + +$sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; +if (!$user->rights->societe->client->voir) $sql .= ', '.MAIN_DB_PREFIX.'societe_commerciaux as sc'; + +$sql .= ' WHERE f.entity = '.$conf->entity; +if (!$user->rights->societe->client->voir) $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id; +if ($socid > 0) $sql .= ' AND f.fk_soc = '.$socid; +if ($search_ref) $sql .= natural_search('p.ref', $search_ref); +$sql .= dolSqlDateFilter('p.datep', $search_day, $search_month, $search_year); +if ($search_company) $sql .= natural_search('s.nom', $search_company); +if ($search_payment_type != '') $sql .= " AND c.code='".$db->escape($search_payment_type)."'"; +if ($search_cheque_num != '') $sql .= natural_search('p.num_paiement', $search_cheque_num); +if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); +if ($search_bank_account > 0) $sql .= ' AND b.fk_account='.$search_bank_account."'"; + +if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); + +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; + +$sql .= ' GROUP BY p.rowid, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, c.code, c.libelle, ba.rowid, ba.label'; +if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; + +$sql .= $db->order($sortfield, $sortorder); + +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } +} + +$sql .= $db->plimit($limit + 1, $offset); + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + llxFooter(); + $db->close(); + exit; +} + +$num = $db->num_rows($resql); +$i = 0; + +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + +if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); +if ($saerch_day) $param .= '&search_day='.urlencode($search_day); +if ($saerch_month) $param .= '&search_month='.urlencode($search_month); +if ($search_year) $param .= '&search_year='.urlencode($search_year); +if ($search_company) $param .= '&search_company='.urlencode($search_company); +if ($search_payment_type) $param .= '&search_company='.urlencode($search_payment_type); +if ($search_cheque_num) $param .= '&search_cheque_num='.urlencode($search_cheque_num); +if ($search_amount) $param .= '&search_amount='.urlencode($search_amount); + +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +print '
    '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 1); + +if ($search_all) +{ + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; +} + +$moreforfilter = ''; + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; + +if ($moreforfilter) { + print '
    '; + print $moreforfilter; + print '
    '; +} + +$varpage = empty($contextpage) ? $_SERVER['PHP_SELF'] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + +print '
    '; +print ''; + +print ''; + +// Filter: Ref +if (!empty($arrayfields['p.ref']['checked'])) { + print ''; +} + +// Filter: Date +if (!empty($arrayfields['p.datep']['checked'])) { + print ''; +} + +// Filter: Thirdparty +if (!empty($arrayfields['s.nom']['checked'])) { + print ''; +} + +// Filter: Payment type +if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; +} + +// Filter: Cheque number (fund transfer) +if (!empty($arrayfields['p.num_paiement']['checked'])) { + print ''; +} + +// Filter: Bank account +if (!empty($arrayfields['ba.label']['checked'])) { + print ''; +} + +// Filter: Amount +if (!empty($arrayfields['p.amount']['checked'])) { + print ''; +} + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +// Buttons +print ''; + +print ''; + +print ''; +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.datep']['checked'])) print_liste_field_titre($arrayfields['p.datep']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['c.libelle']['checked'])) print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.num_paiement']['checked'])) print_liste_field_titre($arrayfields['p.num_paiement']['label'], $_SERVER["PHP_SELF"], "p.num_paiement", '', $param, '', $sortfield, $sortorder, '', $arrayfields['p.num_paiement']['tooltip']); +if (!empty($arrayfields['ba.label']['checked'])) print_liste_field_titre($arrayfields['ba.label']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.amount']['checked'])) print_liste_field_titre($arrayfields['p.amount']['label'], $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); + +// Hook fields +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print_liste_field_titre($selectedfields, $_SERVER['PHP_SELF'], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); +print ''; + +$checkedCount = 0; +foreach ($arrayfields as $column) { + if ($column['checked']) { + $checkedCount++; + } +} + +$i = 0; +$totalarray = array(); +while ($i < min($num, $limit)) { + $objp = $db->fetch_object($resql); + + $paymentfournstatic->id = $objp->rowid; + $paymentfournstatic->ref = $objp->ref; + $paymentfournstatic->datepaye = $objp->datep; + + $companystatic->id = $objp->socid; + $companystatic->name = $objp->name; + $companystatic->email = $objp->email; + + print ''; + + // No + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Ref + if (!empty($arrayfields['p.ref']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Date + if (!empty($arrayfields['p.datep']['checked'])) { + $dateformatforpayment = 'day'; + if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Thirdparty + if (!empty($arrayfields['s.nom']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Pyament type + if (!empty($arrayfields['c.libelle']['checked'])) { + $payment_type = $langs->trans("PaymentType".$objp->paiement_type) != ("PaymentType".$objp->paiement_type) ? $langs->trans("PaymentType".$objp->paiement_type) : $objp->paiement_libelle; + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Cheque number (fund transfer) + if (!empty($arrayfields['p.num_paiement']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Account + if (!empty($arrayfields['ba.label']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Amount + if (!empty($arrayfields['p.amount']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + $totalarray['pos'][$checkedCount] = 'amount'; + $totalarray['val']['amount'] += $objp->pamount; + } + + // Buttons + print ''; + if (!$i) $totalarray['nbfield']++; + + print ''; + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +print '
    '; + print ''; + print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year ? $search_year : -1, 'search_year', 1, 20, 5); + print ''; + print ''; + print ''; + $form->select_types_paiements($search_payment_type, 'search_payment_type', '', 2, 1, 1); + print ''; + print ''; + print ''; + $form->select_comptes($search_bank_account, 'search_bank_account', 0, '', 1); + print ''; + print ''; + print ''; +print $form->showFilterAndCheckAddButtons(0); +print '
    '.(($offset * $limit) + $i).''.$paymentfournstatic->getNomUrl(1).''.dol_print_date($db->jdate($objp->datep), $dateformatforpayment).''; + if ($objp->socid > 0) { + print $companystatic->getNomUrl(1, '', 24); + } + print ''.$payment_type.' '.dol_trunc($objp->num_paiement, 32).''.$objp->num_paiement.''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).''; + else print ' '; + print ''.price($objp->pamount).'
    '; +print '
    '; +print '
    '; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index d9bbe6607bf..47f7744c5ae 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -82,7 +82,8 @@ if (($id > 0) || $ref) } $cancreate = 0; -if (!empty($user->rights->holiday->write_all)) $cancreate = 1; + +if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)) $cancreate = 1; if (!empty($user->rights->holiday->write) && in_array($fuserid, $childids)) $cancreate = 1; $candelete = 0; @@ -146,12 +147,26 @@ if (empty($reshook)) $valideur = GETPOST('valideur', 'int'); $description = trim(GETPOST('description', 'restricthtml')); + // Check that leave is for a user inside the hierarchy or advanced permission for all is set + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->expensereport->writeall_advance))) { + $error++; + setEventMessages($langs->trans("NotEnoughPermission"), null, 'errors'); + } else { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)) { + if (! in_array($fuserid, $childids)) { + $error++; + setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors'); + $action = 'create'; + } + } + } + // If no type if ($type <= 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); $error++; - $action = 'add'; + $action = 'create'; } // If no start date @@ -159,21 +174,21 @@ if (empty($reshook)) { setEventMessages($langs->trans("NoDateDebut"), null, 'errors'); $error++; - $action = 'add'; + $action = 'create'; } // If no end date if (empty($date_fin)) { setEventMessages($langs->trans("NoDateFin"), null, 'errors'); $error++; - $action = 'add'; + $action = 'create'; } // If start date after end date if ($date_debut > $date_fin) { setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors'); $error++; - $action = 'add'; + $action = 'create'; } // Check if there is already holiday for this period @@ -182,16 +197,16 @@ if (empty($reshook)) { setEventMessages($langs->trans("alreadyCPexist"), null, 'errors'); $error++; - $action = 'add'; + $action = 'create'; } // If there is no Business Days within request $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); if ($nbopenedday < 0.5) { - setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); + setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day $error++; - $action = 'add'; + $action = 'create'; } // If no validator designated @@ -741,7 +756,8 @@ if (empty($reshook)) $object->fetch($id); // Si statut en attente de validation et valideur = valideur ou utilisateur, ou droits de faire pour les autres - if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || !empty($user->rights->holiday->write_all))) + if (($object->statut == Holiday::STATUS_VALIDATED || $object->statut == Holiday::STATUS_APPROVED) && ($user->id == $object->fk_validator || in_array($object->fk_user, $childids) + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)))) { $db->begin(); @@ -866,15 +882,15 @@ llxHeader('', $langs->trans('CPTitreMenu')); if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') { - // Si l'utilisateur n'a pas le droit de faire une demande - if (($fuserid == $user->id && empty($user->rights->holiday->write)) || ($fuserid != $user->id && empty($user->rights->holiday->write_all))) + // If user has no permission to create a leave + if ((in_array($fuserid, $childids) && empty($user->rights->holiday->write)) || (!in_array($fuserid, $childids) && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)))) { $errors[] = $langs->trans('CantCreateCP'); } else { - // Formulaire de demande de congés payés + // Form to add a leave request print load_fiche_titre($langs->trans('MenuAddCP'), '', 'title_hrm.png'); - // Si il y a une erreur + // Error management if (GETPOST('error')) { switch (GETPOST('error')) { case 'datefin' : @@ -981,11 +997,13 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print ''.$langs->trans("User").''; print ''; - if (empty($user->rights->holiday->write_all)) + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->holiday->writeall_advance)) { print $form->select_dolusers(($fuserid ? $fuserid : $user->id), 'fuserid', 0, '', 0, 'hierarchyme', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); //print ''; - } else print $form->select_dolusers(GETPOST('fuserid', 'int') ?GETPOST('fuserid', 'int') : $user->id, 'fuserid', 0, '', 0, '', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); + } else { + print $form->select_dolusers(GETPOST('fuserid', 'int') ? GETPOST('fuserid', 'int') : $user->id, 'fuserid', 0, '', 0, '', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'maxwidth300'); + } print ''; print ''; @@ -1459,7 +1477,7 @@ if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') print ''.$langs->trans("ActionRefuseCP").''; } } - if (($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || !empty($user->rights->holiday->write_all)) && ($object->statut == 2 || $object->statut == 3)) // Status validated or approved + if (($user->id == $object->fk_validator || in_array($object->fk_user, $childids) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance))) && ($object->statut == 2 || $object->statut == 3)) // Status validated or approved { if (($object->date_debut > dol_now()) || $user->admin) print ''.$langs->trans("ActionCancelCP").''; else print ''.$langs->trans("ActionCancelCP").''; diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index ca83d9341f2..0cd0489c701 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -421,7 +421,7 @@ if ($resql) print '
    '; - $canedit = (($user->id == $user_id && $user->rights->holiday->write) || ($user->id != $user_id && $user->rights->holiday->write_all)); + $canedit = (($user->id == $user_id && $user->rights->holiday->write) || ($user->id != $user_id && (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->holiday->writeall_advance)))); if ($canedit) { diff --git a/htdocs/holiday/month_report.php b/htdocs/holiday/month_report.php index baf444ce295..7e7e7ed29f9 100644 --- a/htdocs/holiday/month_report.php +++ b/htdocs/holiday/month_report.php @@ -48,7 +48,10 @@ $massaction = GETPOST('massaction', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ'); $optioncss = GETPOST('optioncss', 'aZ'); -$search_ref = GETPOST('search_ref', 'alpha'); +$search_ref = GETPOST('search_ref', 'alphanohtml'); +$search_employee = GETPOST('search_employee', 'int'); +$search_type = GETPOST('search_type', 'int'); +$search_description = GETPOST('search_description', 'alphanohtml'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); @@ -82,6 +85,9 @@ if (empty($reshook)) if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { $search_ref = ''; + $search_employee = ''; + $search_type = ''; + $search_description = ''; $toselect = ''; $search_array_options = array(); } @@ -135,7 +141,10 @@ $sql.= " WHERE cp.rowid > 0"; $sql.= " AND cp.statut = 3"; // 3 = Approved $sql.= " AND (date_format(cp.date_debut, '%Y-%m') = '".$db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$db->escape($year_month)."')"; -if ($search_ref != '') $sql.= natural_search('cp.ref', $search_ref, 0); +if (!empty($search_ref)) $sql .= natural_search('cp.ref', $search_ref); +if (!empty($search_employee)) $sql .= " AND cp.fk_user = '".$db->escape($search_employee)."'"; +if (!empty($search_type)) $sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; +if (!empty($search_description)) $sql.= natural_search('cp.description', $search_description); $sql.= $db->order($sortfield, $sortorder); @@ -149,9 +158,12 @@ if (empty($resql)) $num = $db->num_rows($resql); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.= '&limit='.urlencode($limit); -if ($search_ref) $param = '&search_ref='.urlencode($search_ref); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref); +if (!empty($search_employee)) $param .= '&search_employee='.urlencode($search_employee); +if (!empty($search_type)) $param .= '&search_type='.urlencode($search_type); +if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); print '
    '; if ($optioncss != '') print ''; @@ -184,16 +196,50 @@ print '
    '; print ''; print ''; -if (!empty($arrayfields['cp.ref']['checked'])) print ''; -if (!empty($arrayfields['cp.fk_user']['checked'])) print ''; -if (!empty($arrayfields['ct.label']['checked'])) print ''; + +// Filter: Ref +if (!empty($arrayfields['cp.ref']['checked'])) { + print ''; +} + +// Filter: Employee +if (!empty($arrayfields['cp.fk_user']['checked'])) { + print ''; +} + +// Filter: Type +if (!empty($arrayfields['ct.label']['checked'])) { + $typeleaves = $holidaystatic->getTypes(1, -1); + $arraytypeleaves = array(); + foreach ($typeleaves as $key => $val) + { + $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); + $arraytypeleaves[$val['rowid']] = $labeltoshow; + } + + print ''; +} + if (!empty($arrayfields['cp.date_debut']['checked'])) print ''; if (!empty($arrayfields['cp.date_fin']['checked'])) print ''; if (!empty($arrayfields['used_days']['checked'])) print ''; if (!empty($arrayfields['date_start_month']['checked'])) print ''; if (!empty($arrayfields['date_end_month']['checked'])) print ''; if (!empty($arrayfields['used_days_month']['checked'])) print ''; -if (!empty($arrayfields['cp.description']['checked'])) print ''; + +// Filter: Description +if (!empty($arrayfields['cp.description']['checked'])) { + print ''; +} + // Action column print '
    '; + print ''; + print ''; + print $form->select_dolusers($search_employee, "search_employee", 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + print ''; + print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1); + print ''; + print ''; + print ''; $searchpicto = $form->showFilterButtons(); diff --git a/htdocs/holiday/view_log.php b/htdocs/holiday/view_log.php index 4ff8238648c..7043f436e87 100644 --- a/htdocs/holiday/view_log.php +++ b/htdocs/holiday/view_log.php @@ -25,9 +25,16 @@ */ require '../main.inc.php'; + +// Security check (access forbidden for external user too) +if (empty($user->rights->holiday->define_holiday) || $user->socid > 0) { + accessforbidden(); +} + +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) @@ -39,15 +46,15 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') -$search_id = GETPOST('search_id', 'alpha'); -$search_prev_solde = GETPOST('search_prev_solde', 'alpha'); -$search_new_solde = GETPOST('search_new_solde', 'alpha'); -$year = GETPOST('year'); -if (empty($year)) -{ - $tmpdate = dol_getdate(dol_now()); - $year = $tmpdate['year']; -} +$search_id = GETPOST('search_id', 'alphanohtml'); +$search_month = GETPOST('search_month', 'int'); +$search_year = GETPOST('search_year', 'int'); +$search_employee = GETPOST('search_employee', 'int'); +$search_validator = GETPOST('search_validator', 'int'); +$search_description = GETPOST('search_description', 'alphanohtml'); +$search_type = GETPOST('search_type', 'int'); +$search_prev_solde = GETPOST('search_prev_solde', 'alphanohtml'); +$search_new_solde = GETPOST('search_new_solde', 'alphanohtml'); // Load variable for pagination $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -61,10 +68,6 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield="cpl.rowid"; if (! $sortorder) $sortorder="DESC"; - -// Protection if external user -if ($user->socid > 0) accessforbidden(); - // Si l'utilisateur n'a pas le droit de lire cette page if (!$user->rights->holiday->read_all) accessforbidden(); @@ -92,81 +95,126 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -if (empty($reshook)) -{ - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { - $search_id = ''; - $toselect = ''; - $search_array_options = array(); - } + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + $search_id = ''; + $search_month = ''; + $search_year = ''; + $search_employee = ''; + $search_validator = ''; + $search_description = ''; + $search_type = ''; + $search_prev_solde = ''; + $search_new_solde = ''; + $toselect = ''; + $search_array_options = array(); + } - if (GETPOST('button_removefilter_x', 'alpha') - || GETPOST('button_removefilter.x', 'alpha') - || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') - || GETPOST('button_search.x', 'alpha') - || GETPOST('button_search', 'alpha')) - { - $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } + if (GETPOST('button_removefilter_x', 'alpha') + || GETPOST('button_removefilter.x', 'alpha') + || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') + || GETPOST('button_search.x', 'alpha') + || GETPOST('button_search', 'alpha')) + { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } - // Mass actions - /*$objectclass='MyObject'; - $objectlabel='MyObject'; - $permissiontoread = $user->rights->mymodule->read; - $permissiontodelete = $user->rights->mymodule->delete; - $uploaddir = $conf->mymodule->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - */ + // Mass actions + /*$objectclass='MyObject'; + $objectlabel='MyObject'; + $permissiontoread = $user->rights->mymodule->read; + $permissiontodelete = $user->rights->mymodule->delete; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + */ } // Definition of fields for lists $arrayfields = array( - 'cpl.rowid'=>array('label'=>$langs->trans("ID"), 'checked'=>1), - 'cpl.date_action'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'cpl.fk_user_action'=>array('label'=>$langs->trans("ActionByCP"), 'checked'=>1), - 'cpl.fk_user_update'=>array('label'=>$langs->trans("UserUpdateCP"), 'checked'=>1), - 'cpl.type_action'=>array('label'=>$langs->trans("Description"), 'checked'=>1), - 'cpl.fk_type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), - 'cpl.prev_solde'=>array('label'=>$langs->trans("PrevSoldeCP"), 'checked'=>1), - 'variation'=>array('label'=>$langs->trans("Variation"), 'checked'=>1), - 'cpl.new_solde'=>array('label'=>$langs->trans("NewSoldeCP"), 'checked'=>1), + 'cpl.rowid'=>array('label'=>$langs->trans("ID"), 'checked'=>1), + 'cpl.date_action'=>array('label'=>$langs->trans("Date"), 'checked'=>1), + 'cpl.fk_user_action'=>array('label'=>$langs->trans("ActionByCP"), 'checked'=>1), + 'cpl.fk_user_update'=>array('label'=>$langs->trans("UserUpdateCP"), 'checked'=>1), + 'cpl.type_action'=>array('label'=>$langs->trans("Description"), 'checked'=>1), + 'cpl.fk_type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'cpl.prev_solde'=>array('label'=>$langs->trans("PrevSoldeCP"), 'checked'=>1), + 'variation'=>array('label'=>$langs->trans("Variation"), 'checked'=>1), + 'cpl.new_solde'=>array('label'=>$langs->trans("NewSoldeCP"), 'checked'=>1), ); + /* * View */ $form = new Form($db); - +$formother = new FormOther($db); +$holidaylogstatic = new stdClass(); $alltypeleaves = $object->getTypes(1, -1); // To have labels -llxHeader('', $langs->trans('CPTitreMenu').' ('.$langs->trans("Year").' '.$year.')'); +llxHeader('', $langs->trans('CPTitreMenu')); -$sqlwhere = " AND date_action BETWEEN ". -$sqlwhere.= "'".$db->idate(dol_get_first_day($year, 1, 1))."'"; -$sqlwhere.= " AND "; -$sqlwhere.= "'".$db->idate(dol_get_last_day($year, 12, 1))."'"; +$sqlwhere = ''; -if ($search_id != '') $sqlwhere.= natural_search('rowid', $search_id, 1); -if ($search_prev_solde != '') $sqlwhere.= natural_search('prev_solde', $search_prev_solde, 1); -if ($search_new_solde != '') $sqlwhere.= natural_search('new_solde', $search_new_solde, 1); +if (!empty($search_year) && $search_year > 0) { + if (!empty($search_month) && $search_month > 0) { + $from_date = dol_get_first_day($search_year, $search_month, 1); + $to_date = dol_get_last_day($search_year, $search_month, 1); + } else { + $from_date = dol_get_first_day($search_year, 1, 1); + $to_date = dol_get_last_day($search_year, 12, 1); + } + + $sqlwhere .= "AND date_action BETWEEN '".$db->idate($from_date)."' AND '".$db->idate($to_date)."'"; +} + +if (!empty($search_id) && $search_id > 0) $sqlwhere.= natural_search('rowid', $search_id, 1); +if (!empty($search_validator) && $search_validator > 0) $sqlwhere.= natural_search('fk_user_action', $search_validator, 1); +if (!empty($search_employee) && $search_employee > 0) $sqlwhere.= natural_search('fk_user_update', $search_employee, 1); +if (!empty($search_description)) $sqlwhere.= natural_search('type_action', $search_description); +if (!empty($search_type) && $search_type > 0) $sqlwhere.= natural_search('fk_type', $search_type, 1); +if (!empty($search_prev_solde)) $sqlwhere.= natural_search('prev_solde', $search_prev_solde, 1); +if (!empty($search_new_solde)) $sqlwhere.= natural_search('new_solde', $search_new_solde, 1); $sqlorder = $db->order($sortfield, $sortorder); // Recent changes are more important than old changes $log_holiday = $object->fetchLog($sqlorder, $sqlwhere); // Load $object->logs +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + //TODO: $result = $db->query($sql); + //TODO: $nbtotalofrecords = $db->num_rows($result); + $nbtotalofrecords = is_array($object->logs) ? count($object->logs) : 0; + + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } +} + +// TODO: $num = $db->num_rows($resql); +$num = is_array($object->logs) ? count($object->logs) : 0; + $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($search_id) $param = '&search_id='.urlencode($search_id); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if (!empty($search_id)) $param .= '&search_statut='.urlencode($search_statut); +if (!empty($search_month) && $search_month > 0) $param .= '&search_month='.urlencode($search_month); +if (!empty($search_year) && $search_year > 0) $param .= '&search_year='.urlencode($search_year); +if (!empty($search_validator) && $search_validator > 0) $param .= '&search_validator='.urlencode($search_validator); +if (!empty($search_employee) && $search_employee > 0) $param .= '&search_employee='.urlencode($search_employee); +if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); +if (!empty($search_type) && $search_type > 0) $param .= '&search_type='.urlencode($search_type); +if (!empty($search_prev_solde)) $param .= '&search_prev_solde='.urlencode($search_prev_solde); +if (!empty($search_new_solde)) $param .= '&search_new_solde='.urlencode($search_new_solde); print ''; if ($optioncss != '') print ''; @@ -178,44 +226,23 @@ print ''; print ''; print ''; -$pagination = ''; - -print load_fiche_titre($langs->trans('LogCP'), $pagination, 'title_hrm.png'); - -print '
    '.$langs->trans('LastUpdateCP').': '."\n"; +print '
    '.$langs->trans('LastUpdateCP').': '; $lastUpdate = $object->getConfCP('lastUpdate'); -if ($lastUpdate) -{ - $monthLastUpdate = $lastUpdate[4].$lastUpdate[5]; - $yearLastUpdate = $lastUpdate[0].$lastUpdate[1].$lastUpdate[2].$lastUpdate[3]; - print ''.dol_print_date($db->jdate($object->getConfCP('lastUpdate')), 'dayhour', 'tzuser').''; - print '
    '.$langs->trans("MonthOfLastMonthlyUpdate").': '.$yearLastUpdate.'-'.$monthLastUpdate.''."\n"; +if ($lastUpdate) { + $monthLastUpdate = $lastUpdate[4].$lastUpdate[5]; + $yearLastUpdate = $lastUpdate[0].$lastUpdate[1].$lastUpdate[2].$lastUpdate[3]; + print ''.dol_print_date($db->jdate($object->getConfCP('lastUpdate')), 'dayhour', 'tzuser').''; + print '
    '; + print $langs->trans("MonthOfLastMonthlyUpdate").': '.$yearLastUpdate.'-'.$monthLastUpdate.''; +} else { + print $langs->trans('None'); } -else { - print $langs->trans('None'); -} -print "

    \n"; +print '
    '; +print '
    '; $moreforfilter = ''; @@ -225,20 +252,84 @@ $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfiel $selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
    '; -print ''."\n"; +print '
    '; -print ''; +print ''; + +// Filter Id +if (!empty($arrayfields['cpl.rowid']['checked'])) { + print ''; +} + +// Filter: Date +if (!empty($arrayfields['cpl.date_action']['checked'])) { + print ''; +} + +// Filter: Validator +if (!empty($arrayfields['cpl.fk_user_action']['checked'])) { + $validator = new UserGroup($db); + $excludefilter = $user->admin ? '' : 'u.rowid <> '.$user->id; + $valideurobjects = $validator->listUsersForGroup($excludefilter); + $valideurarray = array(); + + foreach ($valideurobjects as $val) { + $valideurarray[$val->id] = $val->id; + } + + print ''; +} + +// Filter: User +if (!empty($arrayfields['cpl.fk_user_update']['checked'])) { + print ''; +} + +// Filter: Description +if (!empty($arrayfields['cpl.type_action']['checked'])) { + print ''; +} + +// Filter: Type +if (!empty($arrayfields['cpl.fk_type']['checked'])) { + foreach ($alltypeleaves as $key => $val) { + $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); + $arraytypeleaves[$val['rowid']] = $labeltoshow; + } + + print ''; +} + +// Filter: Previous balance +if (!empty($arrayfields['cpl.prev_solde']['checked'])) { + print ''; +} + +// Filter: Variation (only placeholder) +if (!empty($arrayfields['variation']['checked'])) { + print ''; +} + +// Filter: New Balance +if (!empty($arrayfields['cpl.new_solde']['checked'])) { + print ''; +} -print ''; -if (!empty($arrayfields['cpl.rowid']['checked'])) print ''; -if (!empty($arrayfields['cpl.date_action']['checked'])) print ''; -if (!empty($arrayfields['cpl.fk_user_action']['checked'])) print ''; -if (!empty($arrayfields['cpl.fk_user_update']['checked'])) print ''; -if (!empty($arrayfields['cpl.type_action']['checked'])) print ''; -if (!empty($arrayfields['cpl.fk_type']['checked'])) print ''; -if (!empty($arrayfields['cpl.prev_solde']['checked'])) print ''; -if (!empty($arrayfields['variation']['checked'])) print ''; -if (!empty($arrayfields['cpl.new_solde']['checked'])) print ''; // Action column print ''; +// TODO: $i = 0; +$i = 1; -foreach ($object->logs as $logs_CP) +while ($i < min($num, $limit)) { - $user_action = new User($db); - $user_action->fetch($logs_CP['fk_user_action']); + //TODO: $obj = $db->fetch_object($resql); + $obj = next($object->logs); - $user_update = new User($db); - $user_update->fetch($logs_CP['fk_user_update']); + $holidaylogstatic->id = $obj['rowid']; + $holidaylogstatic->date = $obj['date_action']; + $holidaylogstatic->validator = $obj['fk_user_action']; + $holidaylogstatic->employee = $obj['fk_user_update']; + $holidaylogstatic->description = $obj['type_action']; + $holidaylogstatic->type = $obj['fk_type']; + $holidaylogstatic->balance_previous = $obj['prev_solde']; + $holidaylogstatic->balance_new = $obj['new_solde']; - $delta = price2num($logs_CP['new_solde'] - $logs_CP['prev_solde'], 5); - $detasign = ($delta > 0 ? '+' : ''); + print ''; - print ''; - if (!empty($arrayfields['cpl.rowid']['checked'])) print ''; - if (!empty($arrayfields['cpl.date_action']['checked'])) print ''; - if (!empty($arrayfields['cpl.fk_user_action']['checked'])) print ''; - if (!empty($arrayfields['cpl.fk_user_update']['checked'])) print ''; - if (!empty($arrayfields['cpl.type_action']['checked'])) print ''; - if (!empty($arrayfields['cpl.fk_type']['checked'])) - { - print ''; - } + // Id + if (!empty($arrayfields['cpl.rowid']['checked'])) { + print ''; + } - if (!empty($arrayfields['cpl.prev_solde']['checked'])) print ''; - if (!empty($arrayfields['variation']['checked'])) print ''; - if (!empty($arrayfields['cpl.new_solde']['checked'])) print ''; - print ''; - print ''."\n"; + // Date + if (!empty($arrayfields['cpl.date_action']['checked'])) { + print ''; + } + + // Validator + if (!empty($arrayfields['cpl.fk_user_action']['checked'])) { + $user_action = new User($db); + $user_action->fetch($holidaylogstatic->validator); + print ''; + } + + // Emloyee + if (!empty($arrayfields['cpl.fk_user_update']['checked'])) { + $user_update = new User($db); + $user_update->fetch($holidaylogstatic->employee); + print ''; + } + + // Description + if (!empty($arrayfields['cpl.type_action']['checked'])) { + print ''; + } + + // Type + if (!empty($arrayfields['cpl.fk_type']['checked'])) { + if ($alltypeleaves[$holidaylogstatic->type]['code'] && $langs->trans($alltypeleaves[$holidaylogstatic->type]['code']) != $alltypeleaves[$holidaylogstatic->type]['code']) { + $label = $langs->trans($alltypeleaves[$holidaylogstatic->type]['code']); + } else { + $label = $alltypeleaves[$holidaylogstatic->type]['label']; + } + + print ''; + } + + // Previous balance + if (!empty($arrayfields['cpl.prev_solde']['checked'])) { + print ''; + } + + // Variation + if (!empty($arrayfields['variation']['checked'])) { + $delta = price2num($holidaylogstatic->balance_new - $holidaylogstatic->balance_previous, 5); + $detasign = ($delta > 0 ? '+' : ''); + print ''; + } + + // New Balance + if (!empty($arrayfields['cpl.new_solde']['checked'])) { + print ''; + } + + // Buttons + print ''; + + print ''; + + $i++; } -if ($log_holiday == '2') -{ - print ''; - print ''; - print ''; +if ($log_holiday == '2') { + print ''; + print ''; + print ''; } -print ''."\n"; -print '
    '; + print ''; + print $formother->selectyear($search_year, 'search_year', 1, 10, 5, 0, 0, '', 'maxwidth200', true); + print ''; + print $form->select_dolusers($search_validator, "search_validator", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); + print ''; + print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, $include, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200'); + print ''; + print ''; + print ''; + print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1); + print ''; + print ''; + print ''; + print ''; + print '
    '; $searchpicto = $form->showFilterButtons(); @@ -256,51 +347,102 @@ if (!empty($arrayfields['cpl.fk_type']['checked'])) print_liste_field_titre($arr if (!empty($arrayfields['cpl.prev_solde']['checked'])) print_liste_field_titre($arrayfields['cpl.prev_solde']['label'], $_SERVER["PHP_SELF"], 'prev_solde', '', '', '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['variation']['checked'])) print_liste_field_titre($arrayfields['variation']['label'], $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['cpl.new_solde']['checked'])) print_liste_field_titre($arrayfields['cpl.new_solde']['label'], $_SERVER["PHP_SELF"], 'new_solde', '', '', '', $sortfield, $sortorder, 'right '); -print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print '
    '.$logs_CP['rowid'].''.$logs_CP['date_action'].''.$user_action->getNomUrl(-1).''.$user_update->getNomUrl(-1).''.$logs_CP['type_action'].''; - $label = (($alltypeleaves[$logs_CP['fk_type']]['code'] && $langs->trans($alltypeleaves[$logs_CP['fk_type']]['code']) != $alltypeleaves[$logs_CP['fk_type']]['code']) ? $langs->trans($alltypeleaves[$logs_CP['fk_type']]['code']) : $alltypeleaves[$logs_CP['fk_type']]['label']); - print $label ? $label : $logs_CP['fk_type']; - print ''.$holidaylogstatic->id.''.price2num($logs_CP['prev_solde'], 5).' '.$langs->trans('days').''.$detasign.$delta.''.price2num($logs_CP['new_solde'], 5).' '.$langs->trans('days').'
    '.$holidaylogstatic->date.''.$user_action->getNomUrl(-1).''.$user_update->getNomUrl(-1).''.$holidaylogstatic->description.''; + print $label ? $label : $holidaylogstatic->type; + print ''.price2num($holidaylogstatic->balance_previous, 5).' '.$langs->trans('days').''.$detasign.$delta.''.price2num($holidaylogstatic->balance_new, 5).' '.$langs->trans('days').'
    '.$langs->trans('NoRecordFound').'
    '.$langs->trans('NoRecordFound').'
    '."\n"; +print '
    '; print '
    '; print '
    '; diff --git a/htdocs/hrm/index.php b/htdocs/hrm/index.php index 88141debfad..3955e3f849a 100644 --- a/htdocs/hrm/index.php +++ b/htdocs/hrm/index.php @@ -96,42 +96,42 @@ print '
    '; if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo { - if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) - { - $langs->load("holiday"); - $listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP'); - } - if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) - { - $langs->load("trips"); - $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); - } - if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) - { - $langs->load("trips"); - $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); - } - if (count($listofsearchfields)) - { - print '
    '; - print ''; - print '
    '; - print ''; - $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print ''; - print ''; - print ''; - if ($i == 0) print ''; - print ''; - $i++; - } - print '
    '.$langs->trans("Search").'
    '; - print '
    '; - print '
    '; - print '
    '; - } + if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) + { + $langs->load("holiday"); + $listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP'); + } + if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) + { + $langs->load("trips"); + $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); + } + if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) + { + $langs->load("trips"); + $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); + } + if (count($listofsearchfields)) + { + print '
    '; + print ''; + print '
    '; + print ''; + $i = 0; + foreach ($listofsearchfields as $key => $value) + { + if ($i == 0) print ''; + print ''; + print ''; + if ($i == 0) print ''; + print ''; + $i++; + } + print '
    '.$langs->trans("Search").'
    '; + print '
    '; + print '
    '; + print '
    '; + } } @@ -141,26 +141,26 @@ if (!empty($conf->holiday->enabled)) { $user_id = $user->id; - print '
    '; - print ''; - print ''; - print ''; - print ''; + print ''; + print '
    '.$langs->trans("Holidays").'
    '; + print '
    '; + print ''; + print ''; + print ''; + print ''; - print ''; - print '
    '.$langs->trans("Holidays").'
    '; - $out = ''; - $typeleaves = $holiday->getTypes(1, 1); - foreach ($typeleaves as $key => $val) - { - $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); - $nb_holiday += $nb_type; - $out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
    '; - } - print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
    '; - print $out; + $out = ''; + $typeleaves = $holiday->getTypes(1, 1); + foreach ($typeleaves as $key => $val) + { + $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); + $nb_holiday += $nb_type; + $out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
    '; + } + print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
    '; + print $out; - print '

    '; + print '

    '; } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) { print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'
    '; @@ -175,80 +175,80 @@ print '
    '; // Latest leave requests if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) { - $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,"; - $sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, x.statut as status"; - $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.rowid = x.fk_user"; - $sql .= " AND x.entity = ".$conf->entity; - if (empty($user->rights->holiday->read_all)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')'; - //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid; - $sql .= $db->order("x.tms", "DESC"); - $sql .= $db->plimit($max, 0); + $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,"; + $sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, x.statut as status"; + $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE u.rowid = x.fk_user"; + $sql .= " AND x.entity = ".$conf->entity; + if (empty($user->rights->holiday->read_all)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')'; + //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid; + $sql .= $db->order("x.tms", "DESC"); + $sql .= $db->plimit($max, 0); - $result = $db->query($sql); - if ($result) - { - $var = false; - $num = $db->num_rows($result); + $result = $db->query($sql); + if ($result) + { + $var = false; + $num = $db->num_rows($result); - $holidaystatic = new Holiday($db); - $userstatic = new User($db); + $holidaystatic = new Holiday($db); + $userstatic = new User($db); - $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); - $typeleaves = $holidaystatic->getTypes(1, -1); + $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); + $typeleaves = $holidaystatic->getTypes(1, -1); - $i = 0; + $i = 0; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if ($num) - { - while ($i < $num && $i < $max) - { - $obj = $db->fetch_object($result); + print '
    '; + print '
    '.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).''.$langs->trans("from").''.$langs->trans("to").''.$langs->trans("FullList").'
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($num) + { + while ($i < $num && $i < $max) + { + $obj = $db->fetch_object($result); - $holidaystatic->id = $obj->rowid; - $holidaystatic->ref = $obj->ref; - $holidaystatic->statut = $obj->status; + $holidaystatic->id = $obj->rowid; + $holidaystatic->ref = $obj->ref; + $holidaystatic->statut = $obj->status; - $userstatic->id = $obj->uid; - $userstatic->lastname = $obj->lastname; - $userstatic->firstname = $obj->firstname; - $userstatic->login = $obj->login; - $userstatic->photo = $obj->photo; - $userstatic->email = $obj->email; - $userstatic->statut = $obj->user_status; + $userstatic->id = $obj->uid; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; + $userstatic->login = $obj->login; + $userstatic->photo = $obj->photo; + $userstatic->email = $obj->email; + $userstatic->statut = $obj->user_status; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning'; - $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon'; + $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning'; + $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - $i++; - } - } else { - print ''; - } - print '
    '.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).''.$langs->trans("from").''.$langs->trans("to").''.$langs->trans("FullList").'
    '.$holidaystatic->getNomUrl(1).''.$userstatic->getNomUrl(-1, 'leave').''.$typeleaves[$obj->fk_type]['label'].'
    '.$holidaystatic->getNomUrl(1).''.$userstatic->getNomUrl(-1, 'leave').''.$typeleaves[$obj->fk_type]['label'].''.dol_print_date($db->jdate($obj->date_start), 'day').' '.$langs->trans($listhalfday[$starthalfday]).''; - print ''.dol_print_date($db->jdate($obj->date_end), 'day').' '.$langs->trans($listhalfday[$endhalfday]).''; - print ''.dol_print_date($db->jdate($obj->dm), 'day').''.$holidaystatic->LibStatut($obj->status, 3).'
    '.dol_print_date($db->jdate($obj->date_start), 'day').' '.$langs->trans($listhalfday[$starthalfday]).''; + print ''.dol_print_date($db->jdate($obj->date_end), 'day').' '.$langs->trans($listhalfday[$endhalfday]).''; + print ''.dol_print_date($db->jdate($obj->dm), 'day').''.$holidaystatic->LibStatut($obj->status, 3).'
    '.$langs->trans("None").'
    '; - print '
    '; - print '
    '; - } else dol_print_error($db); + $i++; + } + } else { + print ''.$langs->trans("None").''; + } + print ''; + print '
    '; + print '
    '; + } else dol_print_error($db); } @@ -298,7 +298,7 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) $userstatic->id = $obj->uid; $userstatic->lastname = $obj->lastname; $userstatic->firstname = $obj->firstname; - $userstatic->email = $obj->email; + $userstatic->email = $obj->email; $userstatic->login = $obj->login; $userstatic->statut = $obj->user_status; $userstatic->photo = $obj->photo; diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index 71fad9dee9b..6c93d96619f 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -361,7 +361,7 @@ if ($step == 1 || !$datatoimport) print ''; if ($objimport->array_import_perms[$key]) { - print ''.img_picto($langs->trans("NewImport"), 'filenew').''; + print ''.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').''; } else { print $langs->trans("NotEnoughPermissions"); } @@ -424,7 +424,7 @@ if ($step == 2 && $datatoimport) print ''; print ''; - print ''.$langs->trans("ChooseFormatOfFileToImport", img_picto('', 'filenew')).'

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

    '; print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; @@ -445,7 +445,7 @@ if ($step == 2 && $datatoimport) print ''; // Action button print ''; print ''; } @@ -549,7 +549,7 @@ if ($step == 3 && $datatoimport) print ''; print ''; - print ''.$langs->trans("ChooseFileToImport", img_picto('', 'filenew')).'

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

    '; print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
    '.$langs->trans("DownloadEmptyExample").''; - print ''.img_picto($langs->trans("SelectFormat"), 'filenew').''; + print ''.img_picto($langs->trans("SelectFormat"), 'next', 'class="fa-15x"').''; print '
    '; @@ -643,7 +643,7 @@ if ($step == 3 && $datatoimport) print '">'.img_delete().''; // Action button print ''; print ''; } diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php index 5ec9b8f8870..5012337daf8 100644 --- a/htdocs/includes/odtphp/odf.php +++ b/htdocs/includes/odtphp/odf.php @@ -142,7 +142,7 @@ class Odf } $this->vars[$tag] = $this->convertVarToOdf($value, $encode, $charset); - + return $this; } @@ -156,6 +156,7 @@ class Odf */ public function convertVarToOdf($value, $encode = true, $charset = 'ISO-8859') { + $value = $encode ? htmlspecialchars($value) : $value; $value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value; $convertedValue = $value; @@ -170,9 +171,9 @@ class Odf '', '' ); - + $convertedValue = $this->_replaceHtmlWithOdtTag($this->_getDataFromHtml($value), $customStyles, $fontDeclarations); - + foreach ($customStyles as $key => $val) { array_push($automaticStyles, '' . $val . ''); } @@ -399,7 +400,7 @@ class Odf public function htmlToUTFAndPreOdf($value) { // We decode into utf8, entities - $value=dol_html_entity_decode($value, ENT_QUOTES); + $value=dol_html_entity_decode($value, ENT_QUOTES|ENT_HTML5); // We convert html tags $ishtml=dol_textishtml($value); diff --git a/htdocs/includes/tecnickcom/tcpdf/include/tcpdf_fonts.php b/htdocs/includes/tecnickcom/tcpdf/include/tcpdf_fonts.php index 218fb6df1e5..8681dfbdbfa 100644 --- a/htdocs/includes/tecnickcom/tcpdf/include/tcpdf_fonts.php +++ b/htdocs/includes/tecnickcom/tcpdf/include/tcpdf_fonts.php @@ -1149,7 +1149,7 @@ class TCPDF_FONTS { $subsetglyphs[$g] = true; } } - } + } break; } case 6: { // Format 6: Trimmed table mapping diff --git a/htdocs/install/mysql/data/llx_c_product_nature.sql b/htdocs/install/mysql/data/llx_c_product_nature.sql new file mode 100644 index 00000000000..8351ff2ab79 --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_product_nature.sql @@ -0,0 +1,28 @@ +-- Copyright (C) 2020 florian HENRY florian.henry@scopen.fr +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- + +-- +-- Do not place a comment at the end of the line, this file is parsed when +-- from the install and all '--' are removed. +-- +-- Ne pas placer de commentaire en fin de ligne, ce fichier est parsé lors +-- de l'install et tous les sigles '--' sont supprimés. +-- + +INSERT INTO llx_c_product_nature (code, label, active) VALUES (0, 'RowMaterial', 1); +INSERT INTO llx_c_product_nature (code, label, active) VALUES (1, 'Finished', 1); + diff --git a/htdocs/install/mysql/data/llx_c_transport_mode.sql b/htdocs/install/mysql/data/llx_c_transport_mode.sql new file mode 100644 index 00000000000..69f6ac7f6b8 --- /dev/null +++ b/htdocs/install/mysql/data/llx_c_transport_mode.sql @@ -0,0 +1,31 @@ +-- Copyright (C) 2019-2020 Open-DSI +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- + +-- +-- Ne pas placer de commentaire en fin de ligne, ce fichier est parsé lors +-- de l'install et tous les sigles '--' sont supprimés. +-- + + +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('MAR', 'Transport maritime (y compris camions ou wagons sur bateau)', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('TRA', 'Transport par chemin de fer (y compris camions sur wagon)', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('ROU', 'Transport par route', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('AIR', 'Transport par air', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('POS', 'Envois postaux', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('OLE', 'Installations de transport fixe (oléoduc)', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('NAV', 'Transport par navigation intérieure', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('PRO', 'Propulsion propre', 1); diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql index 831097ebf48..19c6070eb2a 100644 --- a/htdocs/install/mysql/data/llx_c_tva.sql +++ b/htdocs/install/mysql/data/llx_c_tva.sql @@ -123,10 +123,11 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 5 insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1021, 102, 0, 0, '0', 0, '0', 0, 'Μηδενικό Φ.Π.Α.', 1); insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1022, 102, 24, 0, '0', 0, '0', 0, 'Κανονικός Φ.Π.Α.', 1); insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1023, 102, 13, 0, '0', 0, '0', 0, 'Μειωμένος Φ.Π.Α.', 1); -insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1024, 102, 6.5, 0, '0', 0, '0', 0, 'Υπερμειωμένος Φ.Π.Α.', 1); +insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1024, 102, 6, 0, '0', 0, '0', 0, 'Υπερμειωμένος Φ.Π.Α.', 1); insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1025, 102, 16, 0, '0', 0, '0', 0, 'Νήσων κανονικός Φ.Π.Α.', 1); insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1026, 102, 9, 0, '0', 0, '0', 0, 'Νήσων μειωμένος Φ.Π.Α.', 1); -insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1027, 102, 5, 0, '0', 0, '0', 0, 'Νήσων υπερμειωμένος Φ.Π.Α.', 1); +insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1027, 102, 4, 0, '0', 0, '0', 0, 'Νήσων υπερμειωμένος Φ.Π.Α.', 1); +insert into llx_c_tva(rowid,fk_pays,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1028, 102, 17, 0, '0', 0, '0', 0, 'Νήσων υπερμειωμένος Φ.Π.Α.', 1); -- ICELAND (id country=116) insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (1161, 116, '0','0','VAT rate 0',1); diff --git a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql index b66d205ef40..9bb097d10b2 100644 --- a/htdocs/install/mysql/migration/10.0.0-11.0.0.sql +++ b/htdocs/install/mysql/migration/10.0.0-11.0.0.sql @@ -119,7 +119,7 @@ ALTER TABLE llx_categorie_warehouse ADD CONSTRAINT fk_categorie_warehouse_fk_war create table llx_holiday_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -135,7 +135,7 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value create table llx_entrepot_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -165,7 +165,7 @@ ALTER TABLE llx_events ADD COLUMN prefix_session varchar(255) NULL; create table llx_payment_salary_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- salary payment id import_key varchar(14) -- import key )ENGINE=innodb; @@ -183,8 +183,8 @@ ALTER TABLE llx_oauth_token ADD COLUMN fk_soc integer DEFAULT NULL after token; ALTER TABLE llx_adherent_type ADD COLUMN duration varchar(6) DEFAULT NULL after morphy; -ALTER TABLE llx_mailing ADD COLUMN tms timestamp; -ALTER TABLE llx_mailing_cibles ADD COLUMN tms timestamp; +ALTER TABLE llx_mailing ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; +ALTER TABLE llx_mailing_cibles ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_projet ADD COLUMN usage_opportunity integer DEFAULT 0; ALTER TABLE llx_projet ADD COLUMN usage_task integer DEFAULT 1; @@ -458,7 +458,7 @@ create table llx_c_shipment_package_type CREATE TABLE llx_product_fournisseur_price_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -478,7 +478,7 @@ CREATE TABLE llx_mrp_mo( note_private text, date_creation datetime NOT NULL, date_valid datetime NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, fk_user_valid integer, @@ -514,7 +514,7 @@ ALTER TABLE llx_mrp_mo ADD INDEX idx_mrp_mo_fk_project (fk_project); create table llx_mrp_mo_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -551,7 +551,7 @@ CREATE TABLE llx_mrp_production( fk_mrp_production integer, -- if role = 'consumed', id of line with role 'toconsume', if role = 'produced' id of line with role 'toproduce' fk_stock_movement integer, -- id of stock movement when movements are validated date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14) @@ -576,7 +576,7 @@ ALTER TABLE llx_facture_rec MODIFY COLUMN fk_cond_reglement integer NOT NULL DEF create table llx_commande_fournisseur_dispatch_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -587,7 +587,7 @@ ALTER TABLE llx_commande_fournisseur_dispatch_extrafields ADD INDEX idx_commande create table llx_facturedet_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/11.0.0-12.0.0.sql b/htdocs/install/mysql/migration/11.0.0-12.0.0.sql index 994e5d89495..488548ae8b1 100644 --- a/htdocs/install/mysql/migration/11.0.0-12.0.0.sql +++ b/htdocs/install/mysql/migration/11.0.0-12.0.0.sql @@ -36,7 +36,7 @@ UPDATE llx_c_units set scale = 86400 where code = 'D' and unit_type = 'time'; create table llx_commande_fournisseur_dispatch_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -57,7 +57,7 @@ create table llx_c_shipment_package_type create table llx_facturedet_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -69,7 +69,7 @@ ALTER TABLE llx_facture_rec MODIFY COLUMN titre varchar(200) NOT NULL; create table llx_mrp_mo_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -303,7 +303,7 @@ ALTER TABLE llx_categorie_website_page ADD CONSTRAINT fk_categorie_website_page_ ALTER TABLE llx_categorie_website_page ADD CONSTRAINT fk_categorie_website_page_website_page_rowid FOREIGN KEY (fk_website_page) REFERENCES llx_website_page (rowid); ALTER TABLE llx_categorie ADD COLUMN date_creation datetime; -ALTER TABLE llx_categorie ADD COLUMN tms timestamp; +ALTER TABLE llx_categorie ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_categorie ADD COLUMN fk_user_creat integer; ALTER TABLE llx_categorie ADD COLUMN fk_user_modif integer; diff --git a/htdocs/install/mysql/migration/12.0.0-13.0.0.sql b/htdocs/install/mysql/migration/12.0.0-13.0.0.sql index 88c17cc0619..389d7dc478e 100644 --- a/htdocs/install/mysql/migration/12.0.0-13.0.0.sql +++ b/htdocs/install/mysql/migration/12.0.0-13.0.0.sql @@ -47,7 +47,7 @@ ALTER TABLE llx_bom_bom_extrafields ADD INDEX idx_bom_bom_extrafields_fk_object create table llx_mrp_mo_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -103,10 +103,47 @@ ALTER TABLE llx_user DROP COLUMN whatsapp; ALTER TABLE llx_user ADD COLUMN datestartvalidity datetime; ALTER TABLE llx_user ADD COLUMN dateendvalidity datetime; +-- Intracomm Report +CREATE TABLE llx_c_transport_mode ( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + code varchar(3) NOT NULL, + label varchar(255) NOT NULL, + active tinyint DEFAULT 1 NOT NULL +) ENGINE=innodb; + +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('MAR', 'Transport maritime (y compris camions ou wagons sur bateau)', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('TRA', 'Transport par chemin de fer (y compris camions sur wagon)', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('ROU', 'Transport par route', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('AIR', 'Transport par air', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('POS', 'Envois postaux', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('OLE', 'Installations de transport fixe (oléoduc)', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('NAV', 'Transport par navigation intérieure', 1); +INSERT INTO llx_c_transport_mode (code, label, active) VALUES ('PRO', 'Propulsion propre', 1); + +ALTER TABLE llx_facture ADD COLUMN fk_transport_mode integer after location_incoterms; +ALTER TABLE llx_facture_fourn ADD COLUMN fk_transport_mode integer after location_incoterms; + +ALTER TABLE llx_societe ADD COLUMN transport_mode tinyint after cond_reglement; +ALTER TABLE llx_societe ADD COLUMN transport_mode_supplier tinyint after cond_reglement_supplier; + +CREATE TABLE llx_intracommreport +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + + ref varchar(30) NOT NULL, -- report reference number + entity integer DEFAULT 1 NOT NULL, -- multi company id + type_declaration varchar(32), + periods varchar(32), + mode varchar(32), + content_xml text, + type_export varchar(10), + datec datetime, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +)ENGINE=innodb; + ALTER TABLE llx_c_incoterms ADD COLUMN label varchar(100) NULL; - - CREATE TABLE llx_recruitment_recruitmentjobposition( rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, ref varchar(128) DEFAULT '(PROV)' NOT NULL, @@ -124,7 +161,7 @@ CREATE TABLE llx_recruitment_recruitmentjobposition( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, last_main_doc varchar(255), @@ -150,7 +187,7 @@ ALTER TABLE llx_recruitment_recruitmentjobposition ADD COLUMN remuneration_sugge create table llx_recruitment_recruitmentjobposition_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -169,7 +206,7 @@ CREATE TABLE llx_recruitment_recruitmentcandidature( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), @@ -200,7 +237,7 @@ ALTER TABLE llx_recruitment_recruitmentcandidature ADD INDEX idx_recruitment_rec create table llx_recruitment_recruitmentcandidature_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -275,6 +312,7 @@ ALTER TABLE llx_recruitment_recruitmentcandidature ADD UNIQUE INDEX uk_recruitme ALTER TABLE llx_product MODIFY COLUMN seuil_stock_alerte float; ALTER TABLE llx_product MODIFY COLUMN desiredstock float; + ALTER TABLE llx_product_warehouse_properties MODIFY COLUMN seuil_stock_alerte float; ALTER TABLE llx_product_warehouse_properties MODIFY COLUMN desiredstock float; @@ -290,8 +328,8 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('CONTACT_SENTBYMAIL','Mails sent from third party card','Executed when you send email from contact adress card','contact',51); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('CONTACT_DELETE','Contact address deleted','Executed when a contact is deleted','contact',52); -ALTER TABLE llx_ecm_directories CHANGE COLUMN date_m tms timestamp; -ALTER TABLE llx_ecm_files CHANGE COLUMN date_m tms timestamp; +ALTER TABLE llx_ecm_directories CHANGE COLUMN date_m tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; +ALTER TABLE llx_ecm_files CHANGE COLUMN date_m tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines,joinfiles) VALUES (0,'recruitment','recruitmentcandidature_send','',0,null,null,'(AnswerCandidature)' ,100,'$conf->recruitment->enabled',1,'[__[MAIN_INFO_SOCIETE_NOM]__] __(YourCandidature)__', '__(Hello)__ __CANDIDATE_FULLNAME__,

    \n\n__(YourCandidatureAnswer)__
    \n

    \n__(Sincerely)__
    __USER_SIGNATURE__',null, 0); @@ -324,6 +362,8 @@ ALTER TABLE llx_facturedet ADD COLUMN ref_ext varchar(255) AFTER multicurrency_t ALTER TABLE llx_c_ticket_category ADD COLUMN fk_parent integer DEFAULT 0 NOT NULL; ALTER TABLE llx_c_ticket_category ADD COLUMN force_severity varchar(32) NULL; +ALTER TABLE llx_expensereport ADD COLUMN fk_user_creat integer NULL; + ALTER TABLE llx_expensereport_ik ADD COLUMN ikoffset double DEFAULT 0 NOT NULL; ALTER TABLE llx_paiement ADD COLUMN ref_ext varchar(255) AFTER ref; @@ -337,7 +377,7 @@ ALTER TABLE llx_menu MODIFY COLUMN enabled text; CREATE TABLE llx_ecm_files_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -347,7 +387,7 @@ ALTER TABLE llx_ecm_files_extrafields ADD INDEX idx_ecm_files_extrafields (fk_ob CREATE TABLE llx_ecm_directories_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -355,3 +395,29 @@ CREATE TABLE llx_ecm_directories_extrafields ALTER TABLE llx_ecm_directories_extrafields ADD INDEX idx_ecm_directories_extrafields (fk_object); ALTER TABLE llx_website_page ADD COLUMN object_type varchar(255); ALTER TABLE llx_website_page ADD COLUMN fk_object varchar(255); + +DELETE FROM llx_const WHERE name in ('MAIN_INCLUDE_ZERO_VAT_IN_REPORTS'); + +UPDATE llx_projet_task_time SET tms = null WHERE tms = 0; +ALTER TABLE llx_projet_task_time MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; + +ALTER TABLE llx_projet_task_time MODIFY COLUMN datec datetime; + +DELETE FROM llx_user_rights WHERE fk_id IN (SELECT id FROM llx_rights_def where module = 'holiday' and perms = 'lire_tous'); +DELETE FROM llx_rights_def where module = 'holiday' and perms = 'lire_tous'; + +CREATE TABLE llx_c_product_nature ( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code tinyint NOT NULL, + label varchar(100), + active tinyint DEFAULT 1 NOT NULL +) ENGINE=innodb; + +ALTER TABLE llx_c_product_nature ADD UNIQUE INDEX uk_c_product_nature(code, active); + +INSERT INTO llx_c_product_nature (code, label, active) VALUES (0, 'RowMaterial', 1); +INSERT INTO llx_c_product_nature (code, label, active) VALUES (1, 'Finished', 1); + +ALTER TABLE llx_product MODIFY COLUMN finished tinyint DEFAULT NULL; +ALTER TABLE llx_product ADD CONSTRAINT fk_product_finished FOREIGN KEY (finished) REFERENCES llx_c_product_nature (code); + diff --git a/htdocs/install/mysql/migration/3.0.0-3.1.0.sql b/htdocs/install/mysql/migration/3.0.0-3.1.0.sql index a4ab666299d..4104d74da51 100644 --- a/htdocs/install/mysql/migration/3.0.0-3.1.0.sql +++ b/htdocs/install/mysql/migration/3.0.0-3.1.0.sql @@ -419,19 +419,19 @@ update llx_actioncomm set elementtype='order' where elementtype='commande'; update llx_actioncomm set elementtype='contract' where elementtype='contrat'; -alter table llx_propal add column tms timestamp after fk_projet; +alter table llx_propal add column tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP after fk_projet; create table llx_product_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL ) ENGINE=innodb; create table llx_societe_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL ) ENGINE=innodb; @@ -487,7 +487,7 @@ ALTER TABLE llx_don ADD phone varchar(24) after email; ALTER TABLE llx_element_element MODIFY sourcetype varchar(32) NOT NULL; ALTER TABLE llx_element_element MODIFY targettype varchar(32) NOT NULL; -ALTER TABLE llx_societe_prices MODIFY tms timestamp NULL; +ALTER TABLE llx_societe_prices MODIFY tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; -- ALTER TABLE llx_societe_prices ALTER COLUMN tms DROP NOT NULL; -- Fix: It seems this is missing for some users diff --git a/htdocs/install/mysql/migration/3.1.0-3.2.0.sql b/htdocs/install/mysql/migration/3.1.0-3.2.0.sql index 044b1652029..c7356cc18ff 100644 --- a/htdocs/install/mysql/migration/3.1.0-3.2.0.sql +++ b/htdocs/install/mysql/migration/3.1.0-3.2.0.sql @@ -62,7 +62,7 @@ ALTER TABLE llx_societe MODIFY code_compta varchar(24); ALTER TABLE llx_societe MODIFY code_compta_fournisseur varchar(24); -ALTER TABLE llx_chargesociales ADD COLUMN tms timestamp; +ALTER TABLE llx_chargesociales ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_chargesociales ADD COLUMN date_creation datetime; ALTER TABLE llx_chargesociales ADD COLUMN date_valid datetime; @@ -118,7 +118,7 @@ CREATE TABLE llx_localtax ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer NOT NULL DEFAULT '1', - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep date DEFAULT NULL, datev date DEFAULT NULL, amount double NOT NULL DEFAULT '0', diff --git a/htdocs/install/mysql/migration/3.2.0-3.3.0.sql b/htdocs/install/mysql/migration/3.2.0-3.3.0.sql index c0efe6d68b3..07b390f32c4 100644 --- a/htdocs/install/mysql/migration/3.2.0-3.3.0.sql +++ b/htdocs/install/mysql/migration/3.2.0-3.3.0.sql @@ -39,7 +39,7 @@ ALTER TABLE llx_societe DROP COLUMN description; ALTER TABLE llx_societe DROP COLUMN services; ALTER TABLE llx_societe MODIFY COLUMN ref_ext varchar(128); -ALTER TABLE llx_bank ADD COLUMN tms timestamp after datec; +ALTER TABLE llx_bank ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP after datec; -- Monaco VAT Rates insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 271, 27,'19.6','0','VAT standard rate (France hors DOM-TOM)',1); @@ -267,7 +267,7 @@ ALTER TABLE llx_extrafields ADD COLUMN fieldrequired INTEGER DEFAULT 0; create table llx_socpeople_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -276,7 +276,7 @@ ALTER TABLE llx_socpeople_extrafields ADD INDEX idx_socpeople_extrafields (fk_ob create table llx_actioncomm_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -835,7 +835,7 @@ CREATE TABLE llx_product_price_by_qty ( rowid integer AUTO_INCREMENT PRIMARY KEY, fk_product_price integer NOT NULL, - date_price timestamp, + date_price timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, price double (24,8) DEFAULT 0, price_ttc double (24,8) DEFAULT 0, qty_min real DEFAULT 0 @@ -910,7 +910,7 @@ ALTER TABLE llx_bank_account MODIFY COLUMN code_banque varchar(8); create table llx_user_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- member id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/3.3.0-3.4.0.sql b/htdocs/install/mysql/migration/3.3.0-3.4.0.sql index 88d9ae1b685..edc2c931ee1 100644 --- a/htdocs/install/mysql/migration/3.3.0-3.4.0.sql +++ b/htdocs/install/mysql/migration/3.3.0-3.4.0.sql @@ -23,7 +23,7 @@ ALTER TABLE llx_menu MODIFY COLUMN leftmenu varchar(100); create table llx_adherent_type_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -115,7 +115,7 @@ ALTER TABLE llx_c_shipment_mode ADD COLUMN tracking VARCHAR(255) NOT NULL DEFAUL -- VMYSQL4.3 ALTER TABLE llx_c_shipment_mode CHANGE COLUMN rowid rowid INTEGER NOT NULL AUTO_INCREMENT; -- VPGSQL8.2 DROP table llx_c_shipment_mode; --- VPGSQL8.2 CREATE TABLE llx_c_shipment_mode (rowid SERIAL PRIMARY KEY, tms timestamp, code varchar(30) NOT NULL, libelle varchar(50) NOT NULL, description text, tracking varchar(255) NOT NULL, active integer DEFAULT 0, module varchar(32) NULL); +-- VPGSQL8.2 CREATE TABLE llx_c_shipment_mode (rowid SERIAL PRIMARY KEY, tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, code varchar(30) NOT NULL, libelle varchar(50) NOT NULL, description text, tracking varchar(255) NOT NULL, active integer DEFAULT 0, module varchar(32) NULL); -- VPGSQL8.2 INSERT INTO llx_c_shipment_mode (rowid,code,libelle,description,tracking,active) VALUES (1,'CATCH','Catch','Catch by client','',1); -- VPGSQL8.2 INSERT INTO llx_c_shipment_mode (rowid,code,libelle,description,tracking,active) VALUES (2,'TRANS','Transporter','Generic transporter','',1); -- VPGSQL8.2 INSERT INTO llx_c_shipment_mode (rowid,code,libelle,description,tracking,active) VALUES (3,'COLSUI','Colissimo Suivi','Colissimo Suivi','',0); @@ -136,7 +136,7 @@ ALTER TABLE llx_stock_mouvement MODIFY COLUMN value real; create table llx_propal_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -145,7 +145,7 @@ ALTER TABLE llx_propal_extrafields ADD INDEX idx_propal_extrafields (fk_object); create table llx_facture_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -205,7 +205,7 @@ ALTER TABLE llx_facturedet DROP COLUMN fk_export_compta; CREATE TABLE llx_cronjob ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, jobtype varchar(10) NOT NULL, label text NOT NULL, @@ -249,7 +249,7 @@ DROP TABLE llx_printer_ipp; CREATE TABLE llx_printer_ipp ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, printer_name text NOT NULL, printer_location text NOT NULL, @@ -265,7 +265,7 @@ ALTER TABLE llx_adherent MODIFY COLUMN ref_ext varchar(128); create table llx_commande_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -299,7 +299,7 @@ ALTER TABLE llx_socpeople CHANGE COLUMN note note_private text; create table llx_projet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -308,7 +308,7 @@ ALTER TABLE llx_projet_extrafields ADD INDEX idx_projet_extrafields (fk_object); create table llx_projet_task_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -319,7 +319,7 @@ CREATE TABLE llx_opensurvey_comments ( id_comment INTEGER unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, id_sondage CHAR(16) NOT NULL, comment text NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, usercomment text ) ENGINE=InnoDB; @@ -336,7 +336,7 @@ CREATE TABLE llx_opensurvey_sondage ( survey_link_visible integer DEFAULT 1, canedit integer DEFAULT 0, origin varchar(64), - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, sujet TEXT ) ENGINE=InnoDB; CREATE TABLE llx_opensurvey_user_studs ( @@ -344,7 +344,7 @@ CREATE TABLE llx_opensurvey_user_studs ( nom VARCHAR(64) NOT NULL, id_sondage VARCHAR(16) NOT NULL, reponses VARCHAR(100) NOT NULL, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB; ALTER TABLE llx_opensurvey_sondage ADD COLUMN id_sondage_admin CHAR(24); @@ -367,7 +367,7 @@ UPDATE llx_extrafields SET elementtype='societe' WHERE elementtype='company'; create table llx_commande_fournisseur_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -376,7 +376,7 @@ ALTER TABLE llx_commande_fournisseur_extrafields ADD INDEX idx_commande_fourniss create table llx_facture_fourn_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/3.4.0-3.5.0.sql b/htdocs/install/mysql/migration/3.4.0-3.5.0.sql index c6dc0ff9bd7..af3ea13fa5c 100644 --- a/htdocs/install/mysql/migration/3.4.0-3.5.0.sql +++ b/htdocs/install/mysql/migration/3.4.0-3.5.0.sql @@ -43,7 +43,7 @@ ALTER TABLE llx_socpeople ADD COLUMN statut tinyint DEFAULT 1 NOT NULL AFTER imp create table llx_fichinter_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -55,7 +55,7 @@ ALTER TABLE llx_product ADD COLUMN desiredstock integer DEFAULT 0; create table llx_commandedet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) )ENGINE=innodb; @@ -69,7 +69,7 @@ ALTER TABLE llx_facturedet_rec ADD COLUMN info_bits integer DEFAULT 0 after tota create table llx_facturedet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -79,7 +79,7 @@ ALTER TABLE llx_facturedet_extrafields ADD INDEX idx_facturedet_extrafields (fk_ create table llx_propaldet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -314,7 +314,7 @@ INSERT INTO llx_c_departements ( code_departement, fk_region, cheflieu, tncc, nc -- Add ref_ext on bordereau_cheque ALTER TABLE llx_bordereau_cheque ADD ref_ext VARCHAR(255); -ALTER TABLE llx_bordereau_cheque ADD tms timestamp; +ALTER TABLE llx_bordereau_cheque ADD tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; -- Task 1011 @@ -337,7 +337,7 @@ ALTER TABLE llx_contratdet ADD column product_type integer DEFAULT 1 after total create table llx_contrat_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/3.5.0-3.6.0.sql b/htdocs/install/mysql/migration/3.5.0-3.6.0.sql index 5727b946bcb..32ed4c32538 100644 --- a/htdocs/install/mysql/migration/3.5.0-3.6.0.sql +++ b/htdocs/install/mysql/migration/3.5.0-3.6.0.sql @@ -74,7 +74,7 @@ ALTER TABLE llx_bookmark MODIFY COLUMN url varchar(255) NOT NULL; -- VMYSQL4.3 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN date_fin DATETIME NULL DEFAULT NULL; -- VPGSQL8.2 ALTER TABLE llx_opensurvey_sondage ALTER COLUMN date_fin DROP NOT NULL; --- VMYSQL4.1 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP; +-- VMYSQL4.1 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_opensurvey_sondage ADD COLUMN entity integer DEFAULT 1 NOT NULL; @@ -108,7 +108,7 @@ create table llx_product_customer_price rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer NOT NULL, fk_soc integer NOT NULL, price double(24,8) DEFAULT 0, @@ -164,7 +164,7 @@ ALTER TABLE llx_product ADD COLUMN tobatch tinyint DEFAULT 0 NOT NULL; CREATE TABLE llx_product_batch ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product_stock integer NOT NULL, eatby datetime DEFAULT NULL, sellby datetime DEFAULT NULL, @@ -187,7 +187,7 @@ CREATE TABLE llx_expeditiondet_batch ( --DROP TABLE llx_payment_salary CREATE TABLE llx_payment_salary ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user integer NOT NULL, datep date, datev date, @@ -229,7 +229,7 @@ ALTER TABLE llx_projet_task_time ADD thm double(24,8) AFTER fk_user; create table llx_categories_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -283,7 +283,7 @@ CREATE TABLE llx_resource fk_code_type_resource varchar(32), note_public text, note_private text, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; ALTER TABLE llx_resource ADD INDEX fk_code_type_resource_idx (fk_code_type_resource); @@ -298,7 +298,7 @@ CREATE TABLE llx_element_resources busy integer, mandatory integer, fk_user_create integer, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; ALTER TABLE llx_element_resources ADD UNIQUE INDEX idx_element_resources_idx1 (resource_id, resource_type, element_id, element_type); diff --git a/htdocs/install/mysql/migration/3.6.0-3.7.0.sql b/htdocs/install/mysql/migration/3.6.0-3.7.0.sql index 6dc2521ca5d..640f22e4bee 100644 --- a/htdocs/install/mysql/migration/3.6.0-3.7.0.sql +++ b/htdocs/install/mysql/migration/3.6.0-3.7.0.sql @@ -137,7 +137,7 @@ DROP TABLE llx_compta_compte_generaux; -- Align size for accounting account ALTER TABLE llx_accountingaccount MODIFY COLUMN account_number varchar(32); ALTER TABLE llx_accountingaccount MODIFY COLUMN account_parent varchar(32); -ALTER TABLE llx_accountingaccount add column tms timestamp AFTER datec; +ALTER TABLE llx_accountingaccount add column tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER datec; ALTER TABLE llx_accountingdebcred MODIFY COLUMN account_number varchar(32); ALTER TABLE llx_bank_account MODIFY COLUMN account_number varchar(32); ALTER TABLE llx_c_chargesociales MODIFY COLUMN accountancy_code varchar(32); @@ -233,7 +233,7 @@ create table llx_accounting_fiscalyear statut tinyint DEFAULT 0 NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_author integer NULL, fk_user_modif integer NULL )ENGINE=innodb; @@ -1050,7 +1050,7 @@ create table llx_c_email_templates private smallint DEFAULT 0 NOT NULL, -- Template public or private fk_user integer, -- Id utilisateur si modele prive, sinon null datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(255), -- Label of predefined email position smallint, -- Position active tinyint DEFAULT 1 NOT NULL, @@ -1112,7 +1112,7 @@ ALTER TABLE llx_projet_task MODIFY COLUMN planned_workload real DEFAULT 0 NULL; CREATE TABLE llx_fichinterdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -1121,7 +1121,7 @@ ALTER TABLE llx_fichinterdet_extrafields ADD INDEX idx_ficheinterdet_extrafields CREATE TABLE llx_usergroup_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql index ca677fc5224..00bf30f6672 100644 --- a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql +++ b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql @@ -49,7 +49,7 @@ create table llx_loan rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(80) NOT NULL, fk_bank integer, capital real DEFAULT 0 NOT NULL, @@ -75,7 +75,7 @@ create table llx_payment_loan rowid integer AUTO_INCREMENT PRIMARY KEY, fk_loan integer, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, amount_capital real DEFAULT 0, amount_insurance real DEFAULT 0, @@ -145,7 +145,7 @@ ALTER TABLE llx_product ADD COLUMN lifo double(24,8) AFTER fifo; CREATE TABLE llx_printing ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, printer_name text NOT NULL, printer_location text NOT NULL, @@ -177,7 +177,7 @@ DELETE from llx_const where name = 'MAIN_USE_JQUERY_MULTISELECT' and value = '1' create table llx_bank_account_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -198,7 +198,7 @@ ALTER TABLE llx_bank_account_extrafields ADD INDEX idx_bank_account_extrafields create table llx_contratdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -210,7 +210,7 @@ ALTER TABLE llx_product_fournisseur_price ADD COLUMN delivery_time_days integer; ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN comment varchar(255); ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN status integer; -ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN tms timestamp; +ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN batch varchar(30) DEFAULT NULL; ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN eatby date DEFAULT NULL; ALTER TABLE llx_commande_fournisseur_dispatch ADD COLUMN sellby date DEFAULT NULL; @@ -240,7 +240,7 @@ CREATE TABLE llx_expensereport ( date_approve datetime, date_refuse datetime, date_cancel datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_author integer NOT NULL, fk_user_modif integer DEFAULT NULL, fk_user_valid integer DEFAULT NULL, @@ -297,7 +297,7 @@ create table llx_payment_expensereport rowid integer AUTO_INCREMENT PRIMARY KEY, fk_expensereport integer, datec datetime, -- date de creation - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount real DEFAULT 0, fk_typepayment integer NOT NULL, @@ -316,7 +316,7 @@ ALTER TABLE llx_societe ADD COLUMN name_alias varchar(128) NULL; create table llx_commande_fournisseurdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -327,7 +327,7 @@ ALTER TABLE llx_commande_fournisseurdet_extrafields ADD INDEX idx_commande_fourn create table llx_facture_fourn_det_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -357,7 +357,7 @@ CREATE TABLE llx_askpricesupplier ( ref_int varchar(255) DEFAULT NULL, fk_soc integer DEFAULT NULL, fk_projet integer DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime DEFAULT NULL, date_valid datetime DEFAULT NULL, date_cloture datetime DEFAULT NULL, @@ -422,14 +422,14 @@ CREATE TABLE llx_askpricesupplierdet ( CREATE TABLE llx_askpricesupplier_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) DEFAULT NULL ) ENGINE=innodb; CREATE TABLE llx_askpricesupplierdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) DEFAULT NULL ) ENGINE=innodb; @@ -491,7 +491,7 @@ ALTER TABLE llx_don CHANGE COLUMN fk_project fk_projet integer NULL; create table llx_don_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -503,7 +503,7 @@ create table llx_payment_donation rowid integer AUTO_INCREMENT PRIMARY KEY, fk_donation integer, datec datetime, -- date de creation - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount real DEFAULT 0, fk_typepayment integer NOT NULL, @@ -585,7 +585,7 @@ CREATE TABLE IF NOT EXISTS llx_propal_merge_pdf_product ( fk_user_author integer DEFAULT NULL, fk_user_mod integer NOT NULL, datec datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14) DEFAULT NULL ) ENGINE=InnoDB; diff --git a/htdocs/install/mysql/migration/3.8.0-3.9.0.sql b/htdocs/install/mysql/migration/3.8.0-3.9.0.sql index f749e57b432..363288708d4 100644 --- a/htdocs/install/mysql/migration/3.8.0-3.9.0.sql +++ b/htdocs/install/mysql/migration/3.8.0-3.9.0.sql @@ -146,7 +146,7 @@ CREATE TABLE llx_ecm_files cover text, -- is this file a file to use for a cover extraparams varchar(255), -- for stock other parameters with json format date_c datetime, - date_m timestamp, + date_m timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_c integer, fk_user_m integer, acl text -- for future permission 'per file' @@ -227,7 +227,7 @@ CREATE TABLE IF NOT EXISTS llx_establishment ( fk_user_author integer NOT NULL, fk_user_mod integer NOT NULL, datec datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, status smallint DEFAULT 1 ) ENGINE=InnoDB; @@ -236,7 +236,7 @@ CREATE TABLE IF NOT EXISTS llx_user_rib ( fk_user integer NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(30), bank varchar(255), -- bank name code_banque varchar(128), -- bank code @@ -263,7 +263,7 @@ create table llx_stock_lotserial eatby date DEFAULT NULL, -- Eatby date sellby date DEFAULT NULL, -- Sellby date datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer @@ -282,7 +282,7 @@ create table llx_budget date_start date, date_end date, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer @@ -296,7 +296,7 @@ create table llx_budget_lines fk_project_ids varchar(255) NOT NULL, -- List of project ids related to this budget. If budget is dedicated to projects not yet started, we recommand to create a project 'Projects to come'. amount double(24,8) NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer @@ -369,7 +369,7 @@ create table llx_categorie_project create table llx_expedition_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -379,7 +379,7 @@ ALTER TABLE llx_expedition_extrafields ADD INDEX idx_expedition_extrafields (fk_ create table llx_expeditiondet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -392,7 +392,7 @@ ALTER TABLE llx_expeditiondet_extrafields ADD INDEX idx_expeditiondet_extrafield create table llx_livraison_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -402,7 +402,7 @@ ALTER TABLE llx_livraison_extrafields ADD INDEX idx_livraison_extrafields (fk_ob create table llx_livraisondet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; @@ -595,7 +595,7 @@ insert into llx_c_chargesociales (id, libelle, deductible, active, code, fk_pays ALTER TABLE llx_accounting_bookkeeping MODIFY COLUMN doc_ref varchar(300) NOT NULL; -ALTER TABLE llx_holiday ADD COLUMN tms timestamp; +ALTER TABLE llx_holiday ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_holiday ADD COLUMN entity integer DEFAULT 1 NOT NULL; ALTER TABLE llx_holiday ADD INDEX idx_holiday_entity (entity); diff --git a/htdocs/install/mysql/migration/3.9.0-4.0.0.sql b/htdocs/install/mysql/migration/3.9.0-4.0.0.sql index 6ec4fc35f92..6bf230df12a 100644 --- a/htdocs/install/mysql/migration/3.9.0-4.0.0.sql +++ b/htdocs/install/mysql/migration/3.9.0-4.0.0.sql @@ -54,7 +54,7 @@ CREATE TABLE llx_product_lot ( eatby date DEFAULT NULL, -- Eatby date sellby date DEFAULT NULL, -- Sellby date datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer @@ -140,7 +140,7 @@ CREATE TABLE llx_website fk_default_home integer, date_creation datetime, date_modification datetime, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; ALTER TABLE llx_website ADD COLUMN fk_default_home integer; ALTER TABLE llx_website CHANGE COLUMN shortname ref varchar(24) NOT NULL; @@ -158,7 +158,7 @@ CREATE TABLE llx_website_page status integer, date_creation datetime, date_modification datetime, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; ALTER TABLE llx_website_page ADD UNIQUE INDEX uk_website_page_url (fk_website,pageurl); @@ -475,7 +475,7 @@ CREATE TABLE llx_advtargetemailing fk_user_author integer NOT NULL, datec datetime NOT NULL, fk_user_mod integer NOT NULL, - tms timestamp NOT NULL + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=InnoDB; ALTER TABLE llx_advtargetemailing ADD UNIQUE INDEX uk_advtargetemailing_name (name); diff --git a/htdocs/install/mysql/migration/4.0.0-5.0.0.sql b/htdocs/install/mysql/migration/4.0.0-5.0.0.sql index 175e03ec179..7578c633be4 100644 --- a/htdocs/install/mysql/migration/4.0.0-5.0.0.sql +++ b/htdocs/install/mysql/migration/4.0.0-5.0.0.sql @@ -114,7 +114,7 @@ ALTER TABLE llx_societe_remise ADD COLUMN entity integer DEFAULT 1 NOT NULL afte create table llx_expensereport_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -133,7 +133,7 @@ UPDATE llx_adherent_type SET subscription = '1' WHERE subscription = 'yes'; CREATE TABLE llx_product_lot_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -145,7 +145,7 @@ ALTER TABLE llx_website_page MODIFY COLUMN content MEDIUMTEXT; CREATE TABLE llx_product_warehouse_properties ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer NOT NULL, fk_entrepot integer NOT NULL, seuil_stock_alerte integer DEFAULT 0, @@ -156,7 +156,7 @@ CREATE TABLE llx_product_warehouse_properties ALTER TABLE llx_accounting_bookkeeping ADD COLUMN entity integer DEFAULT 1 NOT NULL; ALTER TABLE llx_accounting_bookkeeping ADD COLUMN fk_user_modif integer; ALTER TABLE llx_accounting_bookkeeping ADD COLUMN date_creation datetime; -ALTER TABLE llx_accounting_bookkeeping ADD COLUMN tms timestamp; +ALTER TABLE llx_accounting_bookkeeping ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; -- VMYSQL4.3 ALTER TABLE llx_accounting_bookkeeping MODIFY COLUMN numero_compte varchar(32) NOT NULL; -- VMYSQL4.3 ALTER TABLE llx_accounting_bookkeeping MODIFY COLUMN code_journal varchar(32) NOT NULL; -- VPGSQL8.2 ALTER TABLE llx_accounting_bookkeeping ALTER COLUMN numero_compte SET NOT NULL; @@ -186,7 +186,7 @@ ALTER TABLE llx_entrepot ADD COLUMN fk_parent integer DEFAULT 0; create table llx_resource_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -222,7 +222,7 @@ create table llx_user_employment ref_ext varchar(50), -- reference into an external system (not used by dolibarr) fk_user integer, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, job varchar(128), -- job position. may be a dictionary diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index b53b25f93b1..87eda0668b1 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -61,7 +61,7 @@ ALTER TABLE llx_supplier_proposaldet CHANGE COLUMN fk_askpricesupplier fk_suppli -- VMYSQL4.3 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN date_fin DATETIME NULL DEFAULT NULL; -- VPGSQL8.2 ALTER TABLE llx_opensurvey_sondage ALTER COLUMN date_fin DROP NOT NULL; --- VMYSQL4.1 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP; +-- VMYSQL4.1 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_opensurvey_sondage ADD COLUMN fk_user_creat integer NOT NULL DEFAULT 0; ALTER TABLE llx_opensurvey_sondage ADD COLUMN status integer DEFAULT 1 after date_fin; @@ -160,7 +160,7 @@ ALTER TABLE llx_projet ADD COLUMN fk_user_modif integer; ALTER TABLE llx_projet_task ADD COLUMN fk_user_modif integer; ALTER TABLE llx_projet_task_time ADD COLUMN datec date; -ALTER TABLE llx_projet_task_time ADD COLUMN tms timestamp; +ALTER TABLE llx_projet_task_time ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_product_price ADD COLUMN fk_multicurrency integer; ALTER TABLE llx_product_price ADD COLUMN multicurrency_code varchar(255); @@ -171,12 +171,12 @@ ALTER TABLE llx_product_price ADD COLUMN multicurrency_price_ttc double(24,8) DE ALTER TABLE llx_product_price_by_qty ADD COLUMN fk_user_creat integer; ALTER TABLE llx_product_price_by_qty ADD COLUMN fk_user_modif integer; ALTER TABLE llx_product_price_by_qty DROP COLUMN date_price; -ALTER TABLE llx_product_price_by_qty ADD COLUMN tms timestamp; +ALTER TABLE llx_product_price_by_qty ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_product_price_by_qty ADD COLUMN import_key varchar(14); ALTER TABLE llx_user ADD COLUMN import_key varchar(14); -ALTER TABLE llx_facture_rec ADD COLUMN tms timestamp; +ALTER TABLE llx_facture_rec ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; UPDATE llx_facture_rec SET tms = datec where tms < '2000-01-01'; CREATE TABLE llx_product_attribute @@ -295,7 +295,7 @@ CREATE TABLE llx_accounting_bookkeeping_tmp fk_user_author integer NOT NULL, -- | user creating fk_user_modif integer, -- | user making last change date_creation datetime, -- FEC:EcritureDate | creation date - tms timestamp, -- | date last modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- | date last modification import_key varchar(14), code_journal varchar(32) NOT NULL, -- FEC:JournalCode journal_label varchar(255), -- FEC:JournalLib @@ -391,7 +391,7 @@ ALTER TABLE llx_contratdet ADD COLUMN vat_src_code varchar(10) DEFAULT ''; CREATE TABLE llx_payment_various ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, datep date, datev date, @@ -438,7 +438,7 @@ rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 0, ref varchar(48), datec datetime DEFAULT NULL, -tms timestamp, +tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_author integer, fk_user_modif integer, fk_user_valid integer, @@ -453,7 +453,7 @@ CREATE TABLE llx_inventorydet ( rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, -tms timestamp, +tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_inventory integer DEFAULT 0, fk_warehouse integer DEFAULT 0, fk_product integer DEFAULT 0, @@ -467,7 +467,7 @@ new_pmp double DEFAULT 0 )ENGINE=InnoDB; ALTER TABLE llx_inventory ADD COLUMN datec datetime DEFAULT NULL; -ALTER TABLE llx_inventory ADD COLUMN tms timestamp; +ALTER TABLE llx_inventory ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; ALTER TABLE llx_inventory ADD INDEX idx_inventory_tms (tms); ALTER TABLE llx_inventory ADD INDEX idx_inventory_datec (datec); @@ -502,7 +502,7 @@ CREATE TABLE llx_loan_schedule rowid integer AUTO_INCREMENT PRIMARY KEY, fk_loan integer, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, amount_capital real DEFAULT 0, amount_insurance real DEFAULT 0, @@ -547,7 +547,7 @@ CREATE TABLE llx_website_page fk_user_create integer, fk_user_modif integer, date_creation datetime, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; ALTER TABLE llx_website_page ADD UNIQUE INDEX uk_website_page_url (fk_website,pageurl); @@ -566,7 +566,7 @@ UPDATE llx_extrafields set elementtype='categorie' where elementtype='categories CREATE TABLE llx_blockedlog ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, action varchar(50), amounts real NOT NULL, signature varchar(100) NOT NULL, @@ -593,7 +593,7 @@ CREATE TABLE llx_blockedlog_authority rowid integer AUTO_INCREMENT PRIMARY KEY, blockchain longtext NOT NULL, signature varchar(100) NOT NULL, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; ALTER TABLE llx_blockedlog_authority ADD INDEX signature (signature); @@ -613,7 +613,7 @@ ALTER TABLE llx_mailing_cibles MODIFY COLUMN source_url varchar(255); CREATE TABLE llx_facture_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -623,7 +623,7 @@ ALTER TABLE llx_facture_rec_extrafields ADD INDEX idx_facture_rec_extrafields (f CREATE TABLE llx_facturedet_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/6.0.0-7.0.0.sql b/htdocs/install/mysql/migration/6.0.0-7.0.0.sql index ff6a1fe03fb..93a7a447c18 100644 --- a/htdocs/install/mysql/migration/6.0.0-7.0.0.sql +++ b/htdocs/install/mysql/migration/6.0.0-7.0.0.sql @@ -265,7 +265,7 @@ ALTER TABLE llx_menu MODIFY fk_leftmenu varchar(100); CREATE TABLE llx_website_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -285,7 +285,7 @@ CREATE TABLE llx_website_account( date_last_login datetime, date_previous_login datetime, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), @@ -307,7 +307,7 @@ ALTER TABLE llx_website_account ADD CONSTRAINT llx_website_account_fk_website FO CREATE TABLE llx_website_account_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -326,7 +326,7 @@ alter table llx_user add column pass_encoding varchar(24) NULL; CREATE TABLE IF NOT EXISTS llx_expensereport_ik ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_c_exp_tax_cat integer DEFAULT 0 NOT NULL, fk_range integer DEFAULT 0 NOT NULL, coef double DEFAULT 0 NOT NULL, @@ -441,7 +441,7 @@ INSERT INTO llx_c_exp_tax_range (rowid,fk_c_exp_tax_cat,range_ik, entity, active CREATE TABLE llx_expensereport_rules ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, dates datetime NOT NULL, datee datetime NOT NULL, amount numeric(24,8) NOT NULL, @@ -464,7 +464,7 @@ ALTER TABLE llx_extrafields ADD COLUMN fk_user_author integer; ALTER TABLE llx_extrafields ADD COLUMN fk_user_modif integer; ALTER TABLE llx_extrafields ADD COLUMN datec datetime; ALTER TABLE llx_extrafields ADD COLUMN enabled varchar(255) DEFAULT '1'; -ALTER TABLE llx_extrafields ADD COLUMN tms timestamp; +ALTER TABLE llx_extrafields ADD COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP; -- We fix value of 'list' from 0 to 1 for all extrafields created before this migration --VMYSQL4.1 UPDATE llx_extrafields SET list = 1 WHERE list = 0 AND fk_user_author IS NULL and fk_user_modif IS NULL and datec IS NULL; @@ -528,7 +528,7 @@ DROP TABLE llx_projet_task_comment; CREATE TABLE llx_comment ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, description text NOT NULL, fk_user_author integer DEFAULT NULL, fk_element integer DEFAULT NULL, @@ -572,7 +572,7 @@ create table llx_c_email_senderprofile entity integer DEFAULT 1 NOT NULL, -- multi company id private smallint DEFAULT 0 NOT NULL, -- Template public or private date_creation datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(255), -- Label of predefined email email varchar(255), -- Email signature text, -- Predefined signature @@ -655,7 +655,7 @@ create table llx_onlinesignature object_type varchar(32) NOT NULL, object_id integer NOT NULL, datec datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, name varchar(255) NOT NULL, ip varchar(128), pathoffile varchar(255) @@ -709,7 +709,7 @@ ALTER TABLE llx_resource ADD CONSTRAINT fk_resource_fk_country FOREIGN KEY (fk_c create table llx_facture_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql index 380c64c28fc..888f4fefdd0 100644 --- a/htdocs/install/mysql/migration/7.0.0-8.0.0.sql +++ b/htdocs/install/mysql/migration/7.0.0-8.0.0.sql @@ -149,7 +149,7 @@ CREATE TABLE llx_societe_remise_supplier rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- creation date fk_user_author integer, -- creation user remise_supplier double(6,3) DEFAULT 0 NOT NULL, -- discount @@ -246,7 +246,7 @@ CREATE TABLE llx_ticket date_read datetime, date_close datetime, notify_tiers_at_create tinyint, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; ALTER TABLE llx_ticket ADD COLUMN notify_tiers_at_create integer; @@ -271,7 +271,7 @@ ALTER TABLE llx_ticket_msg ADD CONSTRAINT fk_ticket_msg_fk_track_id FOREIGN KEY CREATE TABLE llx_ticket_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) )ENGINE=innodb; @@ -279,7 +279,7 @@ CREATE TABLE llx_ticket_extrafields create table llx_facture_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -371,7 +371,7 @@ CREATE TABLE llx_societe_account( date_last_login datetime, date_previous_login datetime, date_creation datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), @@ -433,7 +433,7 @@ CREATE TABLE llx_asset( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), @@ -449,7 +449,7 @@ ALTER TABLE llx_asset ADD INDEX idx_asset_fk_asset_type (fk_asset_type); create table llx_asset_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -458,7 +458,7 @@ create table llx_asset_type ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(50) NOT NULL, accountancy_code_asset varchar(32), accountancy_code_depreciation_asset varchar(32), @@ -473,7 +473,7 @@ ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_asset_type FOREIGN KEY (fk_asset_t create table llx_asset_type_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/migration/8.0.0-9.0.0.sql b/htdocs/install/mysql/migration/8.0.0-9.0.0.sql index b7fe131c3f9..36a15d5b85d 100644 --- a/htdocs/install/mysql/migration/8.0.0-9.0.0.sql +++ b/htdocs/install/mysql/migration/8.0.0-9.0.0.sql @@ -43,7 +43,7 @@ ALTER TABLE llx_facture ADD COLUMN pos_source varchar(32); create table llx_facture_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; @@ -182,7 +182,7 @@ CREATE TABLE llx_emailcollector_emailcollector( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), @@ -202,7 +202,7 @@ CREATE TABLE llx_emailcollector_emailcollectorfilter( type varchar(128) NOT NULL, rulevalue varchar(128) NULL, date_creation datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), @@ -217,7 +217,7 @@ CREATE TABLE llx_emailcollector_emailcollectoraction( type varchar(128) NOT NULL, actionparam varchar(255) NULL, date_creation datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, position integer DEFAULT 0, diff --git a/htdocs/install/mysql/migration/9.0.0-10.0.0.sql b/htdocs/install/mysql/migration/9.0.0-10.0.0.sql index a56cb45e4fe..b9a406515ec 100644 --- a/htdocs/install/mysql/migration/9.0.0-10.0.0.sql +++ b/htdocs/install/mysql/migration/9.0.0-10.0.0.sql @@ -87,7 +87,7 @@ create table llx_mailing_unsubscribe unsubscribegroup varchar(128) DEFAULT '', ip varchar(128), date_creat datetime, -- creation date - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; ALTER TABLE llx_mailing_unsubscribe ADD UNIQUE uk_mailing_unsubscribe(email, entity, unsubscribegroup); @@ -223,7 +223,7 @@ CREATE TABLE llx_bom_bom( qty double(24,8), efficiency double(8,4), date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, date_valid datetime, fk_user_creat integer NOT NULL, fk_user_modif integer, @@ -240,7 +240,7 @@ ALTER TABLE llx_bom_bom ADD COLUMN date_valid datetime; create table llx_bom_bom_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -266,7 +266,7 @@ ALTER TABLE llx_bom_bomline ADD COLUMN position integer NOT NULL; create table llx_bom_bomline_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; @@ -335,7 +335,7 @@ UPDATE llx_c_shipment_mode SET label = 'https://www.laposte.fr/outils/suivre-vos create table llx_reception ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ref varchar(30) NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, @@ -383,7 +383,7 @@ ALTER TABLE llx_reception ADD INDEX idx_reception_fk_shipping_method (fk_shippin create table llx_reception_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_accounting_account.sql b/htdocs/install/mysql/tables/llx_accounting_account.sql index 7af83585c7f..893cb19d9ab 100644 --- a/htdocs/install/mysql/tables/llx_accounting_account.sql +++ b/htdocs/install/mysql/tables/llx_accounting_account.sql @@ -24,7 +24,7 @@ create table llx_accounting_account rowid bigint AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_pcg_version varchar(32) NOT NULL, -- Chart system pcg_type varchar(20) NOT NULL, -- First part of Key for predefined groups account_number varchar(32) NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql index cf1c3334092..23e7d489e09 100644 --- a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql +++ b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql @@ -45,7 +45,7 @@ CREATE TABLE llx_accounting_bookkeeping fk_user_author integer NOT NULL, -- | user creating fk_user_modif integer, -- | user making last change date_creation datetime, -- FEC:EcritureDate | creation date - tms timestamp, -- | date last modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- | last modification date fk_user integer NULL, -- The id of user that validate the accounting source document code_journal varchar(32) NOT NULL, -- FEC:JournalCode journal_label varchar(255), -- FEC:JournalLib diff --git a/htdocs/install/mysql/tables/llx_accounting_bookkeeping_tmp.sql b/htdocs/install/mysql/tables/llx_accounting_bookkeeping_tmp.sql index cbf387b9b70..2b8277c70bd 100644 --- a/htdocs/install/mysql/tables/llx_accounting_bookkeeping_tmp.sql +++ b/htdocs/install/mysql/tables/llx_accounting_bookkeeping_tmp.sql @@ -44,7 +44,7 @@ CREATE TABLE llx_accounting_bookkeeping_tmp fk_user_author integer NOT NULL, -- | user creating fk_user_modif integer, -- | user making last change date_creation datetime, -- FEC:EcritureDate | creation date - tms timestamp, -- | date last modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- | last modification date fk_user integer NULL, -- The id of user that validate the accounting source document code_journal varchar(32) NOT NULL, -- FEC:JournalCode journal_label varchar(255), -- FEC:JournalLib diff --git a/htdocs/install/mysql/tables/llx_accounting_fiscalyear.sql b/htdocs/install/mysql/tables/llx_accounting_fiscalyear.sql index 90590fb427d..17e9d9dccfb 100644 --- a/htdocs/install/mysql/tables/llx_accounting_fiscalyear.sql +++ b/htdocs/install/mysql/tables/llx_accounting_fiscalyear.sql @@ -25,7 +25,7 @@ create table llx_accounting_fiscalyear statut tinyint DEFAULT 0 NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_author integer DEFAULT NULL, fk_user_modif integer DEFAULT NULL )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_actioncomm.sql b/htdocs/install/mysql/tables/llx_actioncomm.sql index 857e6270b90..82d97d3ec98 100644 --- a/htdocs/install/mysql/tables/llx_actioncomm.sql +++ b/htdocs/install/mysql/tables/llx_actioncomm.sql @@ -33,7 +33,7 @@ create table llx_actioncomm code varchar(50) NULL, -- code of action for automatic action ('AC_OTH_AUTO' for automatic actions, 'AC_EMAILIN_AUTO' for email input, 'AC_xxx' for manual action...) datec datetime, -- date creation - tms timestamp, -- date modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date fk_user_author integer, -- user id of user that has created record fk_user_mod integer, -- user id of user that has modified record diff --git a/htdocs/install/mysql/tables/llx_actioncomm_extrafields.sql b/htdocs/install/mysql/tables/llx_actioncomm_extrafields.sql index c820feac430..95a415116ab 100644 --- a/htdocs/install/mysql/tables/llx_actioncomm_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_actioncomm_extrafields.sql @@ -19,7 +19,7 @@ create table llx_actioncomm_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_adherent.sql b/htdocs/install/mysql/tables/llx_adherent.sql index 1917e80c81a..6b5490b282d 100644 --- a/htdocs/install/mysql/tables/llx_adherent.sql +++ b/htdocs/install/mysql/tables/llx_adherent.sql @@ -72,7 +72,7 @@ create table llx_adherent model_pdf varchar(255), datevalid datetime, -- date de validation datec datetime, -- date de creation - tms timestamp, -- date de modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date fk_user_author integer, -- can be null because member can be create by a guest fk_user_mod integer, fk_user_valid integer, diff --git a/htdocs/install/mysql/tables/llx_adherent_extrafields.sql b/htdocs/install/mysql/tables/llx_adherent_extrafields.sql index 50f47c7954b..6b67944a321 100644 --- a/htdocs/install/mysql/tables/llx_adherent_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_adherent_extrafields.sql @@ -21,7 +21,7 @@ create table llx_adherent_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- member id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_adherent_type.sql b/htdocs/install/mysql/tables/llx_adherent_type.sql index 7e9270b89dc..bdce18ef0bc 100644 --- a/htdocs/install/mysql/tables/llx_adherent_type.sql +++ b/htdocs/install/mysql/tables/llx_adherent_type.sql @@ -26,7 +26,7 @@ create table llx_adherent_type ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, statut smallint NOT NULL DEFAULT 0, libelle varchar(50) NOT NULL, morphy varchar(3) NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_adherent_type_extrafields.sql b/htdocs/install/mysql/tables/llx_adherent_type_extrafields.sql index 2950147730b..d13056a2894 100644 --- a/htdocs/install/mysql/tables/llx_adherent_type_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_adherent_type_extrafields.sql @@ -19,7 +19,7 @@ create table llx_adherent_type_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_advtargetemailing.sql b/htdocs/install/mysql/tables/llx_advtargetemailing.sql index 22d49768887..34bd7eb53bf 100644 --- a/htdocs/install/mysql/tables/llx_advtargetemailing.sql +++ b/htdocs/install/mysql/tables/llx_advtargetemailing.sql @@ -28,5 +28,5 @@ CREATE TABLE llx_advtargetemailing fk_user_author integer NOT NULL, datec datetime NOT NULL, fk_user_mod integer NOT NULL, - tms timestamp NOT NULL + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_asset.sql b/htdocs/install/mysql/tables/llx_asset.sql index b5bb1d1bfe2..52eeda3ba58 100644 --- a/htdocs/install/mysql/tables/llx_asset.sql +++ b/htdocs/install/mysql/tables/llx_asset.sql @@ -26,7 +26,7 @@ CREATE TABLE llx_asset( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), diff --git a/htdocs/install/mysql/tables/llx_asset_extrafields.sql b/htdocs/install/mysql/tables/llx_asset_extrafields.sql index 364f0e3d08f..c93fac7b20a 100644 --- a/htdocs/install/mysql/tables/llx_asset_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_asset_extrafields.sql @@ -16,7 +16,7 @@ create table llx_asset_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_asset_type.sql b/htdocs/install/mysql/tables/llx_asset_type.sql index bd1c300d087..1205acb959b 100644 --- a/htdocs/install/mysql/tables/llx_asset_type.sql +++ b/htdocs/install/mysql/tables/llx_asset_type.sql @@ -17,7 +17,7 @@ create table llx_asset_type ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(50) NOT NULL, accountancy_code_asset varchar(32), accountancy_code_depreciation_asset varchar(32), diff --git a/htdocs/install/mysql/tables/llx_asset_type_extrafields.sql b/htdocs/install/mysql/tables/llx_asset_type_extrafields.sql index 59ebe94c7d8..7ff09176216 100644 --- a/htdocs/install/mysql/tables/llx_asset_type_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_asset_type_extrafields.sql @@ -16,7 +16,7 @@ create table llx_asset_type_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_bank.sql b/htdocs/install/mysql/tables/llx_bank.sql index 8dfdba27baa..0e1dbc403da 100644 --- a/htdocs/install/mysql/tables/llx_bank.sql +++ b/htdocs/install/mysql/tables/llx_bank.sql @@ -21,7 +21,7 @@ create table llx_bank ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datev date, -- date de valeur dateo date, -- date operation amount double(24,8) NOT NULL default 0, diff --git a/htdocs/install/mysql/tables/llx_bank_account.sql b/htdocs/install/mysql/tables/llx_bank_account.sql index 28a1a0baf34..4ac90dd961d 100644 --- a/htdocs/install/mysql/tables/llx_bank_account.sql +++ b/htdocs/install/mysql/tables/llx_bank_account.sql @@ -26,7 +26,7 @@ create table llx_bank_account ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ref varchar(12) NOT NULL, label varchar(30) NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id diff --git a/htdocs/install/mysql/tables/llx_bank_account_extrafields.sql b/htdocs/install/mysql/tables/llx_bank_account_extrafields.sql index 5d9d8847154..a30e81ab96c 100644 --- a/htdocs/install/mysql/tables/llx_bank_account_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_bank_account_extrafields.sql @@ -19,7 +19,7 @@ create table llx_bank_account_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_blockedlog.sql b/htdocs/install/mysql/tables/llx_blockedlog.sql index 889b28d7a73..f8145718ea6 100644 --- a/htdocs/install/mysql/tables/llx_blockedlog.sql +++ b/htdocs/install/mysql/tables/llx_blockedlog.sql @@ -21,7 +21,7 @@ CREATE TABLE llx_blockedlog rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, date_creation datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, action varchar(50), amounts double(24,8) NOT NULL, element varchar(50), diff --git a/htdocs/install/mysql/tables/llx_blockedlog_authority.sql b/htdocs/install/mysql/tables/llx_blockedlog_authority.sql index 9e7dae8f23c..eb491f93af4 100644 --- a/htdocs/install/mysql/tables/llx_blockedlog_authority.sql +++ b/htdocs/install/mysql/tables/llx_blockedlog_authority.sql @@ -3,5 +3,5 @@ CREATE TABLE llx_blockedlog_authority rowid integer AUTO_INCREMENT PRIMARY KEY, blockchain longtext NOT NULL, signature varchar(100) NOT NULL, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_bom_bom.sql b/htdocs/install/mysql/tables/llx_bom_bom.sql index 45c5fce3485..01ec2e63a3e 100644 --- a/htdocs/install/mysql/tables/llx_bom_bom.sql +++ b/htdocs/install/mysql/tables/llx_bom_bom.sql @@ -31,7 +31,7 @@ CREATE TABLE llx_bom_bom( duration double(24,8) DEFAULT NULL, date_creation datetime NOT NULL, date_valid datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, fk_user_valid integer, diff --git a/htdocs/install/mysql/tables/llx_bom_bom_extrafields.sql b/htdocs/install/mysql/tables/llx_bom_bom_extrafields.sql index 10c44459a8b..15210546fda 100644 --- a/htdocs/install/mysql/tables/llx_bom_bom_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_bom_bom_extrafields.sql @@ -16,7 +16,7 @@ create table llx_bom_bom_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_bom_bomline_extrafields.sql b/htdocs/install/mysql/tables/llx_bom_bomline_extrafields.sql index 1b468da3a22..8ed3e96bd11 100644 --- a/htdocs/install/mysql/tables/llx_bom_bomline_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_bom_bomline_extrafields.sql @@ -16,7 +16,7 @@ create table llx_bom_bomline_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_bordereau_cheque.sql b/htdocs/install/mysql/tables/llx_bordereau_cheque.sql index 3050b831eec..9b1d6e24ad4 100644 --- a/htdocs/install/mysql/tables/llx_bordereau_cheque.sql +++ b/htdocs/install/mysql/tables/llx_bordereau_cheque.sql @@ -33,7 +33,7 @@ create table llx_bordereau_cheque fk_bank_account integer, fk_user_author integer, statut smallint NOT NULL DEFAULT 0, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, note text, entity integer DEFAULT 1 NOT NULL -- multi company id )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_boxes_def.sql b/htdocs/install/mysql/tables/llx_boxes_def.sql index 285bbc22603..fbdf0e3ed36 100644 --- a/htdocs/install/mysql/tables/llx_boxes_def.sql +++ b/htdocs/install/mysql/tables/llx_boxes_def.sql @@ -23,6 +23,6 @@ create table llx_boxes_def rowid integer AUTO_INCREMENT PRIMARY KEY, file varchar(200) NOT NULL, -- Do not increase this as file+note must be small to allow index entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, note varchar(130) -- Do not increase this as file+note must be small to allow index )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_budget.sql b/htdocs/install/mysql/tables/llx_budget.sql index d67e65e8f2b..ab9ed79a64a 100644 --- a/htdocs/install/mysql/tables/llx_budget.sql +++ b/htdocs/install/mysql/tables/llx_budget.sql @@ -26,7 +26,7 @@ create table llx_budget date_start date, date_end date, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer diff --git a/htdocs/install/mysql/tables/llx_budget_lines.sql b/htdocs/install/mysql/tables/llx_budget_lines.sql index 1397b604316..ffdf33aa38f 100644 --- a/htdocs/install/mysql/tables/llx_budget_lines.sql +++ b/htdocs/install/mysql/tables/llx_budget_lines.sql @@ -23,7 +23,7 @@ create table llx_budget_lines fk_project_ids varchar(180) NOT NULL, -- 'IDS:x,y' = List of project ids related to this budget. If budget is dedicated to projects not yet started, we recommand to create a project 'Projects to come'. 'FILTER:ref=*ABC' or 'FILTER:categid=123' = Can also be a dynamic rule to select projects. amount double(24,8) NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer diff --git a/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql b/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql index cd81eb4c42a..8b99059acdd 100644 --- a/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql +++ b/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql @@ -23,7 +23,7 @@ create table llx_c_email_senderprofile entity integer DEFAULT 1 NOT NULL, -- multi company id private smallint DEFAULT 0 NOT NULL, -- Template public (0) or private (id of user) date_creation datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(255), -- Label of predefined email email varchar(255) NOT NULL, -- Email signature text, -- Predefined signature diff --git a/htdocs/install/mysql/tables/llx_c_email_templates.sql b/htdocs/install/mysql/tables/llx_c_email_templates.sql index 3fd97fb2804..04130a208fe 100644 --- a/htdocs/install/mysql/tables/llx_c_email_templates.sql +++ b/htdocs/install/mysql/tables/llx_c_email_templates.sql @@ -27,7 +27,7 @@ create table llx_c_email_templates private smallint DEFAULT 0 NOT NULL, -- Template public or private fk_user integer, -- Id user owner if template is private, or null datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(180), -- Label of predefined email position smallint, -- Position enabled varchar(255) DEFAULT '1', -- Condition to have this module visible diff --git a/htdocs/install/mysql/tables/llx_c_field_list.sql b/htdocs/install/mysql/tables/llx_c_field_list.sql index c99bfe91690..9177228b363 100644 --- a/htdocs/install/mysql/tables/llx_c_field_list.sql +++ b/htdocs/install/mysql/tables/llx_c_field_list.sql @@ -24,7 +24,7 @@ create table llx_c_field_list ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, element varchar(64) NOT NULL, -- name of element list entity integer DEFAULT 1 NOT NULL, -- entity id name varchar(32) NOT NULL, -- name of field with table alias (ex: p.ref) diff --git a/htdocs/install/mysql/tables/llx_c_product_nature.key.sql b/htdocs/install/mysql/tables/llx_c_product_nature.key.sql new file mode 100644 index 00000000000..b6a3d2130bf --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_product_nature.key.sql @@ -0,0 +1 @@ +ALTER TABLE llx_c_product_nature ADD UNIQUE INDEX uk_c_product_nature(code, active); diff --git a/htdocs/install/mysql/tables/llx_c_product_nature.sql b/htdocs/install/mysql/tables/llx_c_product_nature.sql new file mode 100644 index 00000000000..3c467ce7cf8 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_product_nature.sql @@ -0,0 +1,24 @@ +-- ======================================================================== +-- Copyright (C) 2020 Florian HENRY +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- ======================================================================== + +CREATE TABLE llx_c_product_nature ( + rowid integer AUTO_INCREMENT PRIMARY KEY, + code tinyint NOT NULL, + label varchar(100), + active tinyint DEFAULT 1 NOT NULL +) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_c_shipment_mode.sql b/htdocs/install/mysql/tables/llx_c_shipment_mode.sql index 9adc6b3cb0c..6f49f682f24 100644 --- a/htdocs/install/mysql/tables/llx_c_shipment_mode.sql +++ b/htdocs/install/mysql/tables/llx_c_shipment_mode.sql @@ -20,7 +20,7 @@ create table llx_c_shipment_mode ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, code varchar(30) NOT NULL, libelle varchar(50) NOT NULL, description text, diff --git a/htdocs/install/mysql/tables/llx_c_transport_mode.key.sql b/htdocs/install/mysql/tables/llx_c_transport_mode.key.sql new file mode 100644 index 00000000000..4a7d5e89009 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_transport_mode.key.sql @@ -0,0 +1,19 @@ +-- =================================================================== +-- Copyright (C) 2019 Open-DSI +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- =================================================================== + +ALTER TABLE llx_c_transport_mode ADD UNIQUE INDEX uk_c_transport_mode (code, entity); \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_c_transport_mode.sql b/htdocs/install/mysql/tables/llx_c_transport_mode.sql new file mode 100644 index 00000000000..a2634f2a0bf --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_transport_mode.sql @@ -0,0 +1,26 @@ +-- ======================================================================== +-- Copyright (C) 2019 Open-DSI +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- ======================================================================== + +CREATE TABLE llx_c_transport_mode ( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + code varchar(3) NOT NULL, + label varchar(255) NOT NULL, + active tinyint DEFAULT 1 NOT NULL +) ENGINE=innodb; + diff --git a/htdocs/install/mysql/tables/llx_categorie.sql b/htdocs/install/mysql/tables/llx_categorie.sql index cf1df953ba5..29cb5a260e6 100644 --- a/htdocs/install/mysql/tables/llx_categorie.sql +++ b/htdocs/install/mysql/tables/llx_categorie.sql @@ -32,7 +32,7 @@ create table llx_categorie fk_soc integer DEFAULT NULL, -- not used by default. Used when option CATEGORY_ASSIGNED_TO_A_CUSTOMER is set. visible tinyint DEFAULT 1 NOT NULL, -- determine if the products are visible or not date_creation datetime, -- date creation - tms timestamp, -- date modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date fk_user_creat integer, -- user making creation fk_user_modif integer, -- user making last change import_key varchar(14) -- Import key diff --git a/htdocs/install/mysql/tables/llx_categories_extrafields.sql b/htdocs/install/mysql/tables/llx_categories_extrafields.sql index 8a2a82f7382..82c52f1b7ee 100644 --- a/htdocs/install/mysql/tables/llx_categories_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_categories_extrafields.sql @@ -19,7 +19,7 @@ create table llx_categories_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_chargesociales.sql b/htdocs/install/mysql/tables/llx_chargesociales.sql index 57434c93d98..db9e82ac779 100644 --- a/htdocs/install/mysql/tables/llx_chargesociales.sql +++ b/htdocs/install/mysql/tables/llx_chargesociales.sql @@ -25,7 +25,7 @@ create table llx_chargesociales date_ech datetime NOT NULL, -- date echeance libelle varchar(80) NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, date_creation datetime, -- date de creation date_valid datetime, -- date de validation fk_user_author integer, -- user making creation diff --git a/htdocs/install/mysql/tables/llx_commande.sql b/htdocs/install/mysql/tables/llx_commande.sql index aa237383452..add836ce5d5 100644 --- a/htdocs/install/mysql/tables/llx_commande.sql +++ b/htdocs/install/mysql/tables/llx_commande.sql @@ -32,7 +32,7 @@ create table llx_commande fk_soc integer NOT NULL, fk_projet integer DEFAULT NULL, -- projet auquel est rattache la commande - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, date_creation datetime, -- date de creation date_valid datetime, -- date de validation date_cloture datetime, -- date de cloture diff --git a/htdocs/install/mysql/tables/llx_commande_extrafields.sql b/htdocs/install/mysql/tables/llx_commande_extrafields.sql index e6f3f768489..922bcd820a1 100644 --- a/htdocs/install/mysql/tables/llx_commande_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_commande_extrafields.sql @@ -19,7 +19,7 @@ create table llx_commande_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur.sql index bc5cadea228..a9f155a2abb 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseur.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseur.sql @@ -32,7 +32,7 @@ create table llx_commande_fournisseur fk_soc integer NOT NULL, fk_projet integer DEFAULT 0, -- project id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, date_creation datetime, -- date de creation date_valid datetime, -- date de validation date_approve datetime, -- date de approve diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch.sql index 22a0e241dd6..b5f85fea250 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch.sql @@ -36,5 +36,5 @@ create table llx_commande_fournisseur_dispatch sellby date DEFAULT NULL, status integer, datec datetime, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch_extrafields.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch_extrafields.sql index c30cc1c75dd..2c85521ea84 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseur_dispatch_extrafields.sql @@ -19,7 +19,7 @@ create table llx_commande_fournisseur_dispatch_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur_extrafields.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur_extrafields.sql index 6f72a447f10..40c5785dbad 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseur_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseur_extrafields.sql @@ -23,7 +23,7 @@ create table llx_commande_fournisseur_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseur_log.sql b/htdocs/install/mysql/tables/llx_commande_fournisseur_log.sql index 4c576f16f51..c75e9718526 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseur_log.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseur_log.sql @@ -20,7 +20,7 @@ create table llx_commande_fournisseur_log ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datelog datetime NOT NULL, fk_commande integer NOT NULL, fk_statut smallint NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_commande_fournisseurdet_extrafields.sql b/htdocs/install/mysql/tables/llx_commande_fournisseurdet_extrafields.sql index 189b4d7d593..cc22da09720 100644 --- a/htdocs/install/mysql/tables/llx_commande_fournisseurdet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_commande_fournisseurdet_extrafields.sql @@ -24,7 +24,7 @@ create table llx_commande_fournisseurdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_commandedet_extrafields.sql b/htdocs/install/mysql/tables/llx_commandedet_extrafields.sql index 37b7dd6a349..331a3fbe54a 100644 --- a/htdocs/install/mysql/tables/llx_commandedet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_commandedet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_commandedet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_comment.sql b/htdocs/install/mysql/tables/llx_comment.sql index 22b2c40b9f1..3e839d83b4c 100644 --- a/htdocs/install/mysql/tables/llx_comment.sql +++ b/htdocs/install/mysql/tables/llx_comment.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_comment ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, description text NOT NULL, fk_user_author integer DEFAULT NULL, fk_user_modif integer DEFAULT NULL, diff --git a/htdocs/install/mysql/tables/llx_const.sql b/htdocs/install/mysql/tables/llx_const.sql index fcca5f57023..96594bb60b4 100644 --- a/htdocs/install/mysql/tables/llx_const.sql +++ b/htdocs/install/mysql/tables/llx_const.sql @@ -32,7 +32,7 @@ create table llx_const type varchar(64) DEFAULT 'string', -- null or 'encrypted' if param has been encrypted visible tinyint DEFAULT 1 NOT NULL, note text, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; -- diff --git a/htdocs/install/mysql/tables/llx_contrat.sql b/htdocs/install/mysql/tables/llx_contrat.sql index fbb36a5674b..dcdc1288d37 100644 --- a/htdocs/install/mysql/tables/llx_contrat.sql +++ b/htdocs/install/mysql/tables/llx_contrat.sql @@ -26,7 +26,7 @@ create table llx_contrat ref_supplier varchar(255), -- supplier contract ref ref_ext varchar(255), -- external contract ref entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- creation date date_contrat datetime, statut smallint DEFAULT 0, -- not used. deprecated diff --git a/htdocs/install/mysql/tables/llx_contrat_extrafields.sql b/htdocs/install/mysql/tables/llx_contrat_extrafields.sql index 7ab3dfbbdc9..f93ab94d4ca 100644 --- a/htdocs/install/mysql/tables/llx_contrat_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_contrat_extrafields.sql @@ -19,7 +19,7 @@ create table llx_contrat_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_contratdet.sql b/htdocs/install/mysql/tables/llx_contratdet.sql index 4705bbab218..bbe19955e33 100644 --- a/htdocs/install/mysql/tables/llx_contratdet.sql +++ b/htdocs/install/mysql/tables/llx_contratdet.sql @@ -20,7 +20,7 @@ create table llx_contratdet ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_contrat integer NOT NULL, fk_product integer NULL, -- doit pouvoir etre nul pour ligne detail sans produits @@ -53,7 +53,7 @@ create table llx_contratdet total_localtax1 double(24,8) DEFAULT 0, -- Total Local tax 1 de la ligne total_localtax2 double(24,8) DEFAULT 0, -- Total Local tax 2 de la ligne total_ttc double(24,8) DEFAULT 0, -- Total TTC de la ligne toute quantite et incluant remise ligne et globale - product_type integer DEFAULT 1, -- Product type (1=service by default) + product_type integer DEFAULT 1, -- Type of line (1=service by default) info_bits integer DEFAULT 0, -- TVA NPR ou non buy_price_ht double(24,8) DEFAULT NULL, -- buying price diff --git a/htdocs/install/mysql/tables/llx_contratdet_extrafields.sql b/htdocs/install/mysql/tables/llx_contratdet_extrafields.sql index 8933fa66e16..ccd0846e81e 100644 --- a/htdocs/install/mysql/tables/llx_contratdet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_contratdet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_contratdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_contratdet_log.sql b/htdocs/install/mysql/tables/llx_contratdet_log.sql index b13791f4832..f52ced561c7 100644 --- a/htdocs/install/mysql/tables/llx_contratdet_log.sql +++ b/htdocs/install/mysql/tables/llx_contratdet_log.sql @@ -19,7 +19,7 @@ create table llx_contratdet_log ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_contratdet integer NOT NULL, date datetime NOT NULL, statut smallint NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_cronjob.sql b/htdocs/install/mysql/tables/llx_cronjob.sql index 97057e6f41e..a9aa8960991 100644 --- a/htdocs/install/mysql/tables/llx_cronjob.sql +++ b/htdocs/install/mysql/tables/llx_cronjob.sql @@ -21,7 +21,7 @@ CREATE TABLE llx_cronjob ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, jobtype varchar(10) NOT NULL, label text NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_deplacement.sql b/htdocs/install/mysql/tables/llx_deplacement.sql index 8b9fa2a04ae..50bfe8d7cfd 100644 --- a/htdocs/install/mysql/tables/llx_deplacement.sql +++ b/htdocs/install/mysql/tables/llx_deplacement.sql @@ -24,7 +24,7 @@ create table llx_deplacement ref varchar(30) DEFAULT NULL, -- Ref donation (TODO change to NOT NULL) entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, dated datetime, fk_user integer NOT NULL, fk_user_author integer, diff --git a/htdocs/install/mysql/tables/llx_don.sql b/htdocs/install/mysql/tables/llx_don.sql index f03e82d6143..95181a3b30e 100644 --- a/htdocs/install/mysql/tables/llx_don.sql +++ b/htdocs/install/mysql/tables/llx_don.sql @@ -25,7 +25,7 @@ create table llx_don rowid integer AUTO_INCREMENT PRIMARY KEY, ref varchar(30) DEFAULT NULL, -- Ref donation (TODO change to NOT NULL) entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_statut smallint NOT NULL DEFAULT 0, -- Status of donation promise or validate datedon datetime, -- Date of the donation/promise amount double(24,8) DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_don_extrafields.sql b/htdocs/install/mysql/tables/llx_don_extrafields.sql index bf2b780fcee..a4a560d0f8a 100644 --- a/htdocs/install/mysql/tables/llx_don_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_don_extrafields.sql @@ -19,7 +19,7 @@ create table llx_don_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ecm_directories.sql b/htdocs/install/mysql/tables/llx_ecm_directories.sql index 1fa1467e296..a02a72118b2 100644 --- a/htdocs/install/mysql/tables/llx_ecm_directories.sql +++ b/htdocs/install/mysql/tables/llx_ecm_directories.sql @@ -30,7 +30,7 @@ CREATE TABLE llx_ecm_directories fullpath varchar(750), extraparams varchar(255), -- for stock other parameters with json format date_c datetime, - date_m timestamp, + date_m timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_c integer, fk_user_m integer, acl text diff --git a/htdocs/install/mysql/tables/llx_ecm_directories_extrafileds.sql b/htdocs/install/mysql/tables/llx_ecm_directories_extrafileds.sql index e2e496267ba..8bb7d98c592 100644 --- a/htdocs/install/mysql/tables/llx_ecm_directories_extrafileds.sql +++ b/htdocs/install/mysql/tables/llx_ecm_directories_extrafileds.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_ecm_directories_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ecm_files.sql b/htdocs/install/mysql/tables/llx_ecm_files.sql index c459e2ca219..030081b66b7 100644 --- a/htdocs/install/mysql/tables/llx_ecm_files.sql +++ b/htdocs/install/mysql/tables/llx_ecm_files.sql @@ -35,7 +35,7 @@ CREATE TABLE llx_ecm_files gen_or_uploaded varchar(12), -- 'generated' or 'uploaded' extraparams varchar(255), -- for stocking other parameters with json format date_c datetime, - date_m timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_c integer, fk_user_m integer, acl text -- for future permission 'per file' diff --git a/htdocs/install/mysql/tables/llx_ecm_files_extrafields.sql b/htdocs/install/mysql/tables/llx_ecm_files_extrafields.sql index 0cf0de6d375..485db3a0f72 100644 --- a/htdocs/install/mysql/tables/llx_ecm_files_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_ecm_files_extrafields.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_ecm_files_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_element_resources.sql b/htdocs/install/mysql/tables/llx_element_resources.sql index 95ee9b5a751..693a2f990f0 100644 --- a/htdocs/install/mysql/tables/llx_element_resources.sql +++ b/htdocs/install/mysql/tables/llx_element_resources.sql @@ -28,5 +28,5 @@ CREATE TABLE llx_element_resources mandatory integer, duree real, -- total duration of using ressource fk_user_create integer, - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_emailcollector_emailcollector.sql b/htdocs/install/mysql/tables/llx_emailcollector_emailcollector.sql index 87581f418e8..389093241ce 100644 --- a/htdocs/install/mysql/tables/llx_emailcollector_emailcollector.sql +++ b/htdocs/install/mysql/tables/llx_emailcollector_emailcollector.sql @@ -35,7 +35,7 @@ CREATE TABLE llx_emailcollector_emailcollector( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), diff --git a/htdocs/install/mysql/tables/llx_emailcollector_emailcollectoraction.sql b/htdocs/install/mysql/tables/llx_emailcollector_emailcollectoraction.sql index 226f74ce884..c45a3dcd1c4 100644 --- a/htdocs/install/mysql/tables/llx_emailcollector_emailcollectoraction.sql +++ b/htdocs/install/mysql/tables/llx_emailcollector_emailcollectoraction.sql @@ -21,7 +21,7 @@ CREATE TABLE llx_emailcollector_emailcollectoraction( type varchar(128) NOT NULL, actionparam varchar(255) NULL, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, position integer DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_emailcollector_emailcollectorfilter.sql b/htdocs/install/mysql/tables/llx_emailcollector_emailcollectorfilter.sql index 5f49227f655..4e708116e21 100644 --- a/htdocs/install/mysql/tables/llx_emailcollector_emailcollectorfilter.sql +++ b/htdocs/install/mysql/tables/llx_emailcollector_emailcollectorfilter.sql @@ -21,7 +21,7 @@ CREATE TABLE llx_emailcollector_emailcollectorfilter( type varchar(128) NOT NULL, rulevalue varchar(128) NULL, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), diff --git a/htdocs/install/mysql/tables/llx_entrepot.sql b/htdocs/install/mysql/tables/llx_entrepot.sql index 2cabb457016..2a390f008e2 100644 --- a/htdocs/install/mysql/tables/llx_entrepot.sql +++ b/htdocs/install/mysql/tables/llx_entrepot.sql @@ -23,7 +23,7 @@ create table llx_entrepot rowid integer AUTO_INCREMENT PRIMARY KEY, ref varchar(255) NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, entity integer DEFAULT 1 NOT NULL, -- multi company id description text, lieu varchar(64), -- resume lieu situation diff --git a/htdocs/install/mysql/tables/llx_entrepot_extrafields.sql b/htdocs/install/mysql/tables/llx_entrepot_extrafields.sql index 9fa75455f19..95a78b4ce6c 100644 --- a/htdocs/install/mysql/tables/llx_entrepot_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_entrepot_extrafields.sql @@ -19,7 +19,7 @@ create table llx_entrepot_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_establishment.sql b/htdocs/install/mysql/tables/llx_establishment.sql index 0d487e94e5f..7159a53059c 100644 --- a/htdocs/install/mysql/tables/llx_establishment.sql +++ b/htdocs/install/mysql/tables/llx_establishment.sql @@ -36,7 +36,7 @@ CREATE TABLE llx_establishment ( fk_user_author integer NOT NULL, fk_user_mod integer, datec datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL, status tinyint DEFAULT 1 ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_events.sql b/htdocs/install/mysql/tables/llx_events.sql index c3ae55f47e2..ffa4f1029e7 100644 --- a/htdocs/install/mysql/tables/llx_events.sql +++ b/htdocs/install/mysql/tables/llx_events.sql @@ -24,7 +24,7 @@ create table llx_events ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, -- date creation/modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date type varchar(32) NOT NULL, -- action type entity integer DEFAULT 1 NOT NULL, -- multi company id prefix_session varchar(255) NULL, -- prefix of session, obtained with dol_getprefix diff --git a/htdocs/install/mysql/tables/llx_expedition.sql b/htdocs/install/mysql/tables/llx_expedition.sql index e4c216f3da4..4214fef7f44 100644 --- a/htdocs/install/mysql/tables/llx_expedition.sql +++ b/htdocs/install/mysql/tables/llx_expedition.sql @@ -22,7 +22,7 @@ create table llx_expedition ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ref varchar(30) NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_expedition_extrafields.sql b/htdocs/install/mysql/tables/llx_expedition_extrafields.sql index af4228efb41..6b9721a2826 100644 --- a/htdocs/install/mysql/tables/llx_expedition_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_expedition_extrafields.sql @@ -19,7 +19,7 @@ create table llx_expedition_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_expeditiondet_extrafields.sql b/htdocs/install/mysql/tables/llx_expeditiondet_extrafields.sql index 112e41e9578..a71b45946a1 100644 --- a/htdocs/install/mysql/tables/llx_expeditiondet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_expeditiondet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_expeditiondet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_expensereport.sql b/htdocs/install/mysql/tables/llx_expensereport.sql index a212bc55273..772888620fb 100644 --- a/htdocs/install/mysql/tables/llx_expensereport.sql +++ b/htdocs/install/mysql/tables/llx_expensereport.sql @@ -34,8 +34,9 @@ CREATE TABLE llx_expensereport ( date_approve datetime, date_refuse datetime, date_cancel datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_author integer NOT NULL, -- not the user author but the user the expense report is for + fk_user_creat integer DEFAULT NULL, -- the use author fk_user_modif integer DEFAULT NULL, fk_user_valid integer DEFAULT NULL, fk_user_validator integer DEFAULT NULL, diff --git a/htdocs/install/mysql/tables/llx_expensereport_extrafields.sql b/htdocs/install/mysql/tables/llx_expensereport_extrafields.sql index 8b6ad4e998f..1e78afb8513 100644 --- a/htdocs/install/mysql/tables/llx_expensereport_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_expensereport_extrafields.sql @@ -19,7 +19,7 @@ create table llx_expensereport_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_expensereport_ik.sql b/htdocs/install/mysql/tables/llx_expensereport_ik.sql index ddc7fa4d3c7..839fbac8e9a 100644 --- a/htdocs/install/mysql/tables/llx_expensereport_ik.sql +++ b/htdocs/install/mysql/tables/llx_expensereport_ik.sql @@ -21,7 +21,7 @@ CREATE TABLE IF NOT EXISTS llx_expensereport_ik ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_c_exp_tax_cat integer DEFAULT 0 NOT NULL, fk_range integer DEFAULT 0 NOT NULL, coef double DEFAULT 0 NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_expensereport_rules.sql b/htdocs/install/mysql/tables/llx_expensereport_rules.sql index 2a10cc24a7d..ae8f9b09496 100644 --- a/htdocs/install/mysql/tables/llx_expensereport_rules.sql +++ b/htdocs/install/mysql/tables/llx_expensereport_rules.sql @@ -20,7 +20,7 @@ CREATE TABLE llx_expensereport_rules ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, dates datetime NOT NULL, datee datetime NOT NULL, amount double(24,8) NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_extrafields.sql b/htdocs/install/mysql/tables/llx_extrafields.sql index 3578414d98b..1ade8502bf5 100644 --- a/htdocs/install/mysql/tables/llx_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_extrafields.sql @@ -43,5 +43,5 @@ create table llx_extrafields fk_user_author integer, -- user making creation fk_user_modif integer, -- user making last change datec datetime, -- date de creation - tms timestamp -- date of last update + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP -- last modification date )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facture.sql b/htdocs/install/mysql/tables/llx_facture.sql index 429095e1111..010cf1c1573 100644 --- a/htdocs/install/mysql/tables/llx_facture.sql +++ b/htdocs/install/mysql/tables/llx_facture.sql @@ -39,7 +39,7 @@ create table llx_facture datef date, -- date invoice date_pointoftax date DEFAULT NULL, -- date point of tax (for GB) date_valid date, -- date validation - tms timestamp, -- date creation/modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date date_closing datetime, -- date de cloture paye smallint DEFAULT 0 NOT NULL, --amount double(24,8) DEFAULT 0 NOT NULL, @@ -86,6 +86,8 @@ create table llx_facture fk_incoterms integer, -- for incoterms location_incoterms varchar(255), -- for incoterms + fk_mode_transport integer, -- for intracomm report + situation_cycle_ref smallint, -- situation cycle reference situation_counter smallint, -- situation counter situation_final smallint, -- is the situation final ? diff --git a/htdocs/install/mysql/tables/llx_facture_extrafields.sql b/htdocs/install/mysql/tables/llx_facture_extrafields.sql index 4f7b902c97f..bc826d72ce4 100644 --- a/htdocs/install/mysql/tables/llx_facture_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_facture_extrafields.sql @@ -19,7 +19,7 @@ create table llx_facture_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facture_fourn.sql b/htdocs/install/mysql/tables/llx_facture_fourn.sql index 78b06370d8d..ef7e980b8aa 100644 --- a/htdocs/install/mysql/tables/llx_facture_fourn.sql +++ b/htdocs/install/mysql/tables/llx_facture_fourn.sql @@ -35,7 +35,7 @@ create table llx_facture_fourn datef date, -- date de la facture date_pointoftax date DEFAULT NULL, -- date point of tax (for GB) date_valid date, -- date validation - tms timestamp, -- date creation/modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date libelle varchar(255), paye smallint DEFAULT 0 NOT NULL, amount double(24,8) DEFAULT 0 NOT NULL, @@ -70,6 +70,9 @@ create table llx_facture_fourn note_public text, fk_incoterms integer, -- for incoterms location_incoterms varchar(255), -- for incoterms + + fk_mode_transport integer, -- for intracomm report + model_pdf varchar(255), last_main_doc varchar(255), -- relative filepath+filename of last main generated document diff --git a/htdocs/install/mysql/tables/llx_facture_fourn_det_extrafields.sql b/htdocs/install/mysql/tables/llx_facture_fourn_det_extrafields.sql index 7be8ff1c552..7fca2588bdf 100644 --- a/htdocs/install/mysql/tables/llx_facture_fourn_det_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_facture_fourn_det_extrafields.sql @@ -19,7 +19,7 @@ create table llx_facture_fourn_det_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facture_fourn_extrafields.sql b/htdocs/install/mysql/tables/llx_facture_fourn_extrafields.sql index 8fb018cbfcc..48556ec6d33 100644 --- a/htdocs/install/mysql/tables/llx_facture_fourn_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_facture_fourn_extrafields.sql @@ -19,7 +19,7 @@ create table llx_facture_fourn_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facture_rec.sql b/htdocs/install/mysql/tables/llx_facture_rec.sql index 220c1fa608a..0db78d62252 100644 --- a/htdocs/install/mysql/tables/llx_facture_rec.sql +++ b/htdocs/install/mysql/tables/llx_facture_rec.sql @@ -26,7 +26,7 @@ create table llx_facture_rec entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, datec datetime, -- date de creation - tms timestamp, -- date creation/modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date suspended integer DEFAULT 0, -- 1=suspended diff --git a/htdocs/install/mysql/tables/llx_facture_rec_extrafields.sql b/htdocs/install/mysql/tables/llx_facture_rec_extrafields.sql index 6895a7e2291..8a51efb2914 100644 --- a/htdocs/install/mysql/tables/llx_facture_rec_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_facture_rec_extrafields.sql @@ -19,7 +19,7 @@ create table llx_facture_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facturedet_extrafields.sql b/htdocs/install/mysql/tables/llx_facturedet_extrafields.sql index 693abf00001..99f0b87a943 100644 --- a/htdocs/install/mysql/tables/llx_facturedet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_facturedet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_facturedet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_facturedet_rec_extrafields.sql b/htdocs/install/mysql/tables/llx_facturedet_rec_extrafields.sql index da2314ecffb..c220a7e0f0f 100644 --- a/htdocs/install/mysql/tables/llx_facturedet_rec_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_facturedet_rec_extrafields.sql @@ -19,7 +19,7 @@ create table llx_facturedet_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_fichinter.sql b/htdocs/install/mysql/tables/llx_fichinter.sql index e2508c372ca..7c1ef4cf184 100644 --- a/htdocs/install/mysql/tables/llx_fichinter.sql +++ b/htdocs/install/mysql/tables/llx_fichinter.sql @@ -26,7 +26,7 @@ create table llx_fichinter ref varchar(30) NOT NULL, -- number ref_ext varchar(255), entity integer DEFAULT 1 NOT NULL, -- multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- date de creation date_valid datetime, -- date de validation datei date, -- date de livraison du bon d'intervention diff --git a/htdocs/install/mysql/tables/llx_fichinter_extrafields.sql b/htdocs/install/mysql/tables/llx_fichinter_extrafields.sql index 13c7dd15dab..c866669d667 100644 --- a/htdocs/install/mysql/tables/llx_fichinter_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_fichinter_extrafields.sql @@ -19,7 +19,7 @@ create table llx_fichinter_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_fichinterdet_extrafields.sql b/htdocs/install/mysql/tables/llx_fichinterdet_extrafields.sql index 65584c02201..f2ced33ec0d 100644 --- a/htdocs/install/mysql/tables/llx_fichinterdet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_fichinterdet_extrafields.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_fichinterdet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_holiday.sql b/htdocs/install/mysql/tables/llx_holiday.sql index e8116c477a8..3cd5727d867 100644 --- a/htdocs/install/mysql/tables/llx_holiday.sql +++ b/htdocs/install/mysql/tables/llx_holiday.sql @@ -42,7 +42,7 @@ fk_user_cancel integer DEFAULT NULL, detail_refuse varchar( 250 ) DEFAULT NULL, note_private text, note_public text, -tms timestamp, +tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14), extraparams varchar(255) -- for other parameters with json format ) diff --git a/htdocs/install/mysql/tables/llx_holiday_extrafields.sql b/htdocs/install/mysql/tables/llx_holiday_extrafields.sql index 29881bbb0cb..8b6e3ef8dc9 100644 --- a/htdocs/install/mysql/tables/llx_holiday_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_holiday_extrafields.sql @@ -19,7 +19,7 @@ create table llx_holiday_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_intracommreport.sql b/htdocs/install/mysql/tables/llx_intracommreport.sql new file mode 100644 index 00000000000..9d89320c1fa --- /dev/null +++ b/htdocs/install/mysql/tables/llx_intracommreport.sql @@ -0,0 +1,33 @@ +-- =================================================================== +-- Copyright (C) 2015 ATM Consulting +-- Copyright (C) 2019 Open-DSI +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- =================================================================== + +create table llx_intracommreport +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + + ref varchar(30) NOT NULL, -- report reference number + entity integer DEFAULT 1 NOT NULL, -- multi company id + type_declaration varchar(32), + periods varchar(32), + mode varchar(32), + content_xml text, + type_export varchar(10), + datec datetime, + tms timestamp +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_inventory.sql b/htdocs/install/mysql/tables/llx_inventory.sql index 4ccb234e26e..aa35ebb0c42 100644 --- a/htdocs/install/mysql/tables/llx_inventory.sql +++ b/htdocs/install/mysql/tables/llx_inventory.sql @@ -23,7 +23,7 @@ CREATE TABLE llx_inventory entity integer DEFAULT 0, ref varchar(48), date_creation datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, -- user making creation fk_user_modif integer, -- user making last change fk_user_valid integer, -- valideur de la fiche diff --git a/htdocs/install/mysql/tables/llx_inventorydet.sql b/htdocs/install/mysql/tables/llx_inventorydet.sql index 8c770895194..ce23fe0f749 100644 --- a/htdocs/install/mysql/tables/llx_inventorydet.sql +++ b/htdocs/install/mysql/tables/llx_inventorydet.sql @@ -21,7 +21,7 @@ CREATE TABLE llx_inventorydet ( rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_inventory integer DEFAULT 0, fk_warehouse integer DEFAULT 0, fk_product integer DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_livraison.sql b/htdocs/install/mysql/tables/llx_livraison.sql index 31af38edfb6..e58e8c3c0bd 100644 --- a/htdocs/install/mysql/tables/llx_livraison.sql +++ b/htdocs/install/mysql/tables/llx_livraison.sql @@ -20,7 +20,7 @@ create table llx_livraison ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ref varchar(30) NOT NULL, -- delivery number entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_livraison_extrafields.sql b/htdocs/install/mysql/tables/llx_livraison_extrafields.sql index 70248d0ceca..d1fc611bfdd 100644 --- a/htdocs/install/mysql/tables/llx_livraison_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_livraison_extrafields.sql @@ -19,7 +19,7 @@ create table llx_livraison_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_livraisondet_extrafields.sql b/htdocs/install/mysql/tables/llx_livraisondet_extrafields.sql index cb6300a8ca1..667f66ae0a8 100644 --- a/htdocs/install/mysql/tables/llx_livraisondet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_livraisondet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_livraisondet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_loan.sql b/htdocs/install/mysql/tables/llx_loan.sql index a1a187b5ba4..f82597c71c5 100644 --- a/htdocs/install/mysql/tables/llx_loan.sql +++ b/htdocs/install/mysql/tables/llx_loan.sql @@ -22,7 +22,7 @@ create table llx_loan rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(80) NOT NULL, fk_bank integer, diff --git a/htdocs/install/mysql/tables/llx_loan_schedule.sql b/htdocs/install/mysql/tables/llx_loan_schedule.sql index e23bc678e71..dd68a426e61 100644 --- a/htdocs/install/mysql/tables/llx_loan_schedule.sql +++ b/htdocs/install/mysql/tables/llx_loan_schedule.sql @@ -22,7 +22,7 @@ create table llx_loan_schedule rowid integer AUTO_INCREMENT PRIMARY KEY, fk_loan integer, datec datetime, -- creation date - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount_capital double(24,8) DEFAULT 0, amount_insurance double(24,8) DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_localtax.sql b/htdocs/install/mysql/tables/llx_localtax.sql index b7aa682567f..b883c710f7b 100644 --- a/htdocs/install/mysql/tables/llx_localtax.sql +++ b/htdocs/install/mysql/tables/llx_localtax.sql @@ -22,7 +22,7 @@ create table llx_localtax rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, localtaxtype tinyint, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep date, -- date of payment datev date, -- date of value amount double, diff --git a/htdocs/install/mysql/tables/llx_mailing.sql b/htdocs/install/mysql/tables/llx_mailing.sql index 8706159ad46..d9fc0832045 100644 --- a/htdocs/install/mysql/tables/llx_mailing.sql +++ b/htdocs/install/mysql/tables/llx_mailing.sql @@ -43,7 +43,7 @@ create table llx_mailing date_valid datetime, -- date_appro datetime, -- date_envoi datetime, -- date d'envoi - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, -- user creator fk_user_valid integer, -- user validator fk_user_appro integer, -- not used diff --git a/htdocs/install/mysql/tables/llx_mailing_cibles.sql b/htdocs/install/mysql/tables/llx_mailing_cibles.sql index b523c1d11eb..096142b10ad 100644 --- a/htdocs/install/mysql/tables/llx_mailing_cibles.sql +++ b/htdocs/install/mysql/tables/llx_mailing_cibles.sql @@ -34,6 +34,6 @@ create table llx_mailing_cibles source_id integer, source_type varchar(16), date_envoi datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, error_text varchar(255) -- text with error if statut is -1 )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_mailing_unsubscribe.sql b/htdocs/install/mysql/tables/llx_mailing_unsubscribe.sql index 00424256957..543015f5829 100644 --- a/htdocs/install/mysql/tables/llx_mailing_unsubscribe.sql +++ b/htdocs/install/mysql/tables/llx_mailing_unsubscribe.sql @@ -26,5 +26,5 @@ create table llx_mailing_unsubscribe unsubscribegroup varchar(128) DEFAULT '', ip varchar(128), date_creat datetime, -- creation date - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_menu.sql b/htdocs/install/mysql/tables/llx_menu.sql index 4408cb69627..9cff110981a 100644 --- a/htdocs/install/mysql/tables/llx_menu.sql +++ b/htdocs/install/mysql/tables/llx_menu.sql @@ -39,8 +39,8 @@ CREATE TABLE llx_menu langs varchar(100), -- Lang file to load for translation level smallint, -- Deprecated. Not used. perms text, -- Condition to show enabled or disabled - enabled text NULL default '1', -- Condition to show or hide + enabled text NULL, -- Condition to show or hide usertype integer NOT NULL DEFAULT 0, -- 0 if menu for all users, 1 for external only, 2 for internal only - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_mrp_mo.sql b/htdocs/install/mysql/tables/llx_mrp_mo.sql index d3aa294104b..de1933ccfed 100644 --- a/htdocs/install/mysql/tables/llx_mrp_mo.sql +++ b/htdocs/install/mysql/tables/llx_mrp_mo.sql @@ -27,7 +27,7 @@ CREATE TABLE llx_mrp_mo( note_private text, date_creation datetime NOT NULL, date_valid datetime NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, fk_user_valid integer, diff --git a/htdocs/install/mysql/tables/llx_mrp_mo_extrafields.sql b/htdocs/install/mysql/tables/llx_mrp_mo_extrafields.sql index 97eab584cc7..517c269cf0f 100644 --- a/htdocs/install/mysql/tables/llx_mrp_mo_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_mrp_mo_extrafields.sql @@ -16,7 +16,7 @@ create table llx_mrp_mo_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_mrp_production.sql b/htdocs/install/mysql/tables/llx_mrp_production.sql index 509d78a5c0e..bd0cd722f1a 100644 --- a/htdocs/install/mysql/tables/llx_mrp_production.sql +++ b/htdocs/install/mysql/tables/llx_mrp_production.sql @@ -28,7 +28,7 @@ CREATE TABLE llx_mrp_production( fk_mrp_production integer, -- if role = 'consumed', id of line with role 'toconsume', if role = 'produced' id of line with role 'toproduce' fk_stock_movement integer, -- id of stock movement when movements are validated date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14) diff --git a/htdocs/install/mysql/tables/llx_notify.sql b/htdocs/install/mysql/tables/llx_notify.sql index 3ec7d05268e..d2e3bf93076 100644 --- a/htdocs/install/mysql/tables/llx_notify.sql +++ b/htdocs/install/mysql/tables/llx_notify.sql @@ -22,7 +22,7 @@ create table llx_notify ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, daten datetime, -- date de la notification fk_action integer NOT NULL, fk_soc integer NULL, diff --git a/htdocs/install/mysql/tables/llx_notify_def.sql b/htdocs/install/mysql/tables/llx_notify_def.sql index bb516444b04..aed10027347 100644 --- a/htdocs/install/mysql/tables/llx_notify_def.sql +++ b/htdocs/install/mysql/tables/llx_notify_def.sql @@ -21,7 +21,7 @@ create table llx_notify_def ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec date, -- date de creation fk_action integer NOT NULL, fk_soc integer, diff --git a/htdocs/install/mysql/tables/llx_online_signatures.sql b/htdocs/install/mysql/tables/llx_online_signatures.sql index 312cde50671..fbba814dd4d 100644 --- a/htdocs/install/mysql/tables/llx_online_signatures.sql +++ b/htdocs/install/mysql/tables/llx_online_signatures.sql @@ -22,7 +22,7 @@ create table llx_onlinesignature object_type varchar(32) NOT NULL, object_id integer NOT NULL, datec datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, name varchar(255) NOT NULL, ip varchar(128), pathoffile varchar(255) diff --git a/htdocs/install/mysql/tables/llx_opensurvey_comments.sql b/htdocs/install/mysql/tables/llx_opensurvey_comments.sql index 3fcc5a0abf9..52d938b7c47 100644 --- a/htdocs/install/mysql/tables/llx_opensurvey_comments.sql +++ b/htdocs/install/mysql/tables/llx_opensurvey_comments.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_opensurvey_comments ( id_comment INTEGER unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, id_sondage CHAR(16) NOT NULL, comment text NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, usercomment text ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_opensurvey_user_studs.sql b/htdocs/install/mysql/tables/llx_opensurvey_user_studs.sql index a2ddafa1b54..03ad9b35ec5 100644 --- a/htdocs/install/mysql/tables/llx_opensurvey_user_studs.sql +++ b/htdocs/install/mysql/tables/llx_opensurvey_user_studs.sql @@ -20,5 +20,5 @@ CREATE TABLE llx_opensurvey_user_studs ( nom VARCHAR(64) NOT NULL, id_sondage VARCHAR(16) NOT NULL, reponses VARCHAR(100) NOT NULL, -- Not used for 'F' surveys - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_paiement.sql b/htdocs/install/mysql/tables/llx_paiement.sql index dabe261798b..bbf7d52e6c7 100644 --- a/htdocs/install/mysql/tables/llx_paiement.sql +++ b/htdocs/install/mysql/tables/llx_paiement.sql @@ -25,7 +25,7 @@ create table llx_paiement ref_ext varchar(255) NULL, -- payment external reference entity integer DEFAULT 1 NOT NULL, -- Multi company id datec datetime, -- date de creation - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount double(24,8) DEFAULT 0, -- amount paid in Dolibarr currency multicurrency_amount double(24,8) DEFAULT 0, -- amount paid in invoice currency diff --git a/htdocs/install/mysql/tables/llx_paiementcharge.sql b/htdocs/install/mysql/tables/llx_paiementcharge.sql index b489588777a..640f5f0af54 100644 --- a/htdocs/install/mysql/tables/llx_paiementcharge.sql +++ b/htdocs/install/mysql/tables/llx_paiementcharge.sql @@ -21,7 +21,7 @@ create table llx_paiementcharge rowid integer AUTO_INCREMENT PRIMARY KEY, fk_charge integer, datec datetime, -- date de creation - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount double(24,8) DEFAULT 0, fk_typepaiement integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_paiementfourn.sql b/htdocs/install/mysql/tables/llx_paiementfourn.sql index 519526f764a..04066435f20 100644 --- a/htdocs/install/mysql/tables/llx_paiementfourn.sql +++ b/htdocs/install/mysql/tables/llx_paiementfourn.sql @@ -22,7 +22,7 @@ create table llx_paiementfourn rowid integer AUTO_INCREMENT PRIMARY KEY, ref varchar(30), entity integer DEFAULT 1, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- date de creation de l'enregistrement datep datetime, -- date de paiement amount double(24,8) DEFAULT 0, -- montant diff --git a/htdocs/install/mysql/tables/llx_payment_donation.sql b/htdocs/install/mysql/tables/llx_payment_donation.sql index 6573bcb7119..088138bf96f 100644 --- a/htdocs/install/mysql/tables/llx_payment_donation.sql +++ b/htdocs/install/mysql/tables/llx_payment_donation.sql @@ -21,7 +21,7 @@ create table llx_payment_donation rowid integer AUTO_INCREMENT PRIMARY KEY, fk_donation integer, datec datetime, -- date de creation - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount double(24,8) DEFAULT 0, fk_typepayment integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_payment_expensereport.sql b/htdocs/install/mysql/tables/llx_payment_expensereport.sql index 8a75bfcdbfd..a83c0c926a4 100644 --- a/htdocs/install/mysql/tables/llx_payment_expensereport.sql +++ b/htdocs/install/mysql/tables/llx_payment_expensereport.sql @@ -21,7 +21,7 @@ create table llx_payment_expensereport rowid integer AUTO_INCREMENT PRIMARY KEY, fk_expensereport integer, datec datetime, -- date de creation - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount double(24,8) DEFAULT 0, fk_typepayment integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_payment_loan.sql b/htdocs/install/mysql/tables/llx_payment_loan.sql index a646ba1917b..0e080a1bdb7 100644 --- a/htdocs/install/mysql/tables/llx_payment_loan.sql +++ b/htdocs/install/mysql/tables/llx_payment_loan.sql @@ -22,7 +22,7 @@ create table llx_payment_loan rowid integer AUTO_INCREMENT PRIMARY KEY, fk_loan integer, datec datetime, -- creation date - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datep datetime, -- payment date amount_capital double(24,8) DEFAULT 0, amount_insurance double(24,8) DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_payment_salary.sql b/htdocs/install/mysql/tables/llx_payment_salary.sql index cc4aaf94ccb..d6ad2ffcfed 100644 --- a/htdocs/install/mysql/tables/llx_payment_salary.sql +++ b/htdocs/install/mysql/tables/llx_payment_salary.sql @@ -20,7 +20,7 @@ create table llx_payment_salary ( rowid integer AUTO_INCREMENT PRIMARY KEY, ref varchar(30) NULL, -- payment reference number (currently NULL because there is no numbering manager yet) - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- Create date fk_user integer NOT NULL, datep date, -- payment date diff --git a/htdocs/install/mysql/tables/llx_payment_salary_extrafields.sql b/htdocs/install/mysql/tables/llx_payment_salary_extrafields.sql index 3bfed602cff..5f15918ef18 100644 --- a/htdocs/install/mysql/tables/llx_payment_salary_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_payment_salary_extrafields.sql @@ -19,7 +19,7 @@ create table llx_payment_salary_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- salary payment id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_payment_various.sql b/htdocs/install/mysql/tables/llx_payment_various.sql index 4b48c649578..17bbf7c7a16 100644 --- a/htdocs/install/mysql/tables/llx_payment_various.sql +++ b/htdocs/install/mysql/tables/llx_payment_various.sql @@ -22,7 +22,7 @@ create table llx_payment_various ref varchar(30) NULL, -- payment reference number (currently NULL because there is no numbering manager yet) num_payment varchar(50), -- num cheque or other label varchar(255), - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- Create date datep date, -- date de paiement datev date, -- date de valeur (this field should not be here, only into bank tables) diff --git a/htdocs/install/mysql/tables/llx_printing.sql b/htdocs/install/mysql/tables/llx_printing.sql index 0f0c7c71d1b..ecfe050240b 100644 --- a/htdocs/install/mysql/tables/llx_printing.sql +++ b/htdocs/install/mysql/tables/llx_printing.sql @@ -20,7 +20,7 @@ CREATE TABLE llx_printing ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, printer_name text NOT NULL, printer_location text NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_product.key.sql b/htdocs/install/mysql/tables/llx_product.key.sql index c3dd33c88c5..c0526a8f2cc 100644 --- a/htdocs/install/mysql/tables/llx_product.key.sql +++ b/htdocs/install/mysql/tables/llx_product.key.sql @@ -33,6 +33,7 @@ ALTER TABLE llx_product ADD INDEX idx_product_fk_barcode_type (fk_barcode_type); ALTER TABLE llx_product ADD INDEX idx_product_fk_project (fk_project); ALTER TABLE llx_product ADD UNIQUE INDEX uk_product_barcode (barcode, fk_barcode_type, entity); ALTER TABLE llx_product ADD CONSTRAINT fk_product_fk_unit FOREIGN KEY (fk_unit) REFERENCES llx_c_units (rowid); +ALTER TABLE llx_product ADD CONSTRAINT fk_product_finished FOREIGN KEY (finished) REFERENCES llx_c_product_nature (code); ALTER TABLE llx_product ADD CONSTRAINT fk_product_fk_country FOREIGN KEY (fk_country) REFERENCES llx_c_country (rowid); ALTER TABLE llx_product ADD CONSTRAINT fk_product_barcode_type FOREIGN KEY (fk_barcode_type) REFERENCES llx_c_barcode_type (rowid); diff --git a/htdocs/install/mysql/tables/llx_product.sql b/htdocs/install/mysql/tables/llx_product.sql index 714a342a652..2431c884c62 100644 --- a/htdocs/install/mysql/tables/llx_product.sql +++ b/htdocs/install/mysql/tables/llx_product.sql @@ -30,7 +30,7 @@ create table llx_product ref_ext varchar(128), -- reference into an external system (not used by dolibarr) datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_parent integer DEFAULT 0, -- Not used. Used by external modules. Virtual product id label varchar(255) NOT NULL, @@ -92,7 +92,7 @@ create table llx_product lifo double(24,8), -- To store valuation of stock calculated using lifo method, for this product. TODO Not used, should be replaced by stock value stored into movement table. fk_default_warehouse integer DEFAULT NULL, canvas varchar(32) DEFAULT NULL, - finished tinyint DEFAULT NULL, -- 1=manufactured product, 0=matiere premiere + finished tinyint DEFAULT NULL, -- see dictionnary c_product_nature hidden tinyint DEFAULT 0, -- Not used. Deprecated. import_key varchar(14), -- Import key model_pdf varchar(255), -- model save dodument used diff --git a/htdocs/install/mysql/tables/llx_product_batch.sql b/htdocs/install/mysql/tables/llx_product_batch.sql index 9b736278e3a..7300c49874f 100644 --- a/htdocs/install/mysql/tables/llx_product_batch.sql +++ b/htdocs/install/mysql/tables/llx_product_batch.sql @@ -20,7 +20,7 @@ CREATE TABLE llx_product_batch ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product_stock integer NOT NULL, eatby datetime DEFAULT NULL, -- deprecated. should not be used here but should be stored into a table llx_product_lot sellby datetime DEFAULT NULL, -- deprecated. should not be used here but should be stored into a table llx_product_lot diff --git a/htdocs/install/mysql/tables/llx_product_customer_price.sql b/htdocs/install/mysql/tables/llx_product_customer_price.sql index c7b6f1eb1a2..7cd481c3c75 100644 --- a/htdocs/install/mysql/tables/llx_product_customer_price.sql +++ b/htdocs/install/mysql/tables/llx_product_customer_price.sql @@ -25,7 +25,7 @@ create table llx_product_customer_price rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer NOT NULL, fk_soc integer NOT NULL, price double(24,8) DEFAULT 0, diff --git a/htdocs/install/mysql/tables/llx_product_extrafields.sql b/htdocs/install/mysql/tables/llx_product_extrafields.sql index b265340d11c..24e53d9bda6 100644 --- a/htdocs/install/mysql/tables/llx_product_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_product_extrafields.sql @@ -19,7 +19,7 @@ create table llx_product_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql b/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql index 7e61a2df6b1..20d4db7492b 100644 --- a/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql +++ b/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql @@ -24,7 +24,7 @@ create table llx_product_fournisseur_price rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer, fk_soc integer, ref_fourn varchar(30), diff --git a/htdocs/install/mysql/tables/llx_product_fournisseur_price_extrafields.sql b/htdocs/install/mysql/tables/llx_product_fournisseur_price_extrafields.sql index 51d5499e825..728915521a7 100644 --- a/htdocs/install/mysql/tables/llx_product_fournisseur_price_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_product_fournisseur_price_extrafields.sql @@ -18,7 +18,7 @@ Create Table llx_product_fournisseur_price_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_product_lot.sql b/htdocs/install/mysql/tables/llx_product_lot.sql index 4d59a46c153..86cca7d0f04 100644 --- a/htdocs/install/mysql/tables/llx_product_lot.sql +++ b/htdocs/install/mysql/tables/llx_product_lot.sql @@ -25,7 +25,7 @@ CREATE TABLE llx_product_lot ( eatby date DEFAULT NULL, -- Eatby date sellby date DEFAULT NULL, -- Sellby date datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, import_key integer diff --git a/htdocs/install/mysql/tables/llx_product_lot_extrafields.sql b/htdocs/install/mysql/tables/llx_product_lot_extrafields.sql index b3843ed9ba6..8fbbbde1bc5 100644 --- a/htdocs/install/mysql/tables/llx_product_lot_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_product_lot_extrafields.sql @@ -19,7 +19,7 @@ create table llx_product_lot_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_product_price.sql b/htdocs/install/mysql/tables/llx_product_price.sql index 75a5355afe7..ff862e427e0 100644 --- a/htdocs/install/mysql/tables/llx_product_price.sql +++ b/htdocs/install/mysql/tables/llx_product_price.sql @@ -25,7 +25,7 @@ create table llx_product_price ( rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- Multi company id - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer NOT NULL, date_price datetime NOT NULL, price_level smallint NULL DEFAULT 1, diff --git a/htdocs/install/mysql/tables/llx_product_price_by_qty.sql b/htdocs/install/mysql/tables/llx_product_price_by_qty.sql index 7cb8b327b4d..dc3a21bfedb 100644 --- a/htdocs/install/mysql/tables/llx_product_price_by_qty.sql +++ b/htdocs/install/mysql/tables/llx_product_price_by_qty.sql @@ -40,6 +40,6 @@ create table llx_product_price_by_qty multicurrency_price double(24,8) DEFAULT NULL, multicurrency_price_ttc double(24,8) DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_product_stock.sql b/htdocs/install/mysql/tables/llx_product_stock.sql index 586c5b410c7..c5a2f4ad005 100644 --- a/htdocs/install/mysql/tables/llx_product_stock.sql +++ b/htdocs/install/mysql/tables/llx_product_stock.sql @@ -21,7 +21,7 @@ create table llx_product_stock ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer NOT NULL, fk_entrepot integer NOT NULL, reel real, -- physical stock diff --git a/htdocs/install/mysql/tables/llx_product_stock_entrepot.sql b/htdocs/install/mysql/tables/llx_product_stock_entrepot.sql index 903bd59b524..d6d5e57e549 100644 --- a/htdocs/install/mysql/tables/llx_product_stock_entrepot.sql +++ b/htdocs/install/mysql/tables/llx_product_stock_entrepot.sql @@ -21,7 +21,7 @@ create table llx_product_warehouse_properties ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_product integer NOT NULL, fk_entrepot integer NOT NULL, seuil_stock_alerte float DEFAULT '0', diff --git a/htdocs/install/mysql/tables/llx_projet.sql b/htdocs/install/mysql/tables/llx_projet.sql index f783597653f..a36adb3a672 100644 --- a/htdocs/install/mysql/tables/llx_projet.sql +++ b/htdocs/install/mysql/tables/llx_projet.sql @@ -22,7 +22,7 @@ create table llx_projet rowid integer AUTO_INCREMENT PRIMARY KEY, fk_soc integer, datec datetime, -- date creation project - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, dateo date, -- date start project datee date, -- date end project ref varchar(50), diff --git a/htdocs/install/mysql/tables/llx_projet_extrafields.sql b/htdocs/install/mysql/tables/llx_projet_extrafields.sql index 8a96a715b05..0001d4e8876 100644 --- a/htdocs/install/mysql/tables/llx_projet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_projet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_projet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_projet_task.sql b/htdocs/install/mysql/tables/llx_projet_task.sql index cc1088cf7a7..01edb857738 100644 --- a/htdocs/install/mysql/tables/llx_projet_task.sql +++ b/htdocs/install/mysql/tables/llx_projet_task.sql @@ -25,7 +25,7 @@ create table llx_projet_task fk_projet integer NOT NULL, fk_task_parent integer DEFAULT 0 NOT NULL, datec datetime, -- date creation - tms timestamp, -- date creation/modification + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date dateo datetime, -- date start task datee datetime, -- date end task datev datetime, -- date validation diff --git a/htdocs/install/mysql/tables/llx_projet_task_extrafields.sql b/htdocs/install/mysql/tables/llx_projet_task_extrafields.sql index 256c9025dc0..bf3d25e6922 100644 --- a/htdocs/install/mysql/tables/llx_projet_task_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_projet_task_extrafields.sql @@ -19,7 +19,7 @@ create table llx_projet_task_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_projet_task_time.sql b/htdocs/install/mysql/tables/llx_projet_task_time.sql index e1c857af2c3..786d8907588 100644 --- a/htdocs/install/mysql/tables/llx_projet_task_time.sql +++ b/htdocs/install/mysql/tables/llx_projet_task_time.sql @@ -29,7 +29,7 @@ create table llx_projet_task_time invoice_id integer DEFAULT NULL, -- If we need to invoice each line of timespent, we can save invoice id here invoice_line_id integer DEFAULT NULL, -- If we need to invoice each line of timespent, we can save invoice line id here import_key varchar(14), -- Import key - datec date, -- Date creation time - tms timestamp, -- Date update time + datec datetime, -- date creation time + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date note text -- A comment )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_propal.sql b/htdocs/install/mysql/tables/llx_propal.sql index d21d9ef2d7e..662db791094 100644 --- a/htdocs/install/mysql/tables/llx_propal.sql +++ b/htdocs/install/mysql/tables/llx_propal.sql @@ -32,7 +32,7 @@ create table llx_propal fk_soc integer, fk_projet integer DEFAULT NULL, -- projet auquel est rattache la propale - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- date de creation datep date, -- date de la propal fin_validite datetime, -- date de fin de validite diff --git a/htdocs/install/mysql/tables/llx_propal_extrafields.sql b/htdocs/install/mysql/tables/llx_propal_extrafields.sql index f6ccb68b39b..31201e37b55 100644 --- a/htdocs/install/mysql/tables/llx_propal_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_propal_extrafields.sql @@ -19,7 +19,7 @@ create table llx_propal_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_propal_merge_pdf_product.sql b/htdocs/install/mysql/tables/llx_propal_merge_pdf_product.sql index 0c636b2507c..b599702d560 100644 --- a/htdocs/install/mysql/tables/llx_propal_merge_pdf_product.sql +++ b/htdocs/install/mysql/tables/llx_propal_merge_pdf_product.sql @@ -22,7 +22,7 @@ CREATE TABLE llx_propal_merge_pdf_product ( fk_user_author integer DEFAULT NULL, fk_user_mod integer NOT NULL, datec datetime NOT NULL, - tms timestamp NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14) DEFAULT NULL ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_propaldet_extrafields.sql b/htdocs/install/mysql/tables/llx_propaldet_extrafields.sql index 74986b1c641..7235d65eccd 100644 --- a/htdocs/install/mysql/tables/llx_propaldet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_propaldet_extrafields.sql @@ -19,7 +19,7 @@ create table llx_propaldet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_reception.sql b/htdocs/install/mysql/tables/llx_reception.sql index 05ed6ca4604..71cc000ffc1 100644 --- a/htdocs/install/mysql/tables/llx_reception.sql +++ b/htdocs/install/mysql/tables/llx_reception.sql @@ -22,7 +22,7 @@ create table llx_reception ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, ref varchar(30) NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_reception_extrafields.sql b/htdocs/install/mysql/tables/llx_reception_extrafields.sql index e2f83794a0b..13d3be5fe77 100644 --- a/htdocs/install/mysql/tables/llx_reception_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_reception_extrafields.sql @@ -19,7 +19,7 @@ create table llx_reception_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql index f135c1af72f..ded61d49e8b 100644 --- a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql +++ b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.sql @@ -24,7 +24,7 @@ CREATE TABLE llx_recruitment_recruitmentcandidature( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), diff --git a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature_extrafields.sql b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature_extrafields.sql index d0fb92fead9..77cf71b9b00 100644 --- a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature_extrafields.sql @@ -16,7 +16,7 @@ create table llx_recruitment_recruitmentcandidature_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition.sql b/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition.sql index b342156ccd1..4ad1198d808 100644 --- a/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition.sql +++ b/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition.sql @@ -33,7 +33,7 @@ CREATE TABLE llx_recruitment_recruitmentjobposition( note_public text, note_private text, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, last_main_doc varchar(255), diff --git a/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition_extrafields.sql b/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition_extrafields.sql index 07ae2ef5153..21b1ec081bf 100644 --- a/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_recruitment_recruitmentjobposition_extrafields.sql @@ -16,7 +16,7 @@ create table llx_recruitment_recruitmentjobposition_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_resource.sql b/htdocs/install/mysql/tables/llx_resource.sql index 7dc709ad83a..30bd2bcbbf3 100644 --- a/htdocs/install/mysql/tables/llx_resource.sql +++ b/htdocs/install/mysql/tables/llx_resource.sql @@ -34,5 +34,5 @@ CREATE TABLE llx_resource import_key varchar(14), extraparams varchar(255), -- for stock other parameters with json format fk_country integer DEFAULT NULL, -- Optional id of original country - tms timestamp + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_resource_extrafields.sql b/htdocs/install/mysql/tables/llx_resource_extrafields.sql index 6e828258339..88bcc7606c8 100644 --- a/htdocs/install/mysql/tables/llx_resource_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_resource_extrafields.sql @@ -19,7 +19,7 @@ create table llx_resource_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_societe.sql b/htdocs/install/mysql/tables/llx_societe.sql index a98be7912f7..ea02b7be8ad 100644 --- a/htdocs/install/mysql/tables/llx_societe.sql +++ b/htdocs/install/mysql/tables/llx_societe.sql @@ -92,8 +92,10 @@ create table llx_societe remise_supplier real DEFAULT 0, -- discount by default granted by this supplier mode_reglement tinyint, -- payment mode customer cond_reglement tinyint, -- payment term customer + transport_mode tinyint, -- transport mode customer (Intracomm report) mode_reglement_supplier tinyint, -- payment mode supplier cond_reglement_supplier tinyint, -- payment term supplier + transport_mode_supplier tinyint, -- transport mode supplier (Intracomm report) fk_shipping_method integer, -- preferred shipping method id tva_assuj tinyint DEFAULT 1, -- assujeti ou non a la TVA localtax1_assuj tinyint DEFAULT 0, -- assujeti ou non a local tax 1 @@ -114,7 +116,7 @@ create table llx_societe webservices_url varchar(255), -- supplier webservice url webservices_key varchar(128), -- supplier webservice key - tms timestamp, -- last modification date + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date datec datetime, -- creation date fk_user_creat integer NULL, -- utilisateur qui a cree l'info fk_user_modif integer, -- utilisateur qui a modifie l'info diff --git a/htdocs/install/mysql/tables/llx_societe_account.sql b/htdocs/install/mysql/tables/llx_societe_account.sql index 6a78a9a7839..b200d4f3854 100644 --- a/htdocs/install/mysql/tables/llx_societe_account.sql +++ b/htdocs/install/mysql/tables/llx_societe_account.sql @@ -33,7 +33,7 @@ CREATE TABLE llx_societe_account( date_last_login datetime, date_previous_login datetime, date_creation datetime NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer NOT NULL, fk_user_modif integer, import_key varchar(14), diff --git a/htdocs/install/mysql/tables/llx_societe_address.sql b/htdocs/install/mysql/tables/llx_societe_address.sql index 626b0155519..2b5f2d57146 100644 --- a/htdocs/install/mysql/tables/llx_societe_address.sql +++ b/htdocs/install/mysql/tables/llx_societe_address.sql @@ -21,7 +21,7 @@ create table llx_societe_address ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime, -- creation date - tms timestamp, -- modification date + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- last modification date label varchar(30), -- fk_soc integer DEFAULT 0, -- name varchar(60), -- company name diff --git a/htdocs/install/mysql/tables/llx_societe_extrafields.sql b/htdocs/install/mysql/tables/llx_societe_extrafields.sql index e277db15821..a4b5b269358 100644 --- a/htdocs/install/mysql/tables/llx_societe_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_societe_extrafields.sql @@ -19,7 +19,7 @@ create table llx_societe_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_societe_prices.sql b/htdocs/install/mysql/tables/llx_societe_prices.sql index 2b88340e611..2e9178774f5 100644 --- a/htdocs/install/mysql/tables/llx_societe_prices.sql +++ b/htdocs/install/mysql/tables/llx_societe_prices.sql @@ -20,7 +20,7 @@ create table llx_societe_prices ( rowid integer AUTO_INCREMENT PRIMARY KEY, fk_soc integer DEFAULT 0, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, fk_user_author integer, price_level tinyint DEFAULT 1 diff --git a/htdocs/install/mysql/tables/llx_societe_remise.sql b/htdocs/install/mysql/tables/llx_societe_remise.sql index a3a265cce5f..2d4e3a9c258 100644 --- a/htdocs/install/mysql/tables/llx_societe_remise.sql +++ b/htdocs/install/mysql/tables/llx_societe_remise.sql @@ -24,7 +24,7 @@ create table llx_societe_remise rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- creation date fk_user_author integer, -- creation user remise_client double(6,3) DEFAULT 0 NOT NULL, -- discount diff --git a/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql b/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql index 3786b16b76a..d6dfdc20d9d 100644 --- a/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql +++ b/htdocs/install/mysql/tables/llx_societe_remise_supplier.sql @@ -24,7 +24,7 @@ create table llx_societe_remise_supplier rowid integer AUTO_INCREMENT PRIMARY KEY, entity integer DEFAULT 1 NOT NULL, -- multi company id fk_soc integer NOT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- creation date fk_user_author integer, -- creation user remise_supplier double(6,3) DEFAULT 0 NOT NULL, -- discount diff --git a/htdocs/install/mysql/tables/llx_societe_rib.sql b/htdocs/install/mysql/tables/llx_societe_rib.sql index 7d00d9fb1dd..ece4b2edffe 100644 --- a/htdocs/install/mysql/tables/llx_societe_rib.sql +++ b/htdocs/install/mysql/tables/llx_societe_rib.sql @@ -27,7 +27,7 @@ create table llx_societe_rib label varchar(200), fk_soc integer NOT NULL, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- For BAN bank varchar(255), -- bank name diff --git a/htdocs/install/mysql/tables/llx_socpeople.sql b/htdocs/install/mysql/tables/llx_socpeople.sql index 2a1b551beb9..decc229e3e7 100644 --- a/htdocs/install/mysql/tables/llx_socpeople.sql +++ b/htdocs/install/mysql/tables/llx_socpeople.sql @@ -23,7 +23,7 @@ create table llx_socpeople ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_soc integer, -- lien vers la societe entity integer DEFAULT 1 NOT NULL, -- multi company id ref_ext varchar(255), -- reference into an external system (not used by dolibarr) diff --git a/htdocs/install/mysql/tables/llx_socpeople_extrafields.sql b/htdocs/install/mysql/tables/llx_socpeople_extrafields.sql index 66220ce7e98..f2f594e12f3 100644 --- a/htdocs/install/mysql/tables/llx_socpeople_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_socpeople_extrafields.sql @@ -19,7 +19,7 @@ create table llx_socpeople_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_stock_mouvement.sql b/htdocs/install/mysql/tables/llx_stock_mouvement.sql index 94501a516dd..2cd094c1b05 100644 --- a/htdocs/install/mysql/tables/llx_stock_mouvement.sql +++ b/htdocs/install/mysql/tables/llx_stock_mouvement.sql @@ -20,7 +20,7 @@ create table llx_stock_mouvement ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datem datetime, -- Date and hour of movement fk_product integer NOT NULL, -- Id of product batch varchar(128) DEFAULT NULL, -- Lot or serial number diff --git a/htdocs/install/mysql/tables/llx_subscription.sql b/htdocs/install/mysql/tables/llx_subscription.sql index 03d24c68f6e..8e86e216d3f 100644 --- a/htdocs/install/mysql/tables/llx_subscription.sql +++ b/htdocs/install/mysql/tables/llx_subscription.sql @@ -19,7 +19,7 @@ create table llx_subscription ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, fk_adherent integer, fk_type integer, diff --git a/htdocs/install/mysql/tables/llx_supplier_proposal.sql b/htdocs/install/mysql/tables/llx_supplier_proposal.sql index 5e7393112d8..e63c4ff64c7 100644 --- a/htdocs/install/mysql/tables/llx_supplier_proposal.sql +++ b/htdocs/install/mysql/tables/llx_supplier_proposal.sql @@ -23,7 +23,7 @@ CREATE TABLE llx_supplier_proposal ( ref_int varchar(255) DEFAULT NULL, fk_soc integer DEFAULT NULL, fk_projet integer DEFAULT NULL, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime DEFAULT NULL, date_valid datetime DEFAULT NULL, date_cloture datetime DEFAULT NULL, diff --git a/htdocs/install/mysql/tables/llx_supplier_proposal_extrafields.sql b/htdocs/install/mysql/tables/llx_supplier_proposal_extrafields.sql index a13c74d0d04..8dfed18bbbc 100644 --- a/htdocs/install/mysql/tables/llx_supplier_proposal_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_supplier_proposal_extrafields.sql @@ -17,7 +17,7 @@ CREATE TABLE llx_supplier_proposal_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) DEFAULT NULL ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_supplier_proposaldet_extrafields.sql b/htdocs/install/mysql/tables/llx_supplier_proposaldet_extrafields.sql index 0501aecc68b..df6b5216c21 100644 --- a/htdocs/install/mysql/tables/llx_supplier_proposaldet_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_supplier_proposaldet_extrafields.sql @@ -17,7 +17,7 @@ CREATE TABLE llx_supplier_proposaldet_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) DEFAULT NULL ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticket.sql b/htdocs/install/mysql/tables/llx_ticket.sql index 4440bce5cec..c053e787dfa 100644 --- a/htdocs/install/mysql/tables/llx_ticket.sql +++ b/htdocs/install/mysql/tables/llx_ticket.sql @@ -39,6 +39,6 @@ CREATE TABLE llx_ticket date_close datetime, notify_tiers_at_create tinyint, email_msgid varchar(255), -- if ticket is created by email collector, we store here MSG ID - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14) )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_ticket_extrafields.sql b/htdocs/install/mysql/tables/llx_ticket_extrafields.sql index 538da09692e..31f82064461 100644 --- a/htdocs/install/mysql/tables/llx_ticket_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_ticket_extrafields.sql @@ -18,7 +18,7 @@ create table llx_ticket_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- ticket id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_tva.sql b/htdocs/install/mysql/tables/llx_tva.sql index 2804d410e7d..6cf97e6b4c6 100644 --- a/htdocs/install/mysql/tables/llx_tva.sql +++ b/htdocs/install/mysql/tables/llx_tva.sql @@ -20,7 +20,7 @@ create table llx_tva ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, datec datetime, -- Create date datep date, -- date de paiement datev date, -- date de valeur diff --git a/htdocs/install/mysql/tables/llx_user.sql b/htdocs/install/mysql/tables/llx_user.sql index b49feba85d6..c734192ad64 100644 --- a/htdocs/install/mysql/tables/llx_user.sql +++ b/htdocs/install/mysql/tables/llx_user.sql @@ -29,7 +29,7 @@ create table llx_user fk_establishment integer DEFAULT 0, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, login varchar(50) NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_user_employment.sql b/htdocs/install/mysql/tables/llx_user_employment.sql index ff2a87028d4..c06df0189d2 100644 --- a/htdocs/install/mysql/tables/llx_user_employment.sql +++ b/htdocs/install/mysql/tables/llx_user_employment.sql @@ -25,7 +25,7 @@ create table llx_user_employment ref_ext varchar(50), -- reference into an external system (not used by dolibarr) fk_user integer, datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_user_creat integer, fk_user_modif integer, job varchar(128), -- job position. may be a dictionary diff --git a/htdocs/install/mysql/tables/llx_user_extrafields.sql b/htdocs/install/mysql/tables/llx_user_extrafields.sql index b7ba9116630..c38e9435a63 100644 --- a/htdocs/install/mysql/tables/llx_user_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_user_extrafields.sql @@ -21,7 +21,7 @@ create table llx_user_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- member id import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_user_rib.sql b/htdocs/install/mysql/tables/llx_user_rib.sql index 1349e77a77b..4463a1f6f2b 100644 --- a/htdocs/install/mysql/tables/llx_user_rib.sql +++ b/htdocs/install/mysql/tables/llx_user_rib.sql @@ -22,7 +22,7 @@ create table llx_user_rib fk_user integer NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, label varchar(30), bank varchar(255), -- bank name code_banque varchar(128), -- bank code diff --git a/htdocs/install/mysql/tables/llx_usergroup.sql b/htdocs/install/mysql/tables/llx_usergroup.sql index 43bbba9dbb1..959dfbca3d9 100644 --- a/htdocs/install/mysql/tables/llx_usergroup.sql +++ b/htdocs/install/mysql/tables/llx_usergroup.sql @@ -24,7 +24,7 @@ create table llx_usergroup nom varchar(180) NOT NULL, entity integer DEFAULT 1 NOT NULL, -- multi company id datec datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, note text, model_pdf varchar(255) DEFAULT NULL )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_usergroup_extrafields.sql b/htdocs/install/mysql/tables/llx_usergroup_extrafields.sql index e2e96f142d9..ea358509eff 100644 --- a/htdocs/install/mysql/tables/llx_usergroup_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_usergroup_extrafields.sql @@ -18,7 +18,7 @@ CREATE TABLE llx_usergroup_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_website.sql b/htdocs/install/mysql/tables/llx_website.sql index 717052f795c..b2103177972 100644 --- a/htdocs/install/mysql/tables/llx_website.sql +++ b/htdocs/install/mysql/tables/llx_website.sql @@ -36,6 +36,6 @@ CREATE TABLE llx_website fk_user_modif integer, date_creation datetime, position integer DEFAULT 0, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_website_extrafields.sql b/htdocs/install/mysql/tables/llx_website_extrafields.sql index ff39e2c51c4..b3fd6786a09 100644 --- a/htdocs/install/mysql/tables/llx_website_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_website_extrafields.sql @@ -16,7 +16,7 @@ CREATE TABLE llx_website_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_website_page.sql b/htdocs/install/mysql/tables/llx_website_page.sql index e2bec4a8a24..4b1b3045d6b 100644 --- a/htdocs/install/mysql/tables/llx_website_page.sql +++ b/htdocs/install/mysql/tables/llx_website_page.sql @@ -38,7 +38,7 @@ CREATE TABLE llx_website_page fk_user_modif integer, author_alias varchar(64), date_creation datetime, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14), -- import key object_type varchar(255), fk_object varchar(255) diff --git a/htdocs/install/mysql/tables/llx_zapier_hook.sql b/htdocs/install/mysql/tables/llx_zapier_hook.sql index 27d56352bff..b54fbc0d348 100644 --- a/htdocs/install/mysql/tables/llx_zapier_hook.sql +++ b/htdocs/install/mysql/tables/llx_zapier_hook.sql @@ -22,8 +22,8 @@ CREATE TABLE llx_zapier_hook( module varchar(128), action varchar(128), status integer, - date_creation DATETIME NOT NULL, + date_creation datetime NOT NULL, fk_user integer NOT NULL, - tms TIMESTAMP NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, import_key varchar(14) ) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_zapier_hook_extrafields.sql b/htdocs/install/mysql/tables/llx_zapier_hook_extrafields.sql index 09fef4cc399..0b4f6e97238 100644 --- a/htdocs/install/mysql/tables/llx_zapier_hook_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_zapier_hook_extrafields.sql @@ -16,7 +16,7 @@ create table llx_zapier_hook_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; diff --git a/htdocs/intracommreport/admin/index.html b/htdocs/intracommreport/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/intracommreport/admin/intracommreport.php b/htdocs/intracommreport/admin/intracommreport.php new file mode 100644 index 00000000000..5c2246ec852 --- /dev/null +++ b/htdocs/intracommreport/admin/intracommreport.php @@ -0,0 +1,208 @@ + + * Copyright (C) 2019-2020 Open-DSI + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/intracommreport.php + * \ingroup intracommreport + * \brief Page to setup the module intracomm report + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/intracommreport.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("admin","intracommreport")); + +if (! $user->admin) accessforbidden(); + +$action = GETPOST('action', 'aZ09'); + +// Parameters INTRACOMMREPORT_* and others +$list_DEB = array ( + 'INTRACOMMREPORT_NUM_AGREMENT', +); + +$list_DES = array ( + 'INTRACOMMREPORT_NUM_DECLARATION', +); + +if ($action == 'update') { + $error = 0; + + if (! $error) + { + foreach ($list_DEB as $constname) + { + $constvalue = GETPOST($constname, 'alpha'); + + if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } + + foreach ($list_DES as $constname) + { + $constvalue = GETPOST($constname, 'alpha'); + + if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } + + dolibarr_set_const($db, "INTRACOMMREPORT_TYPE_ACTEUR", GETPOST("INTRACOMMREPORT_TYPE_ACTEUR", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "INTRACOMMREPORT_ROLE_ACTEUR", GETPOST("INTRACOMMREPORT_ROLE_ACTEUR", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "INTRACOMMREPORT_NIV_OBLIGATION_INTRODUCTION", GETPOST("INTRACOMMREPORT_NIV_OBLIGATION_INTRODUCTION", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "INTRACOMMREPORT_NIV_OBLIGATION_EXPEDITION", GETPOST("INTRACOMMREPORT_NIV_OBLIGATION_EXPEDITION", 'alpha'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "INTRACOMMREPORT_CATEG_FRAISDEPORT", GETPOST("INTRACOMMREPORT_CATEG_FRAISDEPORT", 'alpha'), 'chaine', 0, '', $conf->entity); + + if ($error) { + setEventMessages($langs->trans("Error"), null, 'errors'); + } + } + + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } +} + +/* + * View + */ + +$form=new Form($db); +$formother=new FormOther($db); + +llxHeader('', $langs->trans("IntracommReportSetup")); + +$linkback = '' . $langs->trans("BackToModuleList") . ''; +print load_fiche_titre($langs->trans("IntracommReportSetup"), $linkback, 'title_setup'); + +$head = intracommReportAdminPrepareHead(); + +dol_fiche_head($head, 'general', $langs->trans("IntracommReport"), -1, "intracommreport"); + +print '
    '; +print ''; +print ''; + +print load_fiche_titre($langs->trans("Parameters").' (DEB)'); + +print '
    '; - print ''.img_picto($langs->trans("NewImport"), 'filenew').''; + print ''.img_picto($langs->trans("NewImport"), 'next', 'class="fa-15x"').''; print '
    '; +print ''; +print ''; +print ''; +print ''; + +foreach ($list_DEB as $key) +{ + print ''; + + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + + print ''; +} + +print ''; +print ''; +$arraychoices=array(''=>$langs->trans("None"), 'PSI'=>'Déclarant pour son compte', 'TDP'=>'Tiers déclarant'); +print ''; +print "\n"; + +print ''; +print ''; +$arraychoices=array(''=>$langs->trans("None"), 'sender'=>'Emetteur', 'PSI'=>'Déclarant'); +print ''; +print "\n"; + +print ''; +print ''; +$arraychoices=array(1=>'Seuil de 460 000 €', 2=>'En dessous de 460 000 €'); +print ''; +print "\n"; + +print ''; +print ''; +$arraychoices=array(3=>'Seuil de 460 000 €', 4=>'En dessous de 460 000 €'); +print ''; +print "\n"; + +print ''; +print ''; +$arraychoices=array(3=>'Seuil de 460 000 €', 4=>'En dessous de 460 000 €'); +print ''; +print "\n"; + +print '
    '.$langs->trans("Description").''.$langs->trans("Value").'
    '.$label.''; + print ''; + print '
    '.$langs->trans("INTRACOMMREPORT_TYPE_ACTEUR").''; +print $form->selectarray('INTRACOMMREPORT_TYPE_ACTEUR', $arraychoices, $conf->global->INTRACOMMREPORT_TYPE_ACTEUR, 0); +print '
    '.$langs->trans("INTRACOMMREPORT_ROLE_ACTEUR").''; +print $form->selectarray('INTRACOMMREPORT_ROLE_ACTEUR', $arraychoices, $conf->global->INTRACOMMREPORT_ROLE_ACTEUR, 0); +print '
    '.$langs->trans("INTRACOMMREPORT_NIV_OBLIGATION_INTRODUCTION").''; +print $form->selectarray('INTRACOMMREPORT_NIV_OBLIGATION_INTRODUCTION', $arraychoices, $conf->global->INTRACOMMREPORT_NIV_OBLIGATION_INTRODUCTION, 0); +print '
    '.$langs->trans("INTRACOMMREPORT_NIV_OBLIGATION_EXPEDITION").''; +print $form->selectarray('INTRACOMMREPORT_NIV_OBLIGATION_EXPEDITION', $arraychoices, $conf->global->INTRACOMMREPORT_NIV_OBLIGATION_EXPEDITION, 0); +print '
    '.$langs->trans("INTRACOMMREPORT_CATEG_FRAISDEPORT").''; +print $formother->select_categories(0, $conf->global->INTRACOMMREPORT_CATEG_FRAISDEPORT, 'INTRACOMMREPORT_CATEG_FRAISDEPORT'); +print '
    '; + + +print load_fiche_titre($langs->trans("Parameters").' (DES)'); + +print ''; +print ''; +print ''; +print ''; +print ''; + +foreach ($list_DES as $key) +{ + print ''; + + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + + print ''; +} + +print '
    '.$langs->trans("Description").''.$langs->trans("Value").'
    '.$label.''; + print ''; + print '
    '; + +print '
    '; +print '
    '; +print ''; +print '
    '; +print '
    '; + +print ''; + +dol_fiche_end(); + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/intracommreport/card.php b/htdocs/intracommreport/card.php new file mode 100644 index 00000000000..01cc99574f7 --- /dev/null +++ b/htdocs/intracommreport/card.php @@ -0,0 +1,330 @@ + + * Copyright (C) 2019-2020 Open-DSI + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/intracommreport/card.php + * \ingroup Intracomm report + * \brief Page to manage intracomm report export + */ +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/intracommreport/class/intracommreport.class.php'; + +$langs->loadLangs(array("intracommreport")); + +$action = GETPOST('action'); +$exporttype = GETPOST('exporttype'); // DEB ou DES +if (empty($exporttype)) $exporttype = 'deb'; + +$form = new Form($db); +$formother = new FormOther($db); +$year = GETPOST('year'); +$month = GETPOST('month'); +$type_declaration = GETPOST('type'); +$backtopage=GETPOST('backtopage', 'alpha'); + +/* + * Actions + */ + +if ($user->rights->intracommreport->delete && $action == 'confirm_delete' && $confirm == 'yes') +{ + $result=$object->delete($id, $user); + if ($result > 0) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + else { + header("Location: list.php"); + exit; + } + } + else { + $errmesg=$object->error; + } +} + +if ($action == 'add' && $user->rights->intracommreport->write) { + $object->label = trim($label); + $object->type = trim($type); + $object->type_declaration = (int) $statut; + $object->subscription = (int) $subscription; + + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error++; + + if (empty($object->label)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); + } + else { + $sql = "SELECT libelle FROM ".MAIN_DB_PREFIX."adherent_type WHERE libelle='".$db->escape($object->label)."'"; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + } + if ($num) { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorLabelAlreadyExists", $login), null, 'errors'); + } + } + + if (! $error) + { + $id=$object->create($user); + if ($id > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } + else { + $action = 'create'; + } +} + +/* + * View + */ + +// Creation mode +if ($action == 'create') +{ + $title = $langs->trans("IntracommReportTitle"); + llxHeader("", $title); + print load_fiche_titre($langs->trans("IntracommReportTitle")); + + print '
    '; + print ''; + print ''; + + dol_fiche_head(); + + print ''; + + // Label + print ''; + + // Declaration + $declaration["deb"] = $langs->trans("DEB"); + $declaration["des"] = $langs->trans("DES"); + print '\n"; + + // Analysis period + print ''; + print ''; + print ''; + print ''; + + // Type of declaration + $typeOfDeclaration["introduction"] = $langs->trans("Introduction"); + $typeOfDeclaration["expedition"] = $langs->trans("Expedition"); + print '\n"; + + print '
    '.$langs->trans("Label").'
    '.$langs->trans("Declaration")."\n"; + print $form->selectarray("declaration", $declaration, GETPOST('declaration', 'alpha')?GETPOST('declaration', 'alpha'):$object->declaration, 0); + print "
    '; + print $langs->trans("AnalysisPeriod"); + print ''; + print $formother->select_month($month ? date('M') : $month, 'month', 0, 1, 'widthauto valignmiddle '); + print $formother->select_year($year ? date('Y') : $year, 'year', 0, 3, 3); + print '
    '.$langs->trans("TypeOfDeclaration")."\n"; + print $form->selectarray("type_declaration", $typeOfDeclaration, GETPOST('type_declaration', 'alpha')?GETPOST('type_declaration', 'alpha'):$object->type_declaration, 0); + print "
    '; + + dol_fiche_end(); + + print '
    '; + print '     '; + print '
    '; + + print '
    '; +} + +if ($id > 0 && $action != 'edit') { + /* ************************************************************************** */ + /* */ + /* View mode */ + /* */ + /* ************************************************************************** */ + $res = $object->fetch($id); + if ($res < 0) { + dol_print_error($db, $object->error); + exit; + } + + /* + * Show tabs + */ + $head = intracommreport_prepare_head($object); + + dol_fiche_head($head, 'general', $langs->trans("IntracommReport"), -1, 'user'); + + // Confirm remove report + if ($action == 'delete') { + $formquestion = array(); + if ($backtopage) { + $formquestion[] = array( + 'type' => 'hidden', + 'name' => 'backtopage', + 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]) + ); + } + print $form->formconfirm("card.php?rowid=" . $id, $langs->trans("DeleteReport"), + $langs->trans("ConfirmDeleteReport"), "confirm_delete", $formquestion, 'no', 1); + } + + $linkback = '' . $langs->trans("BackToList") . ''; + + dol_banner_tab($object, 'rowid', $linkback); + + print '
    '; + print '
    '; + + print '
    '; + print ''; + + // Type + print '\n"; + + // Analysis Period + print ''; + print ''; + + // Type of Declaration + print ''; + print ''; + + print "
    ' . $langs->trans("Type") . '' . $object->declaration . "
    ' . $langs->trans("AnalysisPeriod") . '' . $object->period . '
    ' . $langs->trans("TypeOfDeclaration") . '' . $object->type_declaration . '
    \n"; + + print "
    \n"; + print '
    '; + + dol_fiche_end(); +} + + /* + switch($action) { + case 'generateXML': + $obj = new TDebProdouane($PDOdb); + $obj->load($PDOdb, GETPOST('id_declaration')); + $obj->generateXMLFile(); + break; + case 'list': + _liste($exporttype); + break; + case 'export': + if ($exporttype == 'deb') _export_xml_deb($type_declaration, $year, str_pad($month, 2, 0, STR_PAD_LEFT)); + else _export_xml_des($type_declaration, $year, str_pad($month, 2, 0, STR_PAD_LEFT)); + default: + if ($exporttype == 'deb') _print_form_deb(); + else _print_form_des(); + break; + } + + function _print_form_des() + { + global $langs, $formother, $year, $month, $type_declaration; + + $title = $langs->trans("IntracommReportDESTitle"); + llxHeader("", $title); + print load_fiche_titre($langs->trans("IntracommReportDESTitle")); + + dol_fiche_head(); + + print '
    '; + print ''; + print ''; + print ''; + print ''; // Permet d'utiliser le bon select de la requête sql + + print ''; + + print ''; + + print ''; + print ''; + print ''; + print ''; + + print '
    '; + print 'Paramètres de l\'export'; + print '
    Période d\'analyse'; + $TabMonth = array(); + for($i=1;$i<=12;$i++) $TabMonth[$i] = $langs->trans('Month'.str_pad($i, 2, 0, STR_PAD_LEFT)); + //print $ATMform->combo('','month', $TabMonth, empty($month) ? date('m') : $month); + print $formother->selectyear(empty($year) ? date('Y') : $year,'year',0, 20, 5); + print '
    '; + + print '
    '; + print ''; + print '
    '; + + print '
    '; + } + + function _export_xml_deb($type_declaration, $period_year, $period_month) { + + global $db, $conf; + + $obj = new TDebProdouane($db); + $obj->entity = $conf->entity; + $obj->mode = 'O'; + $obj->periode = $period_year.'-'.$period_month; + $obj->type_declaration = $type_declaration; + $obj->numero_declaration = $obj->getNextNumeroDeclaration(); + $obj->content_xml = $obj->getXML('O', $type_declaration, $period_year.'-'.$period_month); + if(empty($obj->errors)) { + $obj->save($PDOdb); + $obj->generateXMLFile(); + } + else setEventMessage($obj->errors, 'warnings'); + } + + function _export_xml_des($type_declaration, $period_year, $period_month) { + + global $PDOdb, $conf; + + $obj = new TDebProdouane($PDOdb); + $obj->entity = $conf->entity; + $obj->periode = $period_year.'-'.$period_month; + $obj->type_declaration = $type_declaration; + $obj->exporttype = 'des'; + $obj->numero_declaration = $obj->getNextNumeroDeclaration(); + $obj->content_xml = $obj->getXMLDes($period_year, $period_month, $type_declaration); + if(empty($obj->errors)) { + $obj->save($PDOdb); + $obj->generateXMLFile(); + } + else setEventMessage($obj->errors, 'warnings'); + } + */ + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/intracommreport/class/index.html b/htdocs/intracommreport/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/intracommreport/class/intracommreport.class.php b/htdocs/intracommreport/class/intracommreport.class.php new file mode 100644 index 00000000000..b07d26150d6 --- /dev/null +++ b/htdocs/intracommreport/class/intracommreport.class.php @@ -0,0 +1,423 @@ + + * Copyright (C) 2019-2020 Open-DSI + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/intracommreport/class/intracommreport.class.php + * \ingroup Intracomm report + * \brief File of class to manage intracomm report + */ +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; + +/** + * Class to manage intracomm report + */ +class IntracommReport extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element='intracommreport'; + + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element='intracommreport'; + + /** + * @var int Field with ID of parent key if this field has a parent + */ + public $fk_element='fk_intracommreport'; + + /** + * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + * @var int + */ + public $ismultientitymanaged = 1; + + /** + * DEB - Product + */ + const TYPE_DEB = 0; + + /** + * DES - Service + */ + const TYPE_DES = 1; + + static $type = array( + 'introduction'=>'Introduction' + ,'expedition'=>'Expédition' + ); + + /** + * Constructor + * + * @param DoliDB $db Database handle + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + $this->exporttype = 'deb'; + } + + /** + * Generate XML file + * + * @param int $mode O for create, R for regenerate (Look always 0 ment toujours 0 within the framework of XML exchanges according to documentation) + * @param string $type Declaration type by default - introduction or expedition (always 'expedition' for Des) + * @param string $period_reference Period of reference + * @return void + */ + public function getXML($mode = 'O', $type = 'introduction', $period_reference = '') + { + + global $conf, $mysoc; + + /**************Construction de quelques variables********************/ + $party_id = substr(strtr($mysoc->tva_intra, array(' '=>'')), 0, 4).$mysoc->idprof2; + $declarant = substr($mysoc->managers, 0, 14); + $id_declaration = self::getNumeroDeclaration($this->numero_declaration); + /********************************************************************/ + + /**************Construction du fichier XML***************************/ + $e = new SimpleXMLElement(''); + + $enveloppe = $e->addChild('Envelope'); + $enveloppe->addChild('envelopeId', $conf->global->INTRACOMMREPORT_NUM_AGREMENT); + $date_time = $enveloppe->addChild('DateTime'); + $date_time->addChild('date', date('Y-m-d')); + $date_time->addChild('time', date('H:i:s')); + $party = $enveloppe->addChild('Party'); + $party->addAttribute('partType', $conf->global->INTRACOMMREPORT_TYPE_ACTEUR); + $party->addAttribute('partyRole', $conf->global->INTRACOMMREPORT_ROLE_ACTEUR); + $party->addChild('partyId', $party_id); + $party->addChild('partyName', $declarant); + $enveloppe->addChild('softwareUsed', 'Dolibarr'); + $declaration = $enveloppe->addChild('Declaration'); + $declaration->addChild('declarationId', $id_declaration); + $declaration->addChild('referencePeriod', $period_reference); + if ($conf->global->INTRACOMMREPORT_TYPE_ACTEUR === 'PSI') $psiId = $party_id; + else $psiId = 'NA'; + $declaration->addChild('PSIId', $psiId); + $function = $declaration->addChild('Function'); + $functionCode = $function->addChild('functionCode', $mode); + $declaration->addChild('declarationTypeCode', $conf->global->{'INTRACOMMREPORT_NIV_OBLIGATION_'.strtoupper($type)}); + $declaration->addChild('flowCode', ($type == 'introduction' ? 'A' : 'D')); + $declaration->addChild('currencyCode', $conf->global->MAIN_MONNAIE); + /********************************************************************/ + + /**************Ajout des lignes de factures**************************/ + $res = self::addItemsFact($declaration, $type, $period_reference); + /********************************************************************/ + + $this->errors = array_unique($this->errors); + + if (!empty($res)) return $e->asXML(); + else return 0; + } + + /** + * Generate XMLDes file + * + * @param int $period_year Year of declaration + * @param int $period_month Month of declaration + * @param string $type_declaration Declaration type by default - introduction or expedition (always 'expedition' for Des) + * @return void + */ + public function getXMLDes($period_year, $period_month, $type_declaration = 'expedition') + { + global $mysoc; + + $e = new SimpleXMLElement(''); + + $declaration_des = $e->addChild('declaration_des'); + $declaration_des->addChild('num_des', self::getDeclarationNumber($this->numero_declaration)); + $declaration_des->addChild('num_tvaFr', $mysoc->tva_intra); // /^FR[a-Z0-9]{2}[0-9]{9}$/ // Doit faire 13 caractères + $declaration_des->addChild('mois_des', $period_month); + $declaration_des->addChild('an_des', $period_year); + + /**************Ajout des lignes de factures**************************/ + $res = self::addItemsFact($declaration_des, $type_declaration, $period_year.'-'.$period_month, 'des'); + /********************************************************************/ + + $this->errors = array_unique($this->errors); + + if (!empty($res)) return $e->asXML(); + else return 0; + } + + /** + * Add line from invoice + * + * @param int $declaration Reference declaration + * @param string $type Declaration type by default - introduction or expedition (always 'expedition' for Des) + * @param int $period_reference Reference period + * @param string $exporttype deb=DEB, des=DES + * @return int <0 if KO, >0 if OK + */ + public function addItemsFact(&$declaration, $type, $period_reference, $exporttype = 'deb') + { + global $conf; + + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + + $sql = $this->getSQLFactLines($type, $period_reference, $exporttype); + + $resql = $this->db->query($sql); + + if ($resql) { + $i=1; + + if (empty($resql->num_rows)) { + $this->errors[] = 'No data for this period'; + return 0; + } + + if ($exporttype == 'deb' && $conf->global->INTRACOMMREPORT_CATEG_FRAISDEPORT > 0) { + $categ_fraisdeport = new Categorie(); + $categ_fraisdeport->fetch($conf->global->INTRACOMMREPORT_CATEG_FRAISDEPORT); + $TLinesFraisDePort = array(); + } + + while ($res = $this->db->fetch_object($resql)) { + if ($exporttype == 'des') + { + $this->addItemXMlDes($declaration, $res, $i); + } else { + if (empty($res->fk_pays)) { + // We don't stop the loop because we want to know all the third parties who don't have an informed country + $this->errors[] = 'Country not filled in for the third party '.$res->nom.''; + } else { + if ($conf->global->INTRACOMMREPORT_CATEG_FRAISDEPORT > 0 && $categ_fraisdeport->containsObject('product', $res->id_prod)) { + $TLinesFraisDePort[] = $res; + } else $this->addItemXMl($declaration, $res, $i, ''); + } + } + + $i++; + } + + if (!empty($TLinesFraisDePort)) $this->addItemFraisDePort($declaration, $TLinesFraisDePort, $type, $categ_fraisdeport, $i); + + if (count($this->errors) > 0) return 0; + } + + return 1; + } + + /** + * Add invoice line + * + * @param string $type Declaration type by default - introduction or expedition (always 'expedition' for Des) + * @param int $period_reference Reference declaration + * @param string $exporttype deb=DEB, des=DES + * @return int <0 if KO, >0 if OK + */ + public function getSQLFactLines($type, $period_reference, $exporttype = 'deb') + { + global $mysoc, $conf; + + if ($type=='expedition' || $exporttype=='des') { + $sql = 'SELECT f.facnumber, f.total as total_ht'; + $table = 'facture'; + $table_extraf = 'facture_extrafields'; + $tabledet = 'facturedet'; + $field_link = 'fk_facture'; + } + else { // Introduction + $sql = 'SELECT f.ref_supplier as facnumber, f.total_ht'; + $table = 'facture_fourn'; + $table_extraf = 'facture_fourn_extrafields'; + $tabledet = 'facture_fourn_det'; + $field_link = 'fk_facture_fourn'; + } + $sql.= ', l.fk_product, l.qty + , p.weight, p.rowid as id_prod, p.customcode + , s.rowid as id_client, s.nom, s.zip, s.fk_pays, s.tva_intra + , c.code + , ext.mode_transport + FROM '.MAIN_DB_PREFIX.$tabledet.' l + INNER JOIN '.MAIN_DB_PREFIX.$table.' f ON (f.rowid = l.'.$field_link.') + LEFT JOIN '.MAIN_DB_PREFIX.$table_extraf.' ext ON (ext.fk_object = f.rowid) + INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = l.fk_product) + INNER JOIN '.MAIN_DB_PREFIX.'societe s ON (s.rowid = f.fk_soc) + LEFT JOIN '.MAIN_DB_PREFIX.'c_country c ON (c.rowid = s.fk_pays) + WHERE f.fk_statut > 0 + AND l.product_type = '.($exporttype == 'des' ? 1 : 0).' + AND f.entity = '.$conf->entity.' + AND (s.fk_pays <> '.$mysoc->country_id.' OR s.fk_pays IS NULL) + AND f.datef BETWEEN "'.$period_reference.'-01" AND "'.$period_reference.'-'.date('t').'"'; + + return $sql; + } + + /** + * Add item for DEB + * + * @param int $declaration Reference declaration + * @param int $res Result of request SQL + * @param int $i Line Id + * @param string $code_douane_spe Specific customs authorities code + * @return void + */ + public function addItemXMl(&$declaration, &$res, $i, $code_douane_spe = '') + { + $item = $declaration->addChild('Item'); + $item->addChild('ItemNumber', $i); + $cn8 = $item->addChild('CN8'); + if (empty($code_douane_spe)) $code_douane = $res->customcode; + else $code_douane = $code_douane_spe; + $cn8->addChild('CN8Code', $code_douane); + if (!empty($res->tva_intra)) $item->addChild('partnerId', $res->tva_intra); + $item->addChild('MSConsDestCode', $res->code); // code iso pays client + $item->addChild('netMass', $res->weight * $res->qty); // Poids du produit + $item->addChild('quantityInSU', $res->qty); // Quantité de produit dans la ligne + $item->addChild('invoicedAmount', round($res->total_ht)); // Montant total ht de la facture (entier attendu) + $item->addChild('invoicedNumber', $res->facnumber); // Numéro facture + $item->addChild('statisticalProcedureCode', '11'); + $nature_of_transaction = $item->addChild('NatureOfTransaction'); + $nature_of_transaction->addChild('natureOfTransactionACode', 1); + $nature_of_transaction->addChild('natureOfTransactionBCode', 1); + $item->addChild('modeOfTransportCode', $res->mode_transport); + $item->addChild('regionCode', substr($res->zip, 0, 2)); + } + + /** + * Add item for DES + * + * @param int $declaration Reference declaration + * @param int $res Result of request SQL + * @param int $i Line Id + * @return void + */ + public function addItemXMlDes($declaration, &$res, $i) + { + $item = $declaration->addChild('ligne_des'); + $item->addChild('numlin_des', $i); + $item->addChild('valeur', round($res->total_ht)); // Total amount excl. tax of the invoice (whole amount expected) + $item->addChild('partner_des', $res->tva_intra); // Represents the foreign customer's VAT number + } + + /** + * This function adds an item by retrieving the customs code of the product with the highest amount in the invoice + * + * @param int $declaration Reference declaration + * @param int $TLinesFraisDePort Data of shipping costs line + * @param string $type Declaration type by default - introduction or expedition (always 'expedition' for Des) + * @param int $categ_fraisdeport Id of category of shipping costs + * @param int $i Line Id + * @return void + */ + public function addItemFraisDePort(&$declaration, &$TLinesFraisDePort, $type, &$categ_fraisdeport, $i) + { + + global $conf; + + if ($type=='expedition') { + $table = 'facture'; + $tabledet = 'facturedet'; + $field_link = 'fk_facture'; + $more_sql = 'f.facnumber'; + } else { // Introduction + $table = 'facture_fourn'; + $tabledet = 'facture_fourn_det'; + $field_link = 'fk_facture_fourn'; + $more_sql = 'f.ref_supplier'; + } + + foreach ($TLinesFraisDePort as $res) { + $sql = 'SELECT p.customcode + FROM '.MAIN_DB_PREFIX.$tabledet.' d + INNER JOIN '.MAIN_DB_PREFIX.$table.' f ON (f.rowid = d.'.$field_link.') + INNER JOIN '.MAIN_DB_PREFIX.'product p ON (p.rowid = d.fk_product) + WHERE d.fk_product IS NOT NULL + AND f.entity = '.$conf->entity.' + AND '.$more_sql.' = "'.$res->facnumber.'" + AND d.total_ht = + ( + SELECT MAX(d.total_ht) + FROM '.MAIN_DB_PREFIX.$tabledet.' d + INNER JOIN '.MAIN_DB_PREFIX.$table.' f ON (f.rowid = d.'.$field_link.') + WHERE d.fk_product IS NOT NULL + AND '.$more_sql.' = "'.$res->facnumber.'" + AND d.fk_product NOT IN + ( + SELECT fk_product + FROM '.MAIN_DB_PREFIX.'categorie_product + WHERE fk_categorie = '.$categ_fraisdeport->id.' + ) + )'; + + $resql = $this->db->query($sql); + $ress = $this->db->fetch_object($resql); + + $this->addItemXMl($declaration, $res, $i, $ress->customcode); + + $i++; + } + } + + /** + * Return next reference of declaration not already used (or last reference) + * + * @return string free ref or last ref + */ + public function getNextDeclarationNumber() + { + $resql = $this->db->query('SELECT MAX(numero_declaration) as max_numero_declaration FROM '.$this->get_table().' WHERE exporttype="'.$this->exporttype.'"'); + if ($resql) $res = $this->db->fetch_object($resql); + + return ($res->max_numero_declaration + 1); + } + + /** + * Verify declaration number. Positive integer of a maximum of 6 characters recommended by the documentation + * + * @param int $number Number to verify / convert + * @return int Number + */ + public static function getDeclarationNumber($number) + { + return str_pad($number, 6, 0, STR_PAD_LEFT); + } + + /** + * Generate XML file + * + * @return void + */ + public function generateXMLFile() + { + + $name = $this->periode.'.xml'; + $fname = sys_get_temp_dir().'/'.$name; + $f = fopen($fname, 'w+'); + fwrite($f, $this->content_xml); + fclose($f); + + header('Content-Description: File Transfer'); + header('Content-Type: application/xml'); + header('Content-Disposition: attachment; filename="'.$name.'"'); + header('Expires: 0'); + header('Cache-Control: must-revalidate'); + header('Pragma: public'); + header('Content-Length: ' . filesize($fname)); + readfile($fname); + exit; + } +} diff --git a/htdocs/intracommreport/index.html b/htdocs/intracommreport/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/intracommreport/list.php b/htdocs/intracommreport/list.php new file mode 100644 index 00000000000..6f7ecbc2580 --- /dev/null +++ b/htdocs/intracommreport/list.php @@ -0,0 +1,492 @@ + + * Copyright (C) 2019-2020 Open-DSI + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/intracommreport/list.php + * \ingroup Intracomm Report + * \brief Page to list intracomm report + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/intracommreport/class/intracommreport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('intracommreport')); + +$action=GETPOST('action', 'alpha'); +$massaction=GETPOST('massaction', 'alpha'); +$show_files=GETPOST('show_files', 'int'); +$confirm=GETPOST('confirm', 'alpha'); +$toselect = GETPOST('toselect', 'array'); + +$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); +$search_ref=GETPOST("search_ref", 'alpha'); +$search_type = GETPOST("search_type", 'int'); +$fourn_id = GETPOST("fourn_id", 'int'); +$catid = GETPOST('catid', 'int'); +$optioncss = GETPOST('optioncss', 'alpha'); +$type=GETPOST("type", "int"); + +$diroutputmassaction=$conf->product->dir_output . '/temp/massgeneration/'.$user->id; + +$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = (GETPOST("page", 'int')?GETPOST("page", 'int'):0); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) $sortfield="i.ref"; +if (! $sortorder) $sortorder="ASC"; + +// Initialize context for list +$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'intracommreportlist'; +if ((string) $type == '1') { $contextpage='DESlist'; if ($search_type=='') $search_type='1'; } +if ((string) $type == '0') { $contextpage='DEBlist'; if ($search_type=='') $search_type='0'; } + +// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks +$object=new IntracommReport($db); +$hookmanager->initHooks(array('intracommreportlist')); +$extrafields = new ExtraFields($db); +$form=new Form($db); + +/* +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('intracommreport'); +$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +*/ + +if (empty($action)) $action='list'; + +// Get object canvas (By default, this is not defined, so standard usage of dolibarr) +$canvas=GETPOST("canvas"); +$objcanvas=null; +if (! empty($canvas)) +{ + require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; + $objcanvas = new Canvas($db, $action); + $objcanvas->getCanvas('product', 'list', $canvas); +} + +// Security check +/* +if ($search_type=='0') $result=restrictedArea($user, 'produit', '', '', '', '', '', $objcanvas); +elseif ($search_type=='1') $result=restrictedArea($user, 'service', '', '', '', '', '', $objcanvas); +else $result=restrictedArea($user, 'produit|service', '', '', '', '', '', $objcanvas); +*/ + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array( + 'i.ref'=>"Ref", + 'pfi.ref_fourn'=>"RefSupplier", + 'i.label'=>"ProductLabel", + 'i.description'=>"Description", + "i.note"=>"Note", +); + +$isInEEC=isInEEC($mysoc); + +// Definition of fields for lists +$arrayfields=array( + 'i.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'i.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'i.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->produit->enabled) && ! empty($conf->service->enabled))), +); +/* +// Extra fields +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) +{ + foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + { + 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])); + } +} +*/ +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) +{ + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers + { + $sall=""; + $search_ref=""; + $search_label=""; + //$search_type=''; // There is 2 types of list: a list of product and a list of services. No list with both. So when we clear search criteria, we must keep the filter on type. + + $show_childproducts = ''; + $search_array_options=array(); + } + + // Mass actions + $objectclass='Product'; + if ((string) $search_type == '1') { $objectlabel='Services'; } + if ((string) $search_type == '0') { $objectlabel='Products'; } + + $permtoread = $user->rights->produit->lire; + $permtodelete = $user->rights->produit->supprimer; + $uploaddir = $conf->product->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + +/* + * View + */ +$formother=new FormOther($db); + +$title=$langs->trans('IntracommReportList'.$type); + +$sql = 'SELECT DISTINCT i.rowid, i.type_declaration, i.type_export, i.period, i.mode, i.entity'; +/* +// Add fields from extrafields +if (! empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); +} +*/ +// Add fields from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +$sql.= ' FROM '.MAIN_DB_PREFIX.'intracommreport as i'; + +// if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."intracommreport_extrafields as ef on (i.rowid = ef.fk_object)"; + +$sql.= ' WHERE i.entity IN ('.getEntity('intracommreport').')'; + +if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); +// if the type is not 1, we show all products (type = 0,2,3) +if (dol_strlen($search_type) && $search_type != '-1') +{ + if ($search_type == 1) $sql.= " AND i.type = 1"; + else $sql.= " AND i.type = 0"; +} + +/* +if ($search_ref) $sql .= natural_search('i.ref', $search_ref); +if ($search_label) $sql .= natural_search('i.label', $search_label); +if ($search_barcode) $sql .= natural_search('i.barcode', $search_barcode); +if (isset($search_tosell) && dol_strlen($search_tosell) > 0 && $search_tosell!=-1) $sql.= " AND i.tosell = ".$db->escape($search_tosell); +if (isset($search_tobuy) && dol_strlen($search_tobuy) > 0 && $search_tobuy!=-1) $sql.= " AND i.tobuy = ".$db->escape($search_tobuy); +if (dol_strlen($canvas) > 0) $sql.= " AND i.canvas = '".$db->escape($canvas)."'"; +*/ + +/* +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +*/ +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +$sql.= " GROUP BY i.rowid"; + +/* +// Add fields from extrafields +if (! empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); +} +*/ + +// Add fields from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +$sql.= $db->order($sortfield, $sortorder); + +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } +} + +$sql.= $db->plimit($limit + 1, $offset); + +$resql = $db->query($sql); + +if ($resql) +{ + $num = $db->num_rows($resql); + + $arrayofselected=is_array($toselect)?$toselect:array(); + + $helpurl='EN:Module_IntracommReport|FR:Module_ProDouane'; + llxHeader('', $title, $helpurl, ''); + + // Displays product removal confirmation + if (GETPOST('delreport')) { + setEventMessages($langs->trans("IntracommReportDeleted", GETPOST('delreport')), null, 'mesgs'); + } + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); + if ($sall) $param.="&sall=".urlencode($sall); + if ($search_ref) $param="&search_ref=".urlencode($search_ref); + if ($search_label) $param.="&search_label=".urlencode($search_label); + + // Add $param from extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + + // List of mass actions available + $arrayofmassactions = array( + 'generate_doc'=>$langs->trans("ReGeneratePDF"), + //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + ); + if ($user->rights->intracommreport->delete) $arrayofmassactions['predelete']="".$langs->trans("Delete"); + if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + + $newcardbutton=''; + if ($user->rights->intracommreport->write) + { + $newcardbutton.= dolGetButtonTitle($langs->trans("NewDeclaration"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/intracommreport/card.php?action=create&type='.$type); + } + + print '
    '; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (empty($arrayfields['i.fk_product_type']['checked'])) print ''; + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, $newcardbutton, '', $limit); + + $topicmail="Information"; + $modelmail="product"; + $objecttmp=new IntracommReport($db); + $trackid='prod'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + + if ($sall) + { + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print '
    '.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
    '; + } + + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter.=$hookmanager->resPrint; + else $moreforfilter=$hookmanager->resPrint; + + if ($moreforfilter) + { + print '
    '; + print $moreforfilter; + print '
    '; + } + + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + + print '
    '; + print ''."\n"; + + // Lines with input filters + print ''; + if (! empty($arrayfields['i.ref']['checked'])) + { + print ''; + } + if (! empty($arrayfields['i.label']['checked'])) + { + print ''; + } + // Type + // Type (customer/prospect/supplier) + if (!empty($arrayfields['customerorsupplier']['checked'])) + { + print ''; + } + + if (! empty($arrayfields['i.fk_product_type']['checked'])) + { + print ''; + } + + /* + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + */ + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['i.datec']['checked'])) + { + print ''; + } + // Date modification + if (! empty($arrayfields['i.tms']['checked'])) + { + print ''; + } + print ''; + + print ''; + + print ''; + if (! empty($arrayfields['i.ref']['checked'])) { + print_liste_field_titre($arrayfields['i.ref']['label'], $_SERVER["PHP_SELF"], "i.ref", "", $param, "", $sortfield, $sortorder); + } + if (! empty($arrayfields['i.label']['checked'])) { + print_liste_field_titre($arrayfields['i.label']['label'], $_SERVER["PHP_SELF"], "i.label", "", $param, "", $sortfield, $sortorder); + } + if (! empty($arrayfields['i.fk_product_type']['checked'])) { + print_liste_field_titre($arrayfields['i.fk_product_type']['label'], $_SERVER["PHP_SELF"], "i.fk_product_type", "", $param, "", $sortfield, $sortorder); + } + + /* + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + */ + // Hook fields + $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); + $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['i.datec']['checked'])) { + print_liste_field_titre($arrayfields['i.datec']['label'], $_SERVER["PHP_SELF"], "i.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (! empty($arrayfields['i.tms']['checked'])) { + print_liste_field_titre($arrayfields['i.tms']['label'], $_SERVER["PHP_SELF"], "i.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); + print "\n"; + + + $intracommreport_static = new IntracommReport($db); + + $i = 0; + $totalarray=array(); + while ($i < min($num, $limit)) + { + $obj = $db->fetch_object($resql); + + $intracommreport_static->id = $obj->rowid; + $intracommreport_static->ref = $obj->ref; + $intracommreport_static->ref_fourn = $obj->ref_supplier; + $intracommreport_static->label = $obj->label; + $intracommreport_static->type = $obj->fk_product_type; + $intracommreport_static->status_buy = $obj->tobuy; + $intracommreport_static->status = $obj->tosell; + $intracommreport_static->status_batch = $obj->tobatch; + $intracommreport_static->entity = $obj->entity; + + print ''; + + // Ref + if (! empty($arrayfields['i.ref']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + // Label + if (! empty($arrayfields['i.label']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type + if (! empty($arrayfields['i.fk_product_type']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action + print ''; + if (! $i) $totalarray['nbfield']++; + + print "\n"; + $i++; + } + + $db->free($resql); + + print "
    '; + print ''; + print ''; + print ''; + print ''; + if ($type != '') print ''; + print $formcompany->selectProspectCustomerType($search_type, 'search_type', 'search_type', 'list'); + print ''; + $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); + print $form->selectarray('search_type', $array, $search_type); + print ''; + print ''; + print ''; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '
    '; + print $intracommreport_static->getNomUrl(1); + print "'.dol_trunc($obj->label, 80).''.$obj->fk_product_type.''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    "; + print "
    "; + print '
    '; +} +else { + dol_print_error($db); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 3d9b36d58b6..24255577b11 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -20,11 +20,12 @@ CantSuggest=Can't suggest AccountancySetupDoneFromAccountancyMenu=Most setup of the accountancy is done from the menu %s ConfigAccountingExpert=Configuration of the module accounting (double entry) Journalization=Journalization -Journaux=Journals +Journals=Journals JournalFinancial=Financial journals BackToChartofaccounts=Return chart of accounts Chartofaccounts=Chart of accounts -ChartOfSubaccounts=Chart of subaccounts +ChartOfSubaccounts=Chart of individual accounts +ChartOfIndividualAccountsOfSubsidiaryLedger=Chart of individual accounts of the subsidiary ledger CurrentDedicatedAccountingAccount=Current dedicated account AssignDedicatedAccountingAccount=New account to assign InvoiceLabel=Invoice label @@ -44,7 +45,9 @@ CountriesInEEC=Countries in EEC CountriesNotInEEC=Countries not in EEC CountriesInEECExceptMe=Countries in EEC except %s CountriesExceptMe=All countries except %s -AccountantFiles=Export accounting documents +AccountantFiles=Export source documents +ExportAccountingSourceDocHelp=With this tool, you can export the source events (list and PDFs) that were used to generate your accountancy. To export your journals, use the menu entry %s - %s. +VueByAccountAccounting=View by accounting account MainAccountForCustomersNotDefined=Main accounting account for customers not defined in setup MainAccountForSuppliersNotDefined=Main accounting account for vendors not defined in setup @@ -80,7 +83,7 @@ AccountancyAreaDescAnalyze=STEP %s: Add or edit existing transactions and genera AccountancyAreaDescClosePeriod=STEP %s: Close period so we can't make modification in a future. -TheJournalCodeIsNotDefinedOnSomeBankAccount=A mandatory step in setup was not complete (accounting code journal not defined for all bank accounts) +TheJournalCodeIsNotDefinedOnSomeBankAccount=A mandatory step in setup has not been completed (accounting code journal not defined for all bank accounts) Selectchartofaccounts=Select active chart of accounts ChangeAndLoad=Change and load Addanaccount=Add an accounting account @@ -90,8 +93,8 @@ SubledgerAccount=Subledger account SubledgerAccountLabel=Subledger account label ShowAccountingAccount=Show accounting account ShowAccountingJournal=Show accounting journal -ShowAccountingAccountInBookKeeping=Show accounting account in ledger -ShowAccountingAccountInBookKeepingByAccount=Show accounting account in ledger by account +ShowAccountingAccountInLedger=Show accounting account in ledger +ShowAccountingAccountInJournals=Show accounting account in journals AccountAccountingSuggest=Accounting account suggested MenuDefaultAccounts=Default accounts MenuBankAccounts=Bank accounts @@ -113,7 +116,7 @@ ExpenseReportsVentilation=Expense report binding CreateMvts=Create new transaction UpdateMvts=Modification of a transaction ValidTransaction=Validate transaction -WriteBookKeeping=Register transactions in Ledger +WriteBookKeeping=Register transactions in accounting Bookkeeping=Ledger AccountBalance=Account balance ObjectsRef=Source object ref @@ -209,12 +212,12 @@ ByPredefinedAccountGroups=By predefined groups ByPersonalizedAccountGroups=By personalized groups ByYear=By year NotMatch=Not Set -DeleteMvt=Delete Ledger lines +DeleteMvt=Delete some operation lines from accounting DelMonth=Month to delete DelYear=Year to delete DelJournal=Journal to delete -ConfirmDeleteMvt=This will delete all lines of the Ledger for the year/month and/or from a specific journal (At least one criterion is required). You will have to reuse the feature 'Registration in accounting' to have the deleted record back in the ledger. -ConfirmDeleteMvtPartial=This will delete the transaction from the Ledger (all lines related to same transaction will be deleted) +ConfirmDeleteMvt=This will delete all operation lines of the accounting for the year/month and/or for a specific journal (At least one criterion is required). You will have to reuse the feature '%s' to have the deleted record back in the ledger. +ConfirmDeleteMvtPartial=This will delete the transaction from the accounting (all operation lines related to the same transaction will be deleted) FinanceJournal=Finance journal ExpenseReportsJournal=Expense reports journal DescFinanceJournal=Finance journal including all the types of payments by bank account diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 8d64fe1a8d6..e47390b9ce0 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -271,7 +271,7 @@ NoticePeriod=Notice period NewByMonth=New by month Emails=Emails EMailsSetup=Emails setup -EMailsDesc=This page allows you to override your default PHP parameters for email sending. In most cases on Unix/Linux OS, the PHP setup is correct and these parameters are unnecessary. +EMailsDesc=This page allows you to set parameters or options for email sending. EmailSenderProfiles=Emails sender profiles EMailsSenderProfileDesc=You can keep this section empty. If you enter some emails here, they will be added to the list of possible senders into the combobox when your write a new email. MAIN_MAIL_SMTP_PORT=SMTP/SMTPS Port (default value in php.ini: %s) @@ -480,9 +480,10 @@ ModuleCompanyCodeSupplierDigitaria=%s followed by the truncated supplier name by Use3StepsApproval=By default, Purchase Orders need to be created and approved by 2 different users (one step/user to create and one step/user to approve. Note that if user has both permission to create and approve, one step/user will be enough). You can ask with this option to introduce a third step/user approval, if amount is higher than a dedicated value (so 3 steps will be necessary: 1=validation, 2=first approval and 3=second approval if amount is enough).
    Set this to empty if one approval (2 steps) is enough, set it to a very low value (0.1) if a second approval (3 steps) is always required. UseDoubleApproval=Use a 3 steps approval when amount (without tax) is higher than... WarningPHPMail=WARNING: The setup to send emails from the application is using the default generic setup. It is often better to setup outgoing emails to use the email server of your Email Service Provider instead of the default setup for several reasons: -WarningPHPMailA=- Using the server of the Email Service Provider increase the trustability of your email, so it increase the deliverablity without being flagging as SPAM +WarningPHPMailA=- Using the server of the Email Service Provider increases the trustability of your email, so it increases the deliverablity without being flagged as SPAM WarningPHPMailB=- Some Email Service Providers (like Yahoo) do not allow you to send an email from another server than their own server. Your current setup uses the server of the application to send email and not the server of your email provider, so some recipients (the one compatible with the restrictive DMARC protocol), will ask your email provider if they can accept your email and some email providers (like Yahoo) may respond "no" because the server is not theirs, so few of your sent Emails may not be accepted for delivery (be careful also of your email provider's sending quota). WarningPHPMailC=- Using the SMTP server of your own Email Service Provider to send emails is also interesting so all emails sent from application will also be saved into your "Sent" directory of your mailbox. +WarningPHPMailD=If the method 'PHP Mail' is really the method you would like to use, you can remove this warning by adding the constant MAIN_HIDE_WARNING_TO_ENCOURAGE_SMTP_SETUP to 1 in Home - Setup - Other. WarningPHPMail2=If your email SMTP provider need to restrict email client to some IP addresses (very rare), this is the IP address of the mail user agent (MUA) for your ERP CRM application: %s. WarningPHPMailSPF=If the domain name in your sender email address is protected by a SPF record (ask you domain name registar), you must add the following IPs in the SPF record of the DNS of your domain: %s. ClickToShowDescription=Click to show description @@ -658,7 +659,7 @@ Module50200Desc=Offer customers a PayPal online payment page (PayPal account or Module50300Name=Stripe Module50300Desc=Offer customers a Stripe online payment page (credit/debit cards). This can be used to allow your customers to make ad-hoc payments or payments related to a specific Dolibarr object (invoice, order etc...) Module50400Name=Accounting (double entry) -Module50400Desc=Accounting management (double entries, support general and auxiliary ledgers). Export the ledger in several other accounting software formats. +Module50400Desc=Accounting management (double entries, support General and Subsidiary Ledgers). Export the ledger in several other accounting software formats. Module54000Name=PrintIPP Module54000Desc=Direct print (without opening the documents) using Cups IPP interface (Printer must be visible from server, and CUPS must be installed on server). Module55000Name=Poll, Survey or Vote @@ -978,6 +979,9 @@ Permission63003=Delete resources Permission63004=Link resources to agenda events Permission64001=Allow direct printing Permission67000=Allow printing of receipts +Permission68001=Read intracomm report +Permission68002=Create/modify intracomm report +Permission68004=Delete intracomm report Permission941601=Read receipts Permission941602=Create and modify receipts Permission941603=Validate receipts @@ -1023,6 +1027,8 @@ DictionaryHolidayTypes=Types of leave DictionaryOpportunityStatus=Lead status for project/lead DictionaryExpenseTaxCat=Expense report - Transportation categories DictionaryExpenseTaxRange=Expense report - Range by transportation category +DictionaryTransportMode=Intracomm report - Transport mode +TypeOfUnit=Type of unit SetupSaved=Setup saved SetupNotSaved=Setup not saved BackToModuleList=Back to Module list @@ -1891,7 +1897,7 @@ MailToSendReception=Receptions MailToThirdparty=Third parties MailToMember=Members MailToUser=Users -MailToProject=Projects page +MailToProject=Projects MailToTicket=Tickets ByDefaultInList=Show by default on list view YouUseLastStableVersion=You use the latest stable version @@ -2003,7 +2009,7 @@ DisabledResourceLinkContact=Disable feature to link a resource to contacts EnableResourceUsedInEventCheck=Enable feature to check if a resource is in use in an event ConfirmUnactivation=Confirm module reset OnMobileOnly=On small screen (smartphone) only -DisableProspectCustomerType=Disable the "Prospect + Customer" third party type (so third party must be Prospect or Customer but can't be both) +DisableProspectCustomerType=Disable the "Prospect + Customer" third party type (so third party must be "Prospect" or "Customer", but can't be both) MAIN_OPTIMIZEFORTEXTBROWSER=Simplify interface for blind person MAIN_OPTIMIZEFORTEXTBROWSERDesc=Enable this option if you are a blind person, or if you use the application from a text browser like Lynx or Links. MAIN_OPTIMIZEFORCOLORBLIND=Change interface's color for color blind person @@ -2058,5 +2064,7 @@ MeasuringScaleDesc=The scale is the number of places you have to move the decima TemplateAdded=Template added TemplateUpdated=Template updated TemplateDeleted=Template deleted -MailToSendEventPush=Template for event reminder emails +MailToSendEventPush=Event reminder email SwitchThisForABetterSecurity=Switching this value to %s is recommended for more security +DictionaryProductNature= Nature of product +CountryIfSpecificToOneCountry=Country (if specific to a given country) \ No newline at end of file diff --git a/htdocs/langs/en_US/agenda.lang b/htdocs/langs/en_US/agenda.lang index 4ab87aa8420..479155fb2a9 100644 --- a/htdocs/langs/en_US/agenda.lang +++ b/htdocs/langs/en_US/agenda.lang @@ -166,5 +166,4 @@ TimeType=Duration type ReminderType=Callback type AddReminder=Create an automatic reminder notification for this event ErrorReminderActionCommCreation=Error creating the reminder notification for this event -BrowserPush=Browser Notification -EventReminder=Event Reminder \ No newline at end of file +BrowserPush=Browser Notification \ No newline at end of file diff --git a/htdocs/langs/en_US/banks.lang b/htdocs/langs/en_US/banks.lang index 3cfa7ad2538..ffe5ee9ca1c 100644 --- a/htdocs/langs/en_US/banks.lang +++ b/htdocs/langs/en_US/banks.lang @@ -168,6 +168,7 @@ ShowVariousPayment=Show miscellaneous payment AddVariousPayment=Add miscellaneous payment VariousPaymentId=Miscellaneous payment ID VariousPaymentLabel=Miscellaneous payment label +ConfirmCloneVariousPayment=Confirm the clone of a miscellaneous payment SEPAMandate=SEPA mandate YourSEPAMandate=Your SEPA mandate FindYourSEPAMandate=This is your SEPA mandate to authorize our company to make direct debit order to your bank. Return it signed (scan of the signed document) or send it by mail to diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 923ce91d74a..98dc451b5bb 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -354,6 +354,7 @@ VATIntraManualCheck=You can also check manually on the European Commission websi ErrorVATCheckMS_UNAVAILABLE=Check not possible. Check service is not provided by the member state (%s). NorProspectNorCustomer=Not prospect, nor customer JuridicalStatus=Legal Entity Type +Workforce=Workforce Staff=Employees ProspectLevelShort=Potential ProspectLevel=Prospect potential @@ -458,4 +459,5 @@ MulticurrencyUsed=Use Multicurrency MulticurrencyCurrency=Currency InEEC=Europe (EEC) RestOfEurope=Rest of Europe (EEC) -OutOfEurope=Out of Europe (EEC) \ No newline at end of file +OutOfEurope=Out of Europe (EEC) +CurrentOutstandingBillLate=Current outstanding bill late diff --git a/htdocs/langs/en_US/cron.lang b/htdocs/langs/en_US/cron.lang index bb61ed13bbe..9921f21851d 100644 --- a/htdocs/langs/en_US/cron.lang +++ b/htdocs/langs/en_US/cron.lang @@ -47,6 +47,7 @@ CronNbRun=Number of launches CronMaxRun=Maximum number of launches CronEach=Every JobFinished=Job launched and finished +Scheduled=Scheduled #Page card CronAdd= Add jobs CronEvery=Execute job each @@ -57,7 +58,7 @@ CronNote=Comment CronFieldMandatory=Fields %s is mandatory CronErrEndDateStartDt=End date cannot be before start date StatusAtInstall=Status at module installation -CronStatusActiveBtn=Enable +CronStatusActiveBtn=Schedule CronStatusInactiveBtn=Disable CronTaskInactive=This job is disabled CronId=Id diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index e388c505663..47568f574fa 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -269,6 +269,7 @@ WarningYourLoginWasModifiedPleaseLogin=Your login was modified. For security pur WarningAnEntryAlreadyExistForTransKey=An entry already exists for the translation key for this language WarningNumberOfRecipientIsRestrictedInMassAction=Warning, number of different recipient is limited to %s when using the mass actions on lists WarningDateOfLineMustBeInExpenseReportRange=Warning, the date of line is not in the range of the expense report +WarningProjectDraft=Project is still in draft mode. Don't forget to validate it if you plan to use tasks. WarningProjectClosed=Project is closed. You must re-open it first. WarningSomeBankTransactionByChequeWereRemovedAfter=Some bank transaction were removed after that the receipt including them were generated. So nb of cheques and total of receipt may differ from number and total in list. WarningFailedToAddFileIntoDatabaseIndex=Warning, failed to add file entry into ECM database index table diff --git a/htdocs/langs/en_US/intracommreport.lang b/htdocs/langs/en_US/intracommreport.lang new file mode 100644 index 00000000000..73a2a22709d --- /dev/null +++ b/htdocs/langs/en_US/intracommreport.lang @@ -0,0 +1,40 @@ +Module68000Name = Intracomm report +Module68000Desc = Intracomm report management (Support for French DEB/DES format) +IntracommReportSetup = Intracommreport module setup +IntracommReportAbout = About intracommreport + +# Setup +INTRACOMMREPORT_NUM_AGREMENT=Numéro d'agrément (délivré par le CISD de rattachement) +INTRACOMMREPORT_TYPE_ACTEUR=Type d'acteur +INTRACOMMREPORT_ROLE_ACTEUR=Rôle joué par l'acteur +INTRACOMMREPORT_NIV_OBLIGATION_INTRODUCTION=Niveau d'obligation sur les introductions +INTRACOMMREPORT_NIV_OBLIGATION_EXPEDITION=Niveau d'obligation sur les expéditions +INTRACOMMREPORT_CATEG_FRAISDEPORT=Catégorie de services de type "Frais de port" + +INTRACOMMREPORT_NUM_DECLARATION=Numéro de déclarant + +# Menu +MenuIntracommReport=Intracomm report +MenuIntracommReportNew=New declaration +MenuIntracommReportList=List + +# View +NewDeclaration=New declaration +Declaration=Declaration +AnalysisPeriod=Analysis period +TypeOfDeclaration=Type of declaration +DEB=Goods exchange declaration (DEB) +DES=Services exchange declaration (DES) + +# Export page +IntracommReportTitle=Preparation of an XML file in ProDouane format + +# List +IntracommReportList=List of generated declarations +IntracommReportNumber=Numéro déclaration +IntracommReportPeriod=Période d'analyse +IntracommReportTypeDeclaration=Type de déclaration +IntracommReportDownload=Télécharger fichier XML + +# Invoice +IntracommReportTransportMode=Transport mode diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang index 7e34db3d8b8..a7223605ff0 100644 --- a/htdocs/langs/en_US/mails.lang +++ b/htdocs/langs/en_US/mails.lang @@ -163,9 +163,9 @@ AdvTgtCreateFilter=Create filter AdvTgtOrCreateNewFilter=Name of new filter NoContactWithCategoryFound=No contact/address with a category found NoContactLinkedToThirdpartieWithCategoryFound=No contact/address with a category found -OutGoingEmailSetup=Outgoing email setup -InGoingEmailSetup=Incoming email setup -OutGoingEmailSetupForEmailing=Outgoing email setup (for module %s) +OutGoingEmailSetup=Outgoing emails +InGoingEmailSetup=Incoming emails +OutGoingEmailSetupForEmailing=Outgoing emails (for module %s) DefaultOutgoingEmailSetup=Same configuration than the global Outgoing email setup Information=Information ContactsWithThirdpartyFilter=Contacts with third-party filter diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 427a5a80d45..1096b9857f1 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -490,6 +490,7 @@ By=By From=From FromDate=From FromLocation=From +at=at to=to To=to and=and @@ -1014,6 +1015,8 @@ SearchIntoCustomerShipments=Customer shipments SearchIntoExpenseReports=Expense reports SearchIntoLeaves=Leave SearchIntoTickets=Tickets +SearchIntoCustomerPayments=Customer payments +SearchIntoVendorPayments=Vendor payments SearchIntoMiscPayments=Miscellaneous payments CommentLink=Comments NbComments=Number of comments @@ -1096,3 +1099,4 @@ DateOfBirth=Date of birth SecurityTokenHasExpiredSoActionHasBeenCanceledPleaseRetry=Security token has expired, so action has been canceled. Please try again. UpToDate=Up-to-date OutOfDate=Out-of-date +EventReminder=Event Reminder \ No newline at end of file diff --git a/htdocs/langs/en_US/products.lang b/htdocs/langs/en_US/products.lang index 51f547dbdce..3077021aad6 100644 --- a/htdocs/langs/en_US/products.lang +++ b/htdocs/langs/en_US/products.lang @@ -339,6 +339,7 @@ UseProductFournDesc=Add a feature to define the descriptions of products defined ProductSupplierDescription=Vendor description for the product UseProductSupplierPackaging=Use packaging on supplier prices (recalculate quantities according to packaging set on supplier price when adding/updating line in supplier documents) PackagingForThisProduct=Packaging +PackagingForThisProductDesc=On supplier order, you will automaticly order this quantity (or a multiple of this quantity). Cannot be less than minimum buying quantity QtyRecalculatedWithPackaging=The quantity of the line were recalculated according to supplier packaging #Attributes diff --git a/htdocs/langs/en_US/users.lang b/htdocs/langs/en_US/users.lang index d6ffb849aa8..996ba20ab7d 100644 --- a/htdocs/langs/en_US/users.lang +++ b/htdocs/langs/en_US/users.lang @@ -75,6 +75,7 @@ CreateInternalUserDesc=This form allows you to create an internal user in your c InternalExternalDesc=An internal user is a user that is part of your company/organization.
    An external user is a customer, vendor or other (Creating an external user for a third-party can be done from the contact record of the third-party).

    In both cases, permissions defines rights on Dolibarr, also external user can have a different menu manager than internal user (See Home - Setup - Display) PermissionInheritedFromAGroup=Permission granted because inherited from one of a user's group. Inherited=Inherited +UserWillBe=Created user will be UserWillBeInternalUser=Created user will be an internal user (because not linked to a particular third party) UserWillBeExternalUser=Created user will be an external user (because linked to a particular third party) IdPhoneCaller=Id phone caller diff --git a/htdocs/langs/fr_FR/bills.lang b/htdocs/langs/fr_FR/bills.lang index 5da6bda8133..37745a85490 100644 --- a/htdocs/langs/fr_FR/bills.lang +++ b/htdocs/langs/fr_FR/bills.lang @@ -58,7 +58,7 @@ SuppliersInvoices=Factures fournisseurs SupplierBill=Facture fournisseur SupplierBills=Factures fournisseurs Payment=Règlement -PaymentBack=Rembourser +PaymentBack=Remboursement CustomerInvoicePaymentBack=Rembourser Payments=Règlements PaymentsBack=Remboursements diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index 1c4116b34c2..5ea03693eb8 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -52,6 +52,8 @@ $object = new Loan($db); $hookmanager->initHooks(array('loancard', 'globalcard')); +$error = 0; + /* * Actions @@ -62,7 +64,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { // Classify paid - if ($action == 'confirm_paid' && $confirm == 'yes') + if ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->loan->write) { $object->fetch($id); $result = $object->set_paid($user); @@ -75,7 +77,7 @@ if (empty($reshook)) } // Delete loan - if ($action == 'confirm_delete' && $confirm == 'yes') + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->write) { $object->fetch($id); $result = $object->delete($user); @@ -146,12 +148,12 @@ if (empty($reshook)) if ($id <= 0) { $error++; - setEventMessages($object->db->lastqueryerror, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $action = 'create'; } } } else { - header("Location: index.php"); + header("Location: list.php"); exit(); } } diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php index 9c5c1b559ad..dc6d72094b2 100644 --- a/htdocs/loan/class/paymentloan.class.php +++ b/htdocs/loan/class/paymentloan.class.php @@ -417,6 +417,31 @@ class PaymentLoan extends CommonObject } } + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->statut, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + return ''; + } + /** * Add record into bank for payment with links between this bank record and invoices of payment. * All payment properties must have been set first like after a call to create(). diff --git a/htdocs/loan/payment/card.php b/htdocs/loan/payment/card.php index 51aa3f85a92..15759a8ce7b 100644 --- a/htdocs/loan/payment/card.php +++ b/htdocs/loan/payment/card.php @@ -71,42 +71,6 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->loan->del } } -// Create payment -if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->loan->write) -{ - $db->begin(); - - $result = $payment->valide(); - - if ($result > 0) - { - $db->commit(); - - $factures = array(); // TODO Get all id of invoices linked to this payment - foreach ($factures as $id) - { - $fac = new Facture($db); - $fac->fetch($id); - - $outputlangs = $langs; - if (!empty($_REQUEST['lang_id'])) - { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($_REQUEST['lang_id']); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $fac->generateDocument($fac->model_pdf, $outputlangs); - } - } - - header('Location: card.php?id='.$payment->id); - exit; - } else { - setEventMessages($payment->error, $payment->errors, 'errors'); - $db->rollback(); - } -} - /* * View @@ -124,7 +88,7 @@ $head[$h][1] = $langs->trans("PaymentLoan"); $hselected = $h; $h++; -dol_fiche_head($head, $hselected, $langs->trans("PaymentLoan"), 0, 'payment'); +dol_fiche_head($head, $hselected, $langs->trans("PaymentLoan"), -1, 'payment'); /* * Confirm deletion of the payment @@ -134,24 +98,17 @@ if ($action == 'delete') print $form->formconfirm('card.php?id='.$payment->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } -/* - * Confirm validation of the payment - */ -if ($action == 'valide') -{ - $facid = $_GET['facid']; - print $form->formconfirm('card.php?id='.$payment->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide', '', 0, 2); -} +$linkback = ''; +$morehtmlref = ''; +$morehtmlright = ''; +dol_banner_tab($payment, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); + +print '
    '; +print '
    '; print ''; -// Ref -print ''; -print ''; - // Date print ''; @@ -188,6 +145,8 @@ if (!empty($conf->banque->enabled)) print '
    '.$langs->trans('Ref').''; -print $form->showrefnav($payment, 'id', '', 1, 'rowid', 'id'); -print '
    '.$langs->trans('Date').''.dol_print_date($payment->datep, 'day').'
    '; +print '
    '; + /* * List of loans payed @@ -262,20 +221,8 @@ print '
    '; /* * Actions buttons */ -print '
    '; -/* -if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) -{ - if ($user->socid == 0 && $payment->statut == 0 && $_GET['action'] == '') - { - if ($user->rights->facture->paiement) - { - print ''.$langs->trans('Valid').''; - } - } -} -*/ +print '
    '; if (empty($action) && !empty($user->rights->loan->delete)) { diff --git a/htdocs/loan/payment/payment.php b/htdocs/loan/payment/payment.php index 9aaa75b9845..82f114b7b20 100644 --- a/htdocs/loan/payment/payment.php +++ b/htdocs/loan/payment/payment.php @@ -272,14 +272,13 @@ if ($action == 'create') print ''; print ''; print ''; - print ''; + print ''; print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; - - print ''; + /* + print '
    '.$langs->trans("Loan").'
    '; print ''; if ($echance > 0) @@ -295,13 +294,9 @@ if ($action == 'create') print ''; print '
    '.$langs->trans("Ref").''.$chid.'
    '; + */ - print '
    '; - - print ''; - print ''; - print ''; - print ''; + print '
    '.$langs->trans("Payment").'
    '; print '"; - print ''; print ''; print ''; print ''; // Number print ''; - print ''."\n"; + print ''."\n"; + print ""; print ''; print ''; @@ -344,6 +339,7 @@ if ($action == 'create') dol_fiche_end(); + print '
    '.$langs->trans("Date").''; if (empty($datepaid)) @@ -310,7 +305,6 @@ if ($action == 'create') else $datepayment = $datepaid; print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1); print "
    '.$langs->trans("PaymentMode").''; @@ -321,14 +315,15 @@ if ($action == 'create') print '
    '.$langs->trans('AccountToDebit').''; - $form->select_comptes(isset($_POST["accountid"])?$_POST["accountid"]:$loan->accountid, "accountid", 0, 'courant = '.Account::TYPE_CURRENT, 1); // Show opend bank account list + $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", 'int') : $loan->accountid, "accountid", 0, 'courant = '.Account::TYPE_CURRENT, 1); // Show opend bank account list print '
    '.$langs->trans('Numero'); print ' ('.$langs->trans("ChequeOrTransferNumber").')'; print '
    '.$langs->trans("NotePrivate").'
    '; print ''; print ''; diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index ef7b5e33a7d..3cfb5c3d1a5 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -12,6 +12,7 @@ * Copyright (C) 2014-2015 Marcos García * Copyright (C) 2015 Raphaël Doursenaud * Copyright (C) 2020 Demarest Maxime + * Copyright (C) 2020 Charlene Benke * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -57,12 +58,16 @@ if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) */ function testSqlAndScriptInject($val, $type) { - $val = html_entity_decode($val, ENT_QUOTES); // So gl // Check all cases that need a token (all POST actions, all actions and mass actions on pages with CSRFCHECK_WITH_TOKEN set, all sensitive GET actions) if ($_SERVER['REQUEST_METHOD'] == 'POST' || ((GETPOSTISSET('action') || GETPOSTISSET('massaction')) && defined('CSRFCHECK_WITH_TOKEN')) || - in_array(GETPOST('action', 'aZ09'), array('add', 'addtimespent', 'update', 'install', 'delete', 'deleteprof', 'deletepayment'))) + in_array(GETPOST('action', 'aZ09'), array('add', 'addtimespent', 'update', 'install', 'delete', 'deleteprof', 'deletepayment', 'confirm_create_user', 'confirm_create_thirdparty', 'confirm_reject_check'))) { if (!GETPOSTISSET('token')) { - if (GETPOST('uploadform')) { + if (GETPOST('uploadform', 'int')) { dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." refused. File size too large."); $langs->loadLangs(array("errors", "install")); print $langs->trans("ErrorFileSizeTooLarge").' '; @@ -1655,8 +1660,13 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead $helpbaseurl = ''; $helppage = ''; $mode = ''; + $helppresent = ''; - if (empty($helppagename)) $helppagename = 'EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios'; + if (empty($helppagename)) { + $helppagename = 'EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios'; + } else { + $helppresent = 'helppresent'; + } // Get helpbaseurl, helppage and mode from helppagename and langs $arrayres = getHelpParamFor($helppagename, $langs); @@ -1674,7 +1684,7 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead if ($mode == 'wiki') $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage))); else $text .= sprintf($helpbaseurl, $helppage); $text .= '">'; - $text .= ''; + $text .= ''; $text .= ''; $toprightmenu .= @Form::textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2); } diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php index 18ca9b5ea20..2c03c3dd2a9 100644 --- a/htdocs/modulebuilder/template/class/myobject.class.php +++ b/htdocs/modulebuilder/template/class/myobject.class.php @@ -568,7 +568,7 @@ class MyObject extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($num)."',"; $sql .= " status = ".self::STATUS_VALIDATED; - if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; + if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'"; if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id; $sql .= " WHERE rowid = ".$this->id; diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php b/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php index 694263e2ec5..ea9eeed797d 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php @@ -43,82 +43,82 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; */ class pdf_standard_myobject extends ModelePDFMyObject { - /** - * @var DoliDb Database handler - */ - public $db; + /** + * @var DoliDb Database handler + */ + public $db; /** - * @var string model name - */ - public $name; + * @var string model name + */ + public $name; /** - * @var string model description (short text) - */ - public $description; - - /** - * @var int Save the name of generated file as the main doc when generating a doc with this template - */ - public $update_main_doc_field; + * @var string model description (short text) + */ + public $description; /** - * @var string document type - */ - public $type; + * @var int Save the name of generated file as the main doc when generating a doc with this template + */ + public $update_main_doc_field; /** - * @var array Minimum version of PHP required by module. - * e.g.: PHP ≥ 5.6 = array(5, 6) - */ + * @var string document type + */ + public $type; + + /** + * @var array Minimum version of PHP required by module. + * e.g.: PHP ≥ 5.6 = array(5, 6) + */ public $phpmin = array(5, 6); /** - * Dolibarr version of the loaded document - * @var string - */ + * Dolibarr version of the loaded document + * @var string + */ public $version = 'dolibarr'; - /** - * @var int page_largeur - */ - public $page_largeur; + /** + * @var int page_largeur + */ + public $page_largeur; /** - * @var int page_hauteur - */ - public $page_hauteur; + * @var int page_hauteur + */ + public $page_hauteur; /** - * @var array format - */ - public $format; + * @var array format + */ + public $format; /** - * @var int marge_gauche - */ + * @var int marge_gauche + */ public $marge_gauche; /** - * @var int marge_droite - */ + * @var int marge_droite + */ public $marge_droite; /** - * @var int marge_haute - */ + * @var int marge_haute + */ public $marge_haute; /** - * @var int marge_basse - */ + * @var int marge_basse + */ public $marge_basse; - /** - * Issuer - * @var Societe Object that emits - */ + /** + * Issuer + * @var Societe Object that emits + */ public $emetteur; /** @@ -182,50 +182,50 @@ class pdf_standard_myobject extends ModelePDFMyObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Function to build pdf onto disk - * - * @param Object $object Object to generate - * @param Translate $outputlangs Lang output object - * @param string $srctemplatepath Full path of source filename for generator using a template file - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return int 1=OK, 0=KO + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Function to build pdf onto disk + * + * @param Object $object Object to generate + * @param Translate $outputlangs Lang output object + * @param string $srctemplatepath Full path of source filename for generator using a template file + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return int 1=OK, 0=KO */ public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { - // phpcs:enable - global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; + // phpcs:enable + global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); + dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - if (!is_object($outputlangs)) $outputlangs = $langs; - // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; + if (!is_object($outputlangs)) $outputlangs = $langs; + // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; - // Load translation files required by the page - $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); + // Load translation files required by the page + $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); - if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { - global $outputlangsbis; - $outputlangsbis = new Translate('', $conf); - $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); - $outputlangsbis->loadLangs(array("main", "bills", "products", "dict", "companies")); - } + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "bills", "products", "dict", "companies")); + } - $nblines = (is_array($object->lines) ? count($object->lines) : 0); + $nblines = (is_array($object->lines) ? count($object->lines) : 0); - $hidetop = 0; - if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { - $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; - } + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + } - // Loop on each lines to detect if there is at least one image to show - $realpatharray = array(); - $this->atleastonephoto = false; - /* + // Loop on each lines to detect if there is at least one image to show + $realpatharray = array(); + $this->atleastonephoto = false; + /* if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) { $objphoto = new Product($this->db); @@ -278,528 +278,528 @@ class pdf_standard_myobject extends ModelePDFMyObject } */ - //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; + //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; - if ($conf->mymodule->dir_output.'/myobject') - { - $object->fetch_thirdparty(); + if ($conf->mymodule->dir_output.'/myobject') + { + $object->fetch_thirdparty(); - // Definition of $dir and $file - if ($object->specimen) - { - $dir = $conf->mymodule->dir_output.'/myobject'; - $file = $dir."/SPECIMEN.pdf"; - } else { - $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->mymodule->dir_output.'/myobject/'.$objectref; - $file = $dir."/".$objectref.".pdf"; - } - if (!file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { - $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); - return 0; - } - } + // Definition of $dir and $file + if ($object->specimen) + { + $dir = $conf->mymodule->dir_output.'/myobject'; + $file = $dir."/SPECIMEN.pdf"; + } else { + $objectref = dol_sanitizeFileName($object->ref); + $dir = $conf->mymodule->dir_output.'/myobject/'.$objectref; + $file = $dir."/".$objectref.".pdf"; + } + if (!file_exists($dir)) + { + if (dol_mkdir($dir) < 0) + { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } - if (file_exists($dir)) - { - // Add pdfgeneration hook - if (!is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($this->db); - } - $hookmanager->initHooks(array('pdfgeneration')); - $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); - global $action; - $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + if (file_exists($dir)) + { + // Add pdfgeneration hook + if (!is_object($hookmanager)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($this->db); + } + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - // Set nblines with the new facture lines content after hook - $nblines = (is_array($object->lines) ? count($object->lines) : 0); + // Set nblines with the new facture lines content after hook + $nblines = (is_array($object->lines) ? count($object->lines) : 0); - // Create pdf instance - $pdf = pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $pdf->SetAutoPageBreak(1, 0); + // Create pdf instance + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $pdf->SetAutoPageBreak(1, 0); - $heightforinfotot = 50; // Height reserved to output the info and total part and payment part - $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) + $heightforinfotot = 50; // Height reserved to output the info and total part and payment part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) - if (class_exists('TCPDF')) - { - $pdf->setPrintHeader(false); - $pdf->setPrintFooter(false); - } - $pdf->SetFont(pdf_getPDFFont($outputlangs)); + if (class_exists('TCPDF')) + { + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); - // Set path to the background PDF File - if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) - { - $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); - $tplidx = $pdf->importPage(1); - } + // Set path to the background PDF File + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + { + $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); + $tplidx = $pdf->importPage(1); + } - $pdf->Open(); - $pagenb = 0; - $pdf->SetDrawColor(128, 128, 128); + $pdf->Open(); + $pagenb = 0; + $pdf->SetDrawColor(128, 128, 128); - $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); - $pdf->SetSubject($outputlangs->transnoentities("PdfTitle")); - $pdf->SetCreator("Dolibarr ".DOL_VERSION); - $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); - $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); + $pdf->SetSubject($outputlangs->transnoentities("PdfTitle")); + $pdf->SetCreator("Dolibarr ".DOL_VERSION); + $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); + $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - // Set certificate - $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; - // If user has no certificate, we try to take the company one - if (!$cert) { - $cert = empty($conf->global->CERTIFICATE_CRT) ? '' : $conf->global->CERTIFICATE_CRT; - } - // If a certificate is found - if ($cert) { - $info = array( - 'Name' => $this->emetteur->name, - 'Location' => getCountry($this->emetteur->country_code, 0), - 'Reason' => 'MYOBJECT', - 'ContactInfo' => $this->emetteur->email - ); - $pdf->setSignature($cert, $cert, $this->emetteur->name, '', 2, $info); - } + // Set certificate + $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; + // If user has no certificate, we try to take the company one + if (!$cert) { + $cert = empty($conf->global->CERTIFICATE_CRT) ? '' : $conf->global->CERTIFICATE_CRT; + } + // If a certificate is found + if ($cert) { + $info = array( + 'Name' => $this->emetteur->name, + 'Location' => getCountry($this->emetteur->country_code, 0), + 'Reason' => 'MYOBJECT', + 'ContactInfo' => $this->emetteur->email + ); + $pdf->setSignature($cert, $cert, $this->emetteur->name, '', 2, $info); + } - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right - // New page - $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pagenb++; + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; - $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); - $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 - $pdf->SetTextColor(0, 0, 0); + $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->SetTextColor(0, 0, 0); - $tab_top = 90 + $top_shift; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); - $tab_height = 130 - $top_shift; - $tab_height_newpage = 150; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); + $tab_height = 130 - $top_shift; + $tab_height_newpage = 150; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; - $nexY = $tab_top - 1; + $nexY = $tab_top - 1; - // Display notes - $notetoshow = empty($object->note_public) ? '' : $object->note_public; - // Extrafields in note - $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); - if (!empty($extranote)) - { - $notetoshow = dol_concatdesc($notetoshow, $extranote); - } + // Display notes + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + // Extrafields in note + $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); + if (!empty($extranote)) + { + $notetoshow = dol_concatdesc($notetoshow, $extranote); + } - $pagenb = $pdf->getPage(); - if ($notetoshow) - { + $pagenb = $pdf->getPage(); + if ($notetoshow) + { $tab_top -= 2; - $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; - $pageposbeforenote = $pagenb; + $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; + $pageposbeforenote = $pagenb; - $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); - complete_substitutions_array($substitutionarray, $outputlangs, $object); - $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); - $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); + complete_substitutions_array($substitutionarray, $outputlangs, $object); + $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); + $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); - $pdf->startTransaction(); + $pdf->startTransaction(); - $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); - // Description - $pageposafternote = $pdf->getPage(); - $posyafter = $pdf->GetY(); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + // Description + $pageposafternote = $pdf->getPage(); + $posyafter = $pdf->GetY(); - if ($pageposafternote > $pageposbeforenote) - { - $pdf->rollbackTransaction(true); + if ($pageposafternote > $pageposbeforenote) + { + $pdf->rollbackTransaction(true); - // prepare pages to receive notes - while ($pagenb < $pageposafternote) { - $pdf->AddPage(); - $pagenb++; - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - // $this->_pagefoot($pdf,$object,$outputlangs,1); - $pdf->setTopMargin($tab_top_newpage); - // The only function to edit the bottom margin of current page to set it. - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); - } + // prepare pages to receive notes + while ($pagenb < $pageposafternote) { + $pdf->AddPage(); + $pagenb++; + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + // $this->_pagefoot($pdf,$object,$outputlangs,1); + $pdf->setTopMargin($tab_top_newpage); + // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + } - // back to start - $pdf->setPage($pageposbeforenote); - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); - $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); - $pageposafternote = $pdf->getPage(); + // back to start + $pdf->setPage($pageposbeforenote); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + $pageposafternote = $pdf->getPage(); - $posyafter = $pdf->GetY(); + $posyafter = $pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text - { - $pdf->AddPage('', '', true); - $pagenb++; - $pageposafternote++; - $pdf->setPage($pageposafternote); - $pdf->setTopMargin($tab_top_newpage); - // The only function to edit the bottom margin of current page to set it. - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); - //$posyafter = $tab_top_newpage; - } + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text + { + $pdf->AddPage('', '', true); + $pagenb++; + $pageposafternote++; + $pdf->setPage($pageposafternote); + $pdf->setTopMargin($tab_top_newpage); + // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + //$posyafter = $tab_top_newpage; + } - // apply note frame to previous pages - $i = $pageposbeforenote; - while ($i < $pageposafternote) { - $pdf->setPage($i); + // apply note frame to previous pages + $i = $pageposbeforenote; + while ($i < $pageposafternote) { + $pdf->setPage($i); - $pdf->SetDrawColor(128, 128, 128); - // Draw note frame - if ($i > $pageposbeforenote) { - $height_note = $this->page_hauteur - ($tab_top_newpage + $heightforfooter); - $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); - } else { - $height_note = $this->page_hauteur - ($tab_top + $heightforfooter); - $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); - } + $pdf->SetDrawColor(128, 128, 128); + // Draw note frame + if ($i > $pageposbeforenote) { + $height_note = $this->page_hauteur - ($tab_top_newpage + $heightforfooter); + $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); + } else { + $height_note = $this->page_hauteur - ($tab_top + $heightforfooter); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); + } - // Add footer - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - $this->_pagefoot($pdf, $object, $outputlangs, 1); + // Add footer + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $this->_pagefoot($pdf, $object, $outputlangs, 1); - $i++; - } + $i++; + } - // apply note frame to last page - $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $height_note = $posyafter - $tab_top_newpage; - $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); - } else // No pagebreak - { - $pdf->commitTransaction(); - $posyafter = $pdf->GetY(); - $height_note = $posyafter - $tab_top; - $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); + // apply note frame to last page + $pdf->setPage($pageposafternote); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + $height_note = $posyafter - $tab_top_newpage; + $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); + } else // No pagebreak + { + $pdf->commitTransaction(); + $posyafter = $pdf->GetY(); + $height_note = $posyafter - $tab_top; + $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) - { - // not enough space, need to add page - $pdf->AddPage('', '', true); - $pagenb++; - $pageposafternote++; - $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) + { + // not enough space, need to add page + $pdf->AddPage('', '', true); + $pagenb++; + $pageposafternote++; + $pdf->setPage($pageposafternote); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $posyafter = $tab_top_newpage; - } - } + $posyafter = $tab_top_newpage; + } + } - $tab_height = $tab_height - $height_note; - $tab_top = $posyafter + 6; - } else { - $height_note = 0; - } + $tab_height = $tab_height - $height_note; + $tab_top = $posyafter + 6; + } else { + $height_note = 0; + } - // Use new auto column system - $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); + // Use new auto column system + $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - // Table simulation to know the height of the title line - $pdf->startTransaction(); - $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); - $pdf->rollbackTransaction(true); + // Table simulation to know the height of the title line + $pdf->startTransaction(); + $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); + $pdf->rollbackTransaction(true); - $nexY = $tab_top + $this->tabTitleHeight; + $nexY = $tab_top + $this->tabTitleHeight; - // Loop on each lines - $pageposbeforeprintlines = $pdf->getPage(); - $pagenb = $pageposbeforeprintlines; - for ($i = 0; $i < $nblines; $i++) - { - $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage - $pdf->SetTextColor(0, 0, 0); + // Loop on each lines + $pageposbeforeprintlines = $pdf->getPage(); + $pagenb = $pageposbeforeprintlines; + for ($i = 0; $i < $nblines; $i++) + { + $curY = $nexY; + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetTextColor(0, 0, 0); - // Define size of image if we need it - $imglinesize = array(); - if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + // Define size of image if we need it + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); - $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore = $pdf->getPage(); + $pdf->setTopMargin($tab_top_newpage); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak = 1; - $posYAfterImage = 0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; - if ($this->getColumnStatus('photo')) - { - // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page - { - $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposbefore + 1); + if ($this->getColumnStatus('photo')) + { + // We start with Photo of product line + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page + { + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposbefore + 1); - $curY = $tab_top_newpage; + $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; - } + } - if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) - { - $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi - // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage = $curY + $imglinesize['height']; - } - } + if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) + { + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + // $pdf->Image does not increase value return by getY, so we save it manually + $posYAfterImage = $curY + $imglinesize['height']; + } + } - // Description of product line - if ($this->getColumnStatus('desc')) - { - $pdf->startTransaction(); + // Description of product line + if ($this->getColumnStatus('desc')) + { + $pdf->startTransaction(); - $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); - $pageposafter = $pdf->getPage(); + $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); + $pageposafter = $pdf->getPage(); - if ($pageposafter > $pageposbefore) // There is a pagebreak - { - $pdf->rollbackTransaction(true); - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + if ($pageposafter > $pageposbefore) // There is a pagebreak + { + $pdf->rollbackTransaction(true); + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. - $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); + $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); - $pageposafter = $pdf->getPage(); - $posyafter = $pdf->GetY(); - //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text - { - if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page - { - $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposafter + 1); - } - } else { - // We found a page break + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text + { + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page + { + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposafter + 1); + } + } else { + // We found a page break // Allows data in the first page if description is long enough to break in multiples pages if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; - } - } else // No pagebreak - { - $pdf->commitTransaction(); - } - } + } + } else // No pagebreak + { + $pdf->commitTransaction(); + } + } - $nexY = $pdf->GetY(); - $pageposafter = $pdf->getPage(); - $pdf->setPage($pageposbefore); - $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $nexY = $pdf->GetY(); + $pageposafter = $pdf->getPage(); + $pdf->setPage($pageposbefore); + $pdf->setTopMargin($this->marge_haute); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - // We suppose that a too long description or photo were moved completely on next page - if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { - $pdf->setPage($pageposafter); $curY = $tab_top_newpage; - } + // We suppose that a too long description or photo were moved completely on next page + if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { + $pdf->setPage($pageposafter); $curY = $tab_top_newpage; + } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut - // Quantity - // Enough for 6 chars - if ($this->getColumnStatus('qty')) - { - $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); - $this->printStdColumnContent($pdf, $curY, 'qty', $qty); - $nexY = max($pdf->GetY(), $nexY); - } + // Quantity + // Enough for 6 chars + if ($this->getColumnStatus('qty')) + { + $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); + $this->printStdColumnContent($pdf, $curY, 'qty', $qty); + $nexY = max($pdf->GetY(), $nexY); + } - // Extrafields - if (!empty($object->lines[$i]->array_options)) { - foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { - if ($this->getColumnStatus($extrafieldColKey)) - { - $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); - $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); - $nexY = max($pdf->GetY(), $nexY); - } - } - } + // Extrafields + if (!empty($object->lines[$i]->array_options)) { + foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { + if ($this->getColumnStatus($extrafieldColKey)) + { + $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); + $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); + $nexY = max($pdf->GetY(), $nexY); + } + } + } - $parameters = array( - 'object' => $object, - 'i' => $i, - 'pdf' =>& $pdf, - 'curY' =>& $curY, - 'nexY' =>& $nexY, - 'outputlangs' => $outputlangs, - 'hidedetails' => $hidedetails - ); - $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook + $parameters = array( + 'object' => $object, + 'i' => $i, + 'pdf' =>& $pdf, + 'curY' =>& $curY, + 'nexY' =>& $nexY, + 'outputlangs' => $outputlangs, + 'hidedetails' => $hidedetails + ); + $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook - $sign = 1; - // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - $prev_progress = $object->lines[$i]->get_prev_progress($object->id); - if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) // Compute progress from previous situation - { - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - } else { - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; - else $tvaligne = $sign * $object->lines[$i]->total_tva; - } + $sign = 1; + // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva + $prev_progress = $object->lines[$i]->get_prev_progress($object->id); + if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) // Compute progress from previous situation + { + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + } else { + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $sign * $object->lines[$i]->total_tva; + } - $localtax1ligne = $object->lines[$i]->total_localtax1; - $localtax2ligne = $object->lines[$i]->total_localtax2; - $localtax1_rate = $object->lines[$i]->localtax1_tx; - $localtax2_rate = $object->lines[$i]->localtax2_tx; - $localtax1_type = $object->lines[$i]->localtax1_type; - $localtax2_type = $object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; - if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; - if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate = (string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; - // Retrieve type from database for backward compatibility with old records - if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined - && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax - { - $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); - $localtax1_type = $localtaxtmp_array[0]; - $localtax2_type = $localtaxtmp_array[2]; - } + // Retrieve type from database for backward compatibility with old records + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax + { + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtax1_type = $localtaxtmp_array[0]; + $localtax2_type = $localtaxtmp_array[2]; + } - // retrieve global local tax - if ($localtax1_type && $localtax1ligne != 0) { - $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; - } - if ($localtax2_type && $localtax2ligne != 0) { - $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - } + // retrieve global local tax + if ($localtax1_type && $localtax1ligne != 0) { + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; + } + if ($localtax2_type && $localtax2ligne != 0) { + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; + } - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; - if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; - $this->tva[$vatrate] += $tvaligne; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; + $this->tva[$vatrate] += $tvaligne; - $nexY = max($nexY, $posYAfterImage); + $nexY = max($nexY, $posYAfterImage); - // Add line - if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { - $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); - //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY, $this->page_largeur - $this->marge_droite, $nexY); - $pdf->SetLineStyle(array('dash'=>0)); - } + // Add line + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { + $pdf->setPage($pageposafter); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); + //$pdf->SetDrawColor(190,190,200); + $pdf->line($this->marge_gauche, $nexY, $this->page_largeur - $this->marge_droite, $nexY); + $pdf->SetLineStyle(array('dash'=>0)); + } - // Detect if some page were added automatically and output _tableau for past pages - while ($pagenb < $pageposafter) { - $pdf->setPage($pagenb); - if ($pagenb == $pageposbeforeprintlines) { - $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); - } - $this->_pagefoot($pdf, $object, $outputlangs, 1); - $pagenb++; - $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - } + // Detect if some page were added automatically and output _tableau for past pages + while ($pagenb < $pageposafter) { + $pdf->setPage($pagenb); + if ($pagenb == $pageposbeforeprintlines) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + $pagenb++; + $pdf->setPage($pagenb); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } - if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { - if ($pagenb == $pageposafter) { - $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); - } - $this->_pagefoot($pdf, $object, $outputlangs, 1); - // New page - $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pagenb++; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - } - } + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { + if ($pagenb == $pageposafter) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } + } - // Show square - if ($pagenb == $pageposbeforeprintlines) - { - $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); - $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code, $outputlangsbis); - $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; - } + // Show square + if ($pagenb == $pageposbeforeprintlines) + { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code, $outputlangsbis); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + } - // Display infos area - //$posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); + // Display infos area + //$posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); - // Display total zone - //$posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); + // Display total zone + //$posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); - // Display payment area - /* + // Display payment area + /* if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) { $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); } */ - // Pagefoot - $this->_pagefoot($pdf, $object, $outputlangs); - if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + // Pagefoot + $this->_pagefoot($pdf, $object, $outputlangs); + if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); - $pdf->Close(); + $pdf->Close(); - $pdf->Output($file, 'F'); + $pdf->Output($file, 'F'); - // Add pdfgeneration hook - $hookmanager->initHooks(array('pdfgeneration')); - $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); - global $action; - $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) - { - $this->error = $hookmanager->error; - $this->errors = $hookmanager->errors; - } + // Add pdfgeneration hook + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) + { + $this->error = $hookmanager->error; + $this->errors = $hookmanager->errors; + } - if (!empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); - $this->result = array('fullpath'=>$file); + $this->result = array('fullpath'=>$file); - return 1; // No error - } else { - $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); - return 0; - } - } else { - $this->error = $langs->transnoentities("ErrorConstantNotDefined", "FAC_OUTPUTDIR"); - return 0; - } + return 1; // No error + } else { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } else { + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "FAC_OUTPUTDIR"); + return 0; + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -872,7 +872,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter } } @@ -900,9 +900,9 @@ class pdf_standard_myobject extends ModelePDFMyObject // Show Draft Watermark if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) - { - pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); - } + { + pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); + } $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); @@ -910,7 +910,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $w = 110; $posy = $this->marge_haute; - $posx = $this->page_largeur - $this->marge_droite - $w; + $posx = $this->page_largeur - $this->marge_droite - $w; $pdf->SetXY($this->marge_gauche, $posy); @@ -929,7 +929,7 @@ class pdf_standard_myobject extends ModelePDFMyObject } if (is_readable($logo)) { - $height = pdf_getHeightForLogo($logo); + $height = pdf_getHeightForLogo($logo); $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { $pdf->SetTextColor(200, 0, 0); @@ -1022,16 +1022,16 @@ class pdf_standard_myobject extends ModelePDFMyObject // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { - $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); - if (count($arrayidcontact) > 0) - { - $usertmp = new User($this->db); - $usertmp->fetch($arrayidcontact[0]); - $posy += 4; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 3, $langs->transnoentities("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); - } + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); + if (count($arrayidcontact) > 0) + { + $usertmp = new User($this->db); + $usertmp->fetch($arrayidcontact[0]); + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 3, $langs->transnoentities("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); + } } $posy += 1; @@ -1138,7 +1138,7 @@ class pdf_standard_myobject extends ModelePDFMyObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** * Show footer of page. Need this->emetteur object - * + * * @param TCPDF $pdf PDF * @param Object $object Object to show * @param Translate $outputlangs Object lang for output @@ -1157,28 +1157,28 @@ class pdf_standard_myobject extends ModelePDFMyObject * * @param object $object common object * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return null - */ - public function defineColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - global $conf, $hookmanager; + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return null + */ + public function defineColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + global $conf, $hookmanager; - // Default field style for content - $this->defaultContentsFieldsStyle = array( - 'align' => 'R', // R,C,L - 'padding' => array(1, 0.5, 1, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ); + // Default field style for content + $this->defaultContentsFieldsStyle = array( + 'align' => 'R', // R,C,L + 'padding' => array(1, 0.5, 1, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ); - // Default field style for content - $this->defaultTitlesFieldsStyle = array( - 'align' => 'C', // R,C,L - 'padding' => array(0.5, 0, 0.5, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ); + // Default field style for content + $this->defaultTitlesFieldsStyle = array( + 'align' => 'C', // R,C,L + 'padding' => array(0.5, 0, 0.5, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ); - /* + /* * For exemple $this->cols['theColKey'] = array( 'rank' => $rank, // int : use for ordering columns @@ -1196,162 +1196,162 @@ class pdf_standard_myobject extends ModelePDFMyObject ); */ - $rank = 0; // do not use negative rank - $this->cols['desc'] = array( - 'rank' => $rank, - 'width' => false, // only for desc - 'status' => true, - 'title' => array( - 'textkey' => 'Designation', // use lang key is usefull in somme case with module - 'align' => 'L', - // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label - // 'label' => ' ', // the final label - 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'content' => array( - 'align' => 'L', - 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - ); + $rank = 0; // do not use negative rank + $this->cols['desc'] = array( + 'rank' => $rank, + 'width' => false, // only for desc + 'status' => true, + 'title' => array( + 'textkey' => 'Designation', // use lang key is usefull in somme case with module + 'align' => 'L', + // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + // 'label' => ' ', // the final label + 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', + 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); - // PHOTO - $rank = $rank + 10; - $this->cols['photo'] = array( - 'rank' => $rank, - 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Photo', - 'label' => ' ' - ), - 'content' => array( - 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'border-left' => false, // remove left line separator - ); + // PHOTO + $rank = $rank + 10; + $this->cols['photo'] = array( + 'rank' => $rank, + 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Photo', + 'label' => ' ' + ), + 'content' => array( + 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'border-left' => false, // remove left line separator + ); - if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) - { - $this->cols['photo']['status'] = true; - } + if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) + { + $this->cols['photo']['status'] = true; + } - $rank = $rank + 10; - $this->cols['vat'] = array( - 'rank' => $rank, - 'status' => false, - 'width' => 16, // in mm - 'title' => array( - 'textkey' => 'VAT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['vat'] = array( + 'rank' => $rank, + 'status' => false, + 'width' => 16, // in mm + 'title' => array( + 'textkey' => 'VAT' + ), + 'border-left' => true, // add left line separator + ); - if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) - { - $this->cols['vat']['status'] = true; - } + if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) + { + $this->cols['vat']['status'] = true; + } - $rank = $rank + 10; - $this->cols['subprice'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'PriceUHT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['subprice'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'PriceUHT' + ), + 'border-left' => true, // add left line separator + ); - $rank = $rank + 10; - $this->cols['qty'] = array( - 'rank' => $rank, - 'width' => 16, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'Qty' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['qty'] = array( + 'rank' => $rank, + 'width' => 16, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'Qty' + ), + 'border-left' => true, // add left line separator + ); - $rank = $rank + 10; - $this->cols['progress'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Progress' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['progress'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Progress' + ), + 'border-left' => true, // add left line separator + ); - if ($this->situationinvoice) - { - $this->cols['progress']['status'] = true; - } + if ($this->situationinvoice) + { + $this->cols['progress']['status'] = true; + } - $rank = $rank + 10; - $this->cols['unit'] = array( - 'rank' => $rank, - 'width' => 11, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Unit' - ), - 'border-left' => true, // add left line separator - ); - if ($conf->global->PRODUCT_USE_UNITS) { - $this->cols['unit']['status'] = true; - } + $rank = $rank + 10; + $this->cols['unit'] = array( + 'rank' => $rank, + 'width' => 11, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Unit' + ), + 'border-left' => true, // add left line separator + ); + if ($conf->global->PRODUCT_USE_UNITS) { + $this->cols['unit']['status'] = true; + } - $rank = $rank + 10; - $this->cols['discount'] = array( - 'rank' => $rank, - 'width' => 13, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'ReductionShort' - ), - 'border-left' => true, // add left line separator - ); - if ($this->atleastonediscount) { - $this->cols['discount']['status'] = true; - } + $rank = $rank + 10; + $this->cols['discount'] = array( + 'rank' => $rank, + 'width' => 13, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'ReductionShort' + ), + 'border-left' => true, // add left line separator + ); + if ($this->atleastonediscount) { + $this->cols['discount']['status'] = true; + } - $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 - $this->cols['totalexcltax'] = array( - 'rank' => $rank, - 'width' => 26, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'TotalHT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 + $this->cols['totalexcltax'] = array( + 'rank' => $rank, + 'width' => 26, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'TotalHT' + ), + 'border-left' => true, // add left line separator + ); - // Add extrafields cols - if (!empty($object->lines)) { - $line = reset($object->lines); - $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); - } + // Add extrafields cols + if (!empty($object->lines)) { + $line = reset($object->lines); + $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); + } - $parameters = array( - 'object' => $object, - 'outputlangs' => $outputlangs, - 'hidedetails' => $hidedetails, - 'hidedesc' => $hidedesc, - 'hideref' => $hideref - ); + $parameters = array( + 'object' => $object, + 'outputlangs' => $outputlangs, + 'hidedetails' => $hidedetails, + 'hidedesc' => $hidedesc, + 'hideref' => $hideref + ); - $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) - { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) - { - $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys - } else { - $this->cols = $hookmanager->resArray; - } + $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook + if ($reshook < 0) + { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } elseif (empty($reshook)) + { + $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys + } else { + $this->cols = $hookmanager->resArray; + } } } diff --git a/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php b/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php index 4c5951dad70..be6d42047ce 100644 --- a/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php +++ b/htdocs/modulebuilder/template/core/triggers/interface_99_modMyModule_MyModuleTriggers.class.php @@ -102,6 +102,19 @@ class InterfaceMyModuleTriggers extends DolibarrTriggers // Put here code you want to execute when a Dolibarr business events occurs. // Data and type of action are stored into $object and $action + // You can isolate code for each action in a separate method: this method should be named like the trigger in camelCase. + // For example : COMPANY_CREATE => public function companyCreate($action, $object, User $user, Translate $langs, Conf $conf) + $methodName = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($action))))); + $callback = array($this, $methodName); + if (is_callable($callback)){ + dol_syslog( + "Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id + ); + + return call_user_func($callback, $action, $object, $user, $langs, $conf); + }; + + // Or you can execute some code here switch ($action) { // Users //case 'USER_CREATE': diff --git a/htdocs/modulebuilder/template/myobject_agenda.php b/htdocs/modulebuilder/template/myobject_agenda.php index e05b4e93491..c636853e66e 100644 --- a/htdocs/modulebuilder/template/myobject_agenda.php +++ b/htdocs/modulebuilder/template/myobject_agenda.php @@ -22,25 +22,25 @@ * \brief Tab of events on MyObject */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN','1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET // Load Dolibarr environment $res = 0; @@ -223,13 +223,15 @@ if ($object->id > 0) $objthirdparty = $object; $objcon = new stdClass(); - $out = '&origin='.$object->element.'&originid='.$object->id; + $out = '&origin='.urlencode($object->element.'@'.$object->module).'&originid='.urlencode($object->id); + $urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id; + $out .= '&backtopage='.urlencode($urlbacktopage); $permok = $user->rights->agenda->myactions->create; if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='trans("AddAnAction"),'filenew'); //$out.=""; @@ -264,7 +266,7 @@ if ($object->id > 0) $filters['search_agenda_label'] = $search_agenda_label; // TODO Replace this with same code than into list.php - show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder, 'mymmodule'); + show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder, $object->module); } } diff --git a/htdocs/modulebuilder/template/myobject_card.php b/htdocs/modulebuilder/template/myobject_card.php index 49841fe24b9..c2c24e39e75 100644 --- a/htdocs/modulebuilder/template/myobject_card.php +++ b/htdocs/modulebuilder/template/myobject_card.php @@ -22,25 +22,25 @@ * \brief Page to create/edit/view myobject */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN','1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET // Load Dolibarr environment $res = 0; @@ -569,7 +569,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // List of actions on element include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, $object->element.'@mymodule', (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlright); + $somethingshown = $formactions->showactions($object, $object->element.'@'.$object->module, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlright); print ''; } diff --git a/htdocs/modulebuilder/template/myobject_document.php b/htdocs/modulebuilder/template/myobject_document.php index 46a8d0c3a10..29c4d5ddfcb 100644 --- a/htdocs/modulebuilder/template/myobject_document.php +++ b/htdocs/modulebuilder/template/myobject_document.php @@ -22,25 +22,25 @@ * \brief Tab for documents linked to MyObject */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN','1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET // Load Dolibarr environment $res = 0; diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index b1ec021e774..f0bbb1c60e6 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -22,25 +22,25 @@ * \brief List page for myobject */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN','1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET // Load Dolibarr environment $res = 0; @@ -444,7 +444,7 @@ foreach ($object->fields as $key => $val) if (!empty($arrayfields['t.'.$key]['checked'])) { print '
    '.$langs->trans("DateDue").''; - if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; diff --git a/htdocs/modulebuilder/template/myobject_note.php b/htdocs/modulebuilder/template/myobject_note.php index 1a6fd1a4cc6..c1c5b93846d 100644 --- a/htdocs/modulebuilder/template/myobject_note.php +++ b/htdocs/modulebuilder/template/myobject_note.php @@ -22,25 +22,25 @@ * \brief Tab for notes on MyObject */ -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. -//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip -//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value -//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler -//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message -//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies -//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN','1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET // Load Dolibarr environment $res = 0; diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php index c0d6658cab7..b4a3b56faa8 100644 --- a/htdocs/mrp/class/mo.class.php +++ b/htdocs/mrp/class/mo.class.php @@ -1328,6 +1328,21 @@ class Mo extends CommonObject $tpl = DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php'; $res = include $tpl; } + + /** + * Function used to replace a thirdparty id with another one. + * + * @param DoliDB $db Database handler + * @param int $origin_id Old thirdparty id + * @param int $dest_id New thirdparty id + * @return bool + */ + public static function replaceThirdparty($db, $origin_id, $dest_id) + { + $tables = array('mrp_production'); + + return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); + } } /** diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php index add7de31b56..e20a57a6e4d 100644 --- a/htdocs/mrp/mo_card.php +++ b/htdocs/mrp/mo_card.php @@ -107,75 +107,75 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - $error = 0; + $error = 0; - $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); + $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); - if (empty($backtopage) || ($cancel && empty($id))) { - if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); - } - } - if ($cancel && !empty($backtopageforcancel)) { - $backtopage = $backtopageforcancel; - } + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; + else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); + } + } + if ($cancel && !empty($backtopageforcancel)) { + $backtopage = $backtopageforcancel; + } - $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record - // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen - include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; - // Actions when linking object each other - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; + // Actions when linking object each other + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; - // Actions when printing a doc from card - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - // Actions to send emails - $triggersendname = 'MO_SENTBYMAIL'; - $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO'; - $trackid = 'mo'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to send emails + $triggersendname = 'MO_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO'; + $trackid = 'mo'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Action to move up and down lines of object - //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + // Action to move up and down lines of object + //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'set_thirdparty' && $permissiontoadd) - { - $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); - } - if ($action == 'classin' && $permissiontoadd) - { - $object->setProject(GETPOST('projectid', 'int')); - } + if ($action == 'set_thirdparty' && $permissiontoadd) + { + $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); + } + if ($action == 'classin' && $permissiontoadd) + { + $object->setProject(GETPOST('projectid', 'int')); + } - // Action close produced - if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) - { - $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); - if ($result >= 0) - { - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->model_pdf; - $ret = $object->fetch($id); // Reload to get new records + // Action close produced + if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) + { + $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); + if ($result >= 0) + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (!empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model = $object->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, 0, 0, 0); - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->generateDocument($model, $outputlangs, 0, 0, 0); + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } @@ -317,7 +317,7 @@ if (($id || $ref) && $action == 'edit') print load_fiche_titre($langs->trans("MO"), '', 'mrp'); print '
    '; - print ''; + print ''; print ''; print ''; if ($backtopage) print ''; @@ -360,7 +360,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -439,32 +439,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= '
    '; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ' : '.$proj->getNomUrl(); - } else { - $morehtmlref .= ''; - } - } + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($permissiontoadd) + { + if ($action != 'classify') + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ' : '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } } $morehtmlref .= ''; @@ -501,167 +501,167 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (!empty($object->table_element_line)) { - // Show object lines + // Show object lines //$result = $object->getLinesArray(); $object->fetchLines(); - print '
    + print ' '; - /*if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + /*if (!empty($conf->use_javascript_ajax) && $object->status == 0) { include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; }*/ - if (!empty($object->lines)) - { - print '
    '; - print ''; + if (!empty($object->lines)) + { + print '
    '; + print '
    '; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
    '.$langs->trans("Summary").'
    '.$langs->trans("Summary").'
    '.$langs->trans("ProductsToConsume").''; - if (!empty($object->lines)) - { - $i = 0; - foreach ($object->lines as $line) { - if ($line->role == 'toconsume') { - if ($i) print ', '; - $tmpproduct = new Product($db); - $tmpproduct->fetch($line->fk_product); - print $tmpproduct->getNomUrl(1); - $i++; - } - } - } - print '
    '.$langs->trans("ProductsToConsume").''; + if (!empty($object->lines)) + { + $i = 0; + foreach ($object->lines as $line) { + if ($line->role == 'toconsume') { + if ($i) print ', '; + $tmpproduct = new Product($db); + $tmpproduct->fetch($line->fk_product); + print $tmpproduct->getNomUrl(1); + $i++; + } + } + } + print '
    '.$langs->trans("ProductsToProduce").''; - if (!empty($object->lines)) - { - $i = 0; - foreach ($object->lines as $line) { - if ($line->role == 'toproduce') { - if ($i) print ', '; - $tmpproduct = new Product($db); - $tmpproduct->fetch($line->fk_product); - print $tmpproduct->getNomUrl(1); - $i++; - } - } - } - print '
    '.$langs->trans("ProductsToProduce").''; + if (!empty($object->lines)) + { + $i = 0; + foreach ($object->lines as $line) { + if ($line->role == 'toproduce') { + if ($i) print ', '; + $tmpproduct = new Product($db); + $tmpproduct->fetch($line->fk_product); + print $tmpproduct->getNomUrl(1); + $i++; + } + } + } + print '
    '; - print '
    '; - } + print '
    '; + print '
    '; + } - print "\n"; + print "\n"; } // Buttons for actions if ($action != 'presend' && $action != 'editline') { - print '
    '."\n"; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print '
    '."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) - { - // Send - //if (empty($user->socid)) { - // print '' . $langs->trans('SendMail') . ''."\n"; - //} + if (empty($reshook)) + { + // Send + //if (empty($user->socid)) { + // print '' . $langs->trans('SendMail') . ''."\n"; + //} - // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { - // TODO Add test that production has not started - print ''.$langs->trans("SetToDraft").''; - } - } + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) + { + if ($permissiontoadd) + { + // TODO Add test that production has not started + print ''.$langs->trans("SetToDraft").''; + } + } - // Modify - if ($object->status == $object::STATUS_DRAFT) { - if ($permissiontoadd) - { - print ''.$langs->trans("Modify").''."\n"; - } else { - print ''.$langs->trans('Modify').''."\n"; - } - } + // Modify + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) + { + print ''.$langs->trans("Modify").''."\n"; + } else { + print ''.$langs->trans('Modify').''."\n"; + } + } - // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) - { - print ''.$langs->trans("Validate").''; - } else { - $langs->load("errors"); - print ''.$langs->trans("Validate").''; - } - } - } + // Validate + if ($object->status == $object::STATUS_DRAFT) + { + if ($permissiontoadd) + { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) + { + print ''.$langs->trans("Validate").''; + } else { + $langs->load("errors"); + print ''.$langs->trans("Validate").''; + } + } + } - // Clone - if ($permissiontoadd) - { - print ''.$langs->trans("ToClone").''; - } + // Clone + if ($permissiontoadd) + { + print ''.$langs->trans("ToClone").''; + } - // Cancel - Reopen - if ($permissiontoadd) - { - if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) - { - $arrayproduced = $object->fetchLinesLinked('produced', 0); - $nbProduced = 0; - foreach ($arrayproduced as $lineproduced) { - $nbProduced += $lineproduced['qty']; - } - if ($nbProduced > 0) { // If production has started, we can close it - print ''.$langs->trans("Close").''."\n"; - } else { - print 'transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").''."\n"; - } + // Cancel - Reopen + if ($permissiontoadd) + { + if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) + { + $arrayproduced = $object->fetchLinesLinked('produced', 0); + $nbProduced = 0; + foreach ($arrayproduced as $lineproduced) { + $nbProduced += $lineproduced['qty']; + } + if ($nbProduced > 0) { // If production has started, we can close it + print ''.$langs->trans("Close").''."\n"; + } else { + print 'transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").''."\n"; + } - print ''.$langs->trans("Cancel").''."\n"; - } + print ''.$langs->trans("Cancel").''."\n"; + } - if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) - { - print ''.$langs->trans("ReOpen").''."\n"; - } - } + if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) + { + print ''.$langs->trans("ReOpen").''."\n"; + } + } - // Delete (need delete permission, or if draft, just need create/modify permission) - if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) - { - print ''.$langs->trans('Delete').''."\n"; - } else { - print ''.$langs->trans('Delete').''."\n"; - } - } - print '
    '."\n"; + // Delete (need delete permission, or if draft, just need create/modify permission) + if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) + { + print ''.$langs->trans('Delete').''."\n"; + } else { + print ''.$langs->trans('Delete').''."\n"; + } + } + print '
    '."\n"; } @@ -672,37 +672,37 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action != 'presend') { - print '
    '; - print ''; // ancre + print '
    '; + print ''; // ancre - // Documents - $objref = dol_sanitizeFileName($object->ref); - $relativepath = $objref.'/'.$objref.'.pdf'; - $filedir = $conf->mrp->dir_output.'/'.$objref; - $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang); + // Documents + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->mrp->dir_output.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang); - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('mo')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('mo')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; + print '
    '; - $MAXEVENT = 10; + $MAXEVENT = 10; - $morehtmlright = ''; - $morehtmlright .= $langs->trans("SeeAll"); - $morehtmlright .= ''; + $morehtmlright = ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright); - print '
    '; + print '
    '; } //Select mail models is same action as presend diff --git a/htdocs/mrp/mo_list.php b/htdocs/mrp/mo_list.php index b9da34958d4..7734e992d48 100644 --- a/htdocs/mrp/mo_list.php +++ b/htdocs/mrp/mo_list.php @@ -92,7 +92,7 @@ $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alph $search = array(); foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); + if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); } // List of fields to search into when doing a "search in all" @@ -392,7 +392,7 @@ foreach ($object->fields as $key => $val) if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; diff --git a/htdocs/mrp/mo_movements.php b/htdocs/mrp/mo_movements.php index 754a83c4770..841e787361b 100644 --- a/htdocs/mrp/mo_movements.php +++ b/htdocs/mrp/mo_movements.php @@ -595,7 +595,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; //print ''; print ''; print ''; - print ''.$tmpproduct->getNomUrl(1).''; + print ''.$tmpproduct->getNomUrl(1); + print '
    '.$tmpproduct->label.''; + print ''; print ''.$line->qty.''; print ''; if ($alreadyproduced) { diff --git a/htdocs/product/admin/dynamic_prices.php b/htdocs/product/admin/dynamic_prices.php index aafc36ca256..bdd86169466 100644 --- a/htdocs/product/admin/dynamic_prices.php +++ b/htdocs/product/admin/dynamic_prices.php @@ -42,17 +42,17 @@ if (!$user->admin) accessforbidden(); //Objects $price_globals = new PriceGlobalVariable($db); if ($action == 'edit_variable') { - $res = $price_globals->fetch($selection); - if ($res < 1) { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } + $res = $price_globals->fetch($selection); + if ($res < 1) { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } } $price_updaters = new PriceGlobalVariableUpdater($db); if ($action == 'edit_updater') { - $res = $price_updaters->fetch($selection); - if ($res < 1) { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } + $res = $price_updaters->fetch($selection); + if ($res < 1) { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } } @@ -61,84 +61,84 @@ if ($action == 'edit_updater') { */ if (!empty($action) && empty($cancel)) { - //Global variable actions - if ($action == 'create_variable' || $action == 'edit_variable') { - $price_globals->code = GETPOSTISSET('code') ?GETPOST('code', 'alpha') : $price_globals->code; - $price_globals->description = GETPOSTISSET('description') ?GETPOST('description', 'restricthtml') : $price_globals->description; - $price_globals->value = GETPOSTISSET('value') ?GETPOST('value', 'int') : $price_globals->value; - //Check if record already exists only when saving - if (!empty($save)) { - foreach ($price_globals->listGlobalVariables() as $entry) { - if ($price_globals->id != $entry->id && dol_strtolower($price_globals->code) == dol_strtolower($entry->code)) { - setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); - $save = null; - } - } - } - } - if ($action == 'create_variable' && !empty($save)) { - $res = $price_globals->create($user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } - } elseif ($action == 'edit_variable' && !empty($save)) { - $res = $price_globals->update($user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } - } elseif ($action == 'delete_variable') { - $res = $price_globals->delete($selection, $user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } - } + //Global variable actions + if ($action == 'create_variable' || $action == 'edit_variable') { + $price_globals->code = GETPOSTISSET('code') ?GETPOST('code', 'alpha') : $price_globals->code; + $price_globals->description = GETPOSTISSET('description') ?GETPOST('description', 'restricthtml') : $price_globals->description; + $price_globals->value = GETPOSTISSET('value') ?GETPOST('value', 'int') : $price_globals->value; + //Check if record already exists only when saving + if (!empty($save)) { + foreach ($price_globals->listGlobalVariables() as $entry) { + if ($price_globals->id != $entry->id && dol_strtolower($price_globals->code) == dol_strtolower($entry->code)) { + setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); + $save = null; + } + } + } + } + if ($action == 'create_variable' && !empty($save)) { + $res = $price_globals->create($user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } + } elseif ($action == 'edit_variable' && !empty($save)) { + $res = $price_globals->update($user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } + } elseif ($action == 'delete_variable') { + $res = $price_globals->delete($selection, $user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } + } - //Updaters actions - if ($action == 'create_updater' || $action == 'edit_updater') { - $price_updaters->type = GETPOSTISSET('type') ? GETPOST('type', 'int') : $price_updaters->type; - $price_updaters->description = GETPOSTISSET('description') ? GETPOST('description', 'restricthtml') : $price_updaters->description; - $price_updaters->parameters = GETPOSTISSET('parameters') ? GETPOST('parameters', 'alphanohtml') : $price_updaters->parameters; - $price_updaters->fk_variable = GETPOSTISSET('fk_variable') ? GETPOST('fk_variable', 'int') : $price_updaters->fk_variable; - $price_updaters->update_interval = GETPOSTISSET('update_interval') ? GETPOST('update_interval', 'int') : $price_updaters->update_interval; - } - if ($action == 'create_updater' && !empty($save)) { - //Verify if process() works - $res = $price_updaters->process(); - if ($res > 0) { - $res = $price_updaters->create($user); - } - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } - } elseif ($action == 'edit_updater' && !empty($save)) { - //Verify if process() works - $res = $price_updaters->process(); - if ($res > 0) { - $res = $price_updaters->update($user); - } - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } - } elseif ($action == 'delete_updater') { - $res = $price_updaters->delete($selection, $user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } - } + //Updaters actions + if ($action == 'create_updater' || $action == 'edit_updater') { + $price_updaters->type = GETPOSTISSET('type') ? GETPOST('type', 'int') : $price_updaters->type; + $price_updaters->description = GETPOSTISSET('description') ? GETPOST('description', 'restricthtml') : $price_updaters->description; + $price_updaters->parameters = GETPOSTISSET('parameters') ? GETPOST('parameters', 'alphanohtml') : $price_updaters->parameters; + $price_updaters->fk_variable = GETPOSTISSET('fk_variable') ? GETPOST('fk_variable', 'int') : $price_updaters->fk_variable; + $price_updaters->update_interval = GETPOSTISSET('update_interval') ? GETPOST('update_interval', 'int') : $price_updaters->update_interval; + } + if ($action == 'create_updater' && !empty($save)) { + //Verify if process() works + $res = $price_updaters->process(); + if ($res > 0) { + $res = $price_updaters->create($user); + } + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } + } elseif ($action == 'edit_updater' && !empty($save)) { + //Verify if process() works + $res = $price_updaters->process(); + if ($res > 0) { + $res = $price_updaters->update($user); + } + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } + } elseif ($action == 'delete_updater') { + $res = $price_updaters->delete($selection, $user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } + } } elseif (!empty($cancel)) { - $action = ''; + $action = ''; } @@ -159,171 +159,171 @@ print '
    '; //Global variables table if ($action != 'create_updater' && $action != 'edit_updater') { - print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); + print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; //Space for buttons - print ''; + print '
    '.$langs->trans("Variable").''.$langs->trans("Description").''.$langs->trans("Value").' 
    '; + print ''; + print ''; + print ''; + print ''; + print ''; //Space for buttons + print ''; - $arrayglobalvars = $price_globals->listGlobalVariables(); - if (!empty($arrayglobalvars)) - { - foreach ($arrayglobalvars as $i=>$entry) { - $var = !$var; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - } else { - print ''; - } - print '
    '.$langs->trans("Variable").''.$langs->trans("Description").''.$langs->trans("Value").' 
    '.$entry->code.''.$entry->description.''.price($entry->value).'id.'">'.img_edit().'  '; - print 'id.'">'.img_delete().'
    '; - print $langs->trans("None"); - print '
    '; + $arrayglobalvars = $price_globals->listGlobalVariables(); + if (!empty($arrayglobalvars)) + { + foreach ($arrayglobalvars as $i=>$entry) { + $var = !$var; + print ''; + print ''.$entry->code.''; + print ''.$entry->description.''; + print ''.price($entry->value).''; + print 'id.'">'.img_edit().'  '; + print 'id.'">'.img_delete().''; + print ''; + } + } else { + print ''; + print $langs->trans("None"); + print ''; + } + print ''; - if (empty($action)) - { - //Action Buttons - print '
    '; - print ''.$langs->trans("AddVariable").''; - print '
    '; - //Separator is only need for updaters table is showed after buttons - print '

    '; - } + if (empty($action)) + { + //Action Buttons + print '
    '; + print ''.$langs->trans("AddVariable").''; + print '
    '; + //Separator is only need for updaters table is showed after buttons + print '

    '; + } } //Global variable editor if ($action == 'create_variable' || $action == 'edit_variable') { - //Form - print '
    '; - print ''; - print ''; - print ''; + //Form + print ''; + print ''; + print ''; + print ''; - //Table - print '
    '; - //Code - print ''; - print ''; - print ''; - print ''; - //Description - print ''; - print ''; - print ''; - print ''; - //Value - print ''; - print ''; - print ''; - print ''; - print '
    '.$langs->trans("Variable").'
    '.$langs->trans("Description").'
    '.$langs->trans("Value").'
    '; + //Table + print '
    '; + //Code + print ''; + print ''; + print ''; + print ''; + //Description + print ''; + print ''; + print ''; + print ''; + //Value + print ''; + print ''; + print ''; + print ''; + print '
    '.$langs->trans("Variable").'
    '.$langs->trans("Description").'
    '.$langs->trans("Value").'
    '; - //Form Buttons - print '
    '; - print '  '; - print ''; - print '
    '; - print '
    '; + //Form Buttons + print '
    '; + print '  '; + print ''; + print '
    '; + print ''; } // Updaters table if ($action != 'create_variable' && $action != 'edit_variable') { - print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); + print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; //Space for buttons - print ''; + print '
    '.$langs->trans("VariableToUpdate").''.$langs->trans("Description").''.$langs->trans("Type").''.$langs->trans("Parameters").''.$langs->trans("UpdateInterval").''.$langs->trans("LastUpdated").' 
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; //Space for buttons + print ''; - $arraypriceupdaters = $price_updaters->listUpdaters(); - if (!empty($arraypriceupdaters)) - { - foreach ($arraypriceupdaters as $i=>$entry) { - $code = ""; - if ($entry->fk_variable > 0) { - $res = $price_globals->fetch($entry->fk_variable); - if ($res > 0) { - $code = $price_globals->code; - } - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - } else { - print ''; - } - print '
    '.$langs->trans("VariableToUpdate").''.$langs->trans("Description").''.$langs->trans("Type").''.$langs->trans("Parameters").''.$langs->trans("UpdateInterval").''.$langs->trans("LastUpdated").' 
    '.$code.''.$entry->description.''.$langs->trans("GlobalVariableUpdaterType".$entry->type).''.$entry->parameters.''.$entry->update_interval.''.$entry->getLastUpdated().'id.'">'.img_edit().'  '; - print 'id.'">'.img_delete().'
    '; - print $langs->trans("None"); - print '
    '; + $arraypriceupdaters = $price_updaters->listUpdaters(); + if (!empty($arraypriceupdaters)) + { + foreach ($arraypriceupdaters as $i=>$entry) { + $code = ""; + if ($entry->fk_variable > 0) { + $res = $price_globals->fetch($entry->fk_variable); + if ($res > 0) { + $code = $price_globals->code; + } + } + print ''; + print ''.$code.''; + print ''.$entry->description.''; + print ''.$langs->trans("GlobalVariableUpdaterType".$entry->type).''; + print ''.$entry->parameters.''; + print ''.$entry->update_interval.''; + print ''.$entry->getLastUpdated().''; + print 'id.'">'.img_edit().'  '; + print 'id.'">'.img_delete().''; + print ''; + } + } else { + print ''; + print $langs->trans("None"); + print ''; + } + print ''; - if (empty($action)) - { - //Action Buttons - print '
    '; - print ''.$langs->trans("AddUpdater").''; - print '
    '; - } + if (empty($action)) + { + //Action Buttons + print '
    '; + print ''.$langs->trans("AddUpdater").''; + print '
    '; + } } //Updater editor if ($action == 'create_updater' || $action == 'edit_updater') { - //Form - print '
    '; - print ''; - print ''; - print ''; + //Form + print ''; + print ''; + print ''; + print ''; - //Table - print '
    '; - //Code - print ''; - print ''; - //Description - print ''; - print ''; - print ''; - print ''; - //Type - print ''; - print ''; - //Parameters - print ''; - $help = $langs->trans("GlobalVariableUpdaterHelp".$type).'
    '.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).''; - print ''; - print ''; - //Interval - print ''; - print ''; - print ''; - print ''; - print '
    '.$langs->trans("VariableToUpdate").''; - $globals_list = array(); - foreach ($price_globals->listGlobalVariables() as $entry) { - $globals_list[$entry->id] = $entry->code; - } - print $form->selectarray('fk_variable', $globals_list, (empty($price_updaters->fk_variable) ? 0 : $price_updaters->fk_variable)); - print '
    '.$langs->trans("Description").'
    '.$langs->trans("Type").''; - $type = empty($price_updaters->type) ? 0 : $price_updaters->type; - $type_list = array(); - foreach ($price_updaters->types as $val) { - $type_list[$val] = $langs->trans("GlobalVariableUpdaterType".$val); - } - print $form->selectarray('type', $type_list, $type); - // This code submits form when type is changed - print ''; - print '
    '.$form->textwithpicto($langs->trans("Parameters"), $help, 1).''; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%'); - $doleditor->Create(); - print '
    '.$langs->trans("UpdateInterval").'
    '; + print ''; + //Parameters + print ''; + $help = $langs->trans("GlobalVariableUpdaterHelp".$type).'
    '.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).''; + print ''.$form->textwithpicto($langs->trans("Parameters"), $help, 1).''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%'); + $doleditor->Create(); + print ''; + print ''; + //Interval + print ''; + print ''.$langs->trans("UpdateInterval").''; + print ''; + print ''; + print ''; - //Form Buttons - print '
    '; - print '  '; - print ''; - print '
    '; - print '
    '; + //Form Buttons + print '
    '; + print '  '; + print ''; + print '
    '; + print ''; } // End of page diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 4970679eb87..62813ee2a57 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -301,8 +301,8 @@ if (empty($reshook)) $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private', 'restricthtml')); $object->note = $object->note_private; // deprecated $object->customcode = GETPOST('customcode', 'alphanohtml'); - $object->country_id = GETPOST('country_id', 'int'); - $object->state_id = GETPOST('state_id', 'int'); + $object->country_id = GETPOST('country_id', 'int'); + $object->state_id = GETPOST('state_id', 'int'); $object->duration_value = $duration_value; $object->duration_unit = $duration_unit; $object->fk_default_warehouse = GETPOST('fk_default_warehouse'); @@ -321,8 +321,19 @@ if (empty($reshook)) $object->surface_units = GETPOST('surface_units'); // This is not the fk_unit but the power of unit $object->volume = GETPOST('volume'); $object->volume_units = GETPOST('volume_units'); // This is not the fk_unit but the power of unit - $object->finished = GETPOST('finished', 'alpha'); - $object->fk_unit = GETPOST('units', 'alpha'); // This is the fk_unit of sale + $finished = GETPOST('finished', 'int'); + if ($finished > 0) { + $object->finished = $finished; + } else { + $object->finished = null; + } + + $units = GETPOST('units', 'int'); + if ($units > 0) { + $object->fk_unit = $units; + } else { + $object->fk_unit = null; + } $accountancy_code_sell = GETPOST('accountancy_code_sell', 'alpha'); $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); @@ -435,10 +446,15 @@ if (empty($reshook)) $object->surface_units = GETPOST('surface_units'); // This is not the fk_unit but the power of unit $object->volume = GETPOST('volume'); $object->volume_units = GETPOST('volume_units'); // This is not the fk_unit but the power of unit - $object->finished = GETPOST('finished', 'alpha'); + + $finished = GETPOST('finished', 'int'); + if ($finished >= 0) { + $object->finished = $finished; + } else { + $object->finished = null; + } $units = GETPOST('units', 'int'); - if ($units > 0) { $object->fk_unit = $units; } else { @@ -965,14 +981,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $linkback = ""; print load_fiche_titre($title, $linkback, $picto); - // We set country_id, country_code and country for the selected country - $object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null; - if ($object->country_id > 0) - { - $tmparray = getCountry($object->country_id, 'all'); - $object->country_code = $tmparray['code']; - $object->country = $tmparray['label']; - } + // We set country_id, country_code and country for the selected country + $object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null; + if ($object->country_id > 0) + { + $tmparray = getCountry($object->country_id, 'all'); + $object->country_code = $tmparray['code']; + $object->country = $tmparray['label']; + } dol_fiche_head(''); @@ -1151,26 +1167,26 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Origin country print ''.$langs->trans("CountryOrigin").''; print ''; - print img_picto('', 'globe-americas', 'class="paddingrightonly"'); - print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print img_picto('', 'globe-americas', 'class="paddingrightonly"'); + print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx'); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print ''; - // State - if (empty($conf->global->PRODUCT_DISABLE_STATE)) - { - if ($conf->browser->layout == 'phone') print ''; - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) - { - print ''.$form->editfieldkey('Region-StateOrigine', 'state_id', '', $object, 0).''; - } else { - print ''.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).''; - } + // State + if (empty($conf->global->PRODUCT_DISABLE_STATE)) + { + if ($conf->browser->layout == 'phone') print ''; + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) + { + print ''.$form->editfieldkey('Region-StateOrigine', 'state_id', '', $object, 0).''; + } else { + print ''.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).''; + } print $formcompany->select_state($object->state_id, $object->country_code); - print ''; - } - print ''; + print ''; + } + print ''; } // Other attributes @@ -1547,8 +1563,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } else { // Nature print ''.$form->textwithpicto($langs->trans("NatureOfProductShort"), $langs->trans("NatureOfProductDesc")).''; - $statutarray = array('-1'=>' ', '1' => $langs->trans("Finished"), '0' => $langs->trans("RowMaterial")); - print $form->selectarray('finished', $statutarray, $object->finished); + print $formproduct->selectProductNature('finished', $object->finished); print ''; // Brut Weight @@ -1616,7 +1631,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // State if (empty($conf->global->PRODUCT_DISABLE_STATE)) { - if ($conf->browser->layout == 'phone') print ''; + if ($conf->browser->layout == 'phone') print ''; if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) { print ''.$form->editfieldkey('Region-StateOrigine', 'state_id', '', $object, 0).''; @@ -2389,7 +2404,7 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete') $objectref = dol_sanitizeFileName($object->ref); $relativepath = $comref.'/'.$objectref.'.pdf'; if (!empty($conf->product->multidir_output[$object->entity])) { - $filedir = $conf->product->multidir_output[$object->entity].'/'.$objectref; //Check repertories of current entities + $filedir = $conf->product->multidir_output[$object->entity].'/'.$objectref; //Check repertories of current entities } else { $filedir = $conf->product->dir_output.'/'.$objectref; } diff --git a/htdocs/product/class/html.formproduct.class.php b/htdocs/product/class/html.formproduct.class.php index a0fd2bdb10c..0de89bf78ff 100644 --- a/htdocs/product/class/html.formproduct.class.php +++ b/htdocs/product/class/html.formproduct.class.php @@ -425,6 +425,75 @@ class FormProduct return $return; } + /** + * Return a combo box with list of units + * NAture of product labels are defined in llx_c_product_nature + * + * @param string $name Name of HTML field + * @param string $selected Preselected value + * @param int $mode 1=Use label as value, 0=Use code + * @param int $showempty 1=show empty value, 0= no + * @return string + */ + public function selectProductNature($name = 'finished', $selected = '', $mode = 0, $showempty = 1) + { + global $langs, $db; + + $langs->load('products'); + + $return = ''; + + // TODO Use a cache + require_once DOL_DOCUMENT_ROOT.'/core/class/cproductnature.class.php'; + $productNature = new CProductNature($db); + + $filter = array(); + $filter['t.active'] = 1; + + $result = $productNature->fetchAll( + '', + '', + 0, + 0, + $filter + ); + if ($result < 0) { + dol_print_error($db); + return -1; + } else { + $return .= ''; + } + + return $return; + } + /** * Return list of lot numbers (stock from product_batch) with stock location and stock qty * diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 18565347072..2aa9b3330e3 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -983,7 +983,7 @@ class Product extends CommonObject $sql .= ", tosell = ".(int) $this->status; $sql .= ", tobuy = ".(int) $this->status_buy; $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch); - $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0) ? "null" : (int) $this->finished); + $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? "null" : (int) $this->finished); $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null'); $sql .= ", net_measure_units = ".($this->net_measure_units != '' ? "'".$this->db->escape($this->net_measure_units)."'" : 'null'); $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null'); @@ -2357,6 +2357,129 @@ class Product extends CommonObject } } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge tableau des stats OF pour le produit/service + * + * @param int $socid Id societe + * @return integer Tableau des stats dans $this->stats_mo, <0 if ko >0 if ok + */ + public function load_stats_mo($socid = 0) + { + // phpcs:enable + global $user, $hookmanager; + + $error=0; + + foreach (array('toconsume','consumed','toproduce','produced') as $role) { + $this->stats_mo['customers_'.$role] = 0; + $this->stats_mo['nb_'.$role] = 0; + $this->stats_mo['qty_'.$role] = 0; + + $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,"; + $sql .= " SUM(mp.qty) as qty"; + $sql .= " FROM ".MAIN_DB_PREFIX."mrp_mo as c"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."mrp_production as mp ON mp.fk_mo=c.rowid"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= "INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".$user->id; + } + $sql .= " WHERE "; + $sql .= " c.entity IN (".getEntity('mo').")"; + + $sql .= " AND mp.fk_product =".$this->id; + $sql .= " AND mp.role ='".$this->db->escape($role)."'"; + if ($socid > 0) { + $sql .= " AND c.fk_soc = ".$socid; + } + + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0; + $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0; + $this->stats_mo['qty_'.$role] = $obj->qty ? $obj->qty : 0; + } else { + $this->error = $this->db->error(); + $error++; + } + } + + if (!empty($error)) { + return -1; + } + + $parameters = array('socid' => $socid); + $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action); + if ($reshook > 0) $this->stats_mo = $hookmanager->resArray['stats_mo']; + + return 1; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Charge tableau des stats OF pour le produit/service + * + * @param int $socid Id societe + * @return integer Tableau des stats dans $this->stats_mo, <0 if ko >0 if ok + */ + public function load_stats_bom($socid = 0) + { + // phpcs:enable + global $user, $hookmanager; + + $error=0; + + $this->stats_bom['nb_toproduce'] = 0; + $this->stats_bom['nb_toconsume'] = 0; + $this->stats_bom['qty_toproduce'] = 0; + $this->stats_bom['qty_toconsume'] = 0; + + $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,"; + $sql .= " b.qty as qty_toproduce"; + $sql .= " FROM ".MAIN_DB_PREFIX."bom_bom as b"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bom_bomline as bl ON bl.fk_bom=b.rowid"; + $sql .= " WHERE "; + $sql .= " b.entity IN (".getEntity('bom').")"; + $sql .= " AND b.fk_product =".$this->id; + + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_bom['nb_toproduce'] = $obj->nb_toproduce ? $obj->nb_toproduce : 0; + $this->stats_bom['qty_toproduce'] = $obj->qty_toproduce ? price2num($obj->qty_toproduce) : 0; + } else { + $this->error = $this->db->error(); + $error++; + } + + $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,"; + $sql .= " SUM(bl.qty) as qty_toconsume"; + $sql .= " FROM ".MAIN_DB_PREFIX."bom_bom as b"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bom_bomline as bl ON bl.fk_bom=b.rowid"; + $sql .= " WHERE "; + $sql .= " b.entity IN (".getEntity('bom').")"; + $sql .= " AND bl.fk_product =".$this->id; + + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + $this->stats_bom['nb_toconsume'] = $obj->nb_toconsume ? $obj->nb_toconsume : 0; + $this->stats_bom['qty_toconsume'] = $obj->qty_toconsume ? price2num($obj->qty_toconsume) : 0; + } else { + $this->error = $this->db->error(); + $error++; + } + + if (!empty($error)) { + return -1; + } + + $parameters = array('socid' => $socid); + $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action); + if ($reshook > 0) $this->stats_bom = $hookmanager->resArray['stats_bom']; + + return 1; + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** @@ -4562,10 +4685,21 @@ class Product extends CommonObject global $langs; $langs->load('products'); - if ($this->finished == '0') { return $langs->trans("RowMaterial"); - } - if ($this->finished == '1') { return $langs->trans("Finished"); + if (isset($this->finished) && $this->finished>=0) { + $sql = 'SELECT label, code FROM '.MAIN_DB_PREFIX.'c_product_nature where code='.((int) $this->finished).' AND active=1'; + $resql = $this->db->query($sql); + if ($resql && $this->db->num_rows($resql) > 0) { + $res = $this->db->fetch_array($resql); + $label = $langs->trans($res['label']); + $this->db->free($resql); + return $label; + } else { + $this->error = $this->db->error().' sql='.$sql; + dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR); + return -1; + } } + return ''; } diff --git a/htdocs/product/class/productcustomerprice.class.php b/htdocs/product/class/productcustomerprice.class.php index 1553869d1f1..25a3c5cd836 100644 --- a/htdocs/product/class/productcustomerprice.class.php +++ b/htdocs/product/class/productcustomerprice.class.php @@ -368,7 +368,7 @@ class Productcustomerprice extends CommonObject } elseif ($key == 'prod.ref' || $key == 'prod.label') { $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; } elseif ($key == 't.price' || $key == 't.price_ttc') { - $sql .= ' AND ' . $key . ' LIKE \'%' . price2num($value) . '%\''; + $sql .= ' AND '.$key.' LIKE \'%'.price2num($value).'%\''; } else { $sql .= ' AND '.$key.' = '.((int) $value); } diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index fb1be576ad5..d7bf7c44ae1 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -169,7 +169,7 @@ if (empty($reshook)) $supplier_description = GETPOST('supplier_description', 'alpha'); $barcode = GETPOST('barcode', 'alpha'); $fk_barcode_type = GETPOST('fk_barcode_type', 'int'); - $packaging = GETPOST('packaging', 'int'); + $packaging = price2num(GETPOST("packaging", 'alphanohtml'), 'MS'); if ($tva_tx == '') { @@ -230,12 +230,6 @@ if (empty($reshook)) } } - if (empty($packaging)) $packaging = 1; - - if ($packaging < $quantity) $packaging = $quantity; - - $object->packaging = $packaging; - if (!$error) { $db->begin(); @@ -296,6 +290,10 @@ if (empty($reshook)) $newprice = price2num(GETPOST("price", "alpha")); + if (empty($packaging)) $packaging = 1; + if ($packaging < $quantity) $packaging = $quantity; + $object->packaging = $packaging; + if ($conf->multicurrency->enabled) { $multicurrency_tx = price2num(GETPOST("multicurrency_tx", 'alpha')); @@ -529,6 +527,23 @@ if ($id > 0 || $ref) } print ''; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + // Packaging + print ''; + + print ''.$form->textwithpicto($langs->trans("PackagingForThisProduct"), $langs->trans("PackagingForThisProductDesc")).''; + print ''; + $packaging = GETPOSTISSET('packaging') ? price2num(GETPOST('packaging', 'nohtml'), 'MS') : ((empty($rowid))?"1":price2num($object->packaging, 'MS')); + print ''; + + // Units + if ($conf->global->PRODUCT_USE_UNITS) { + $unit = $object->getLabelOfUnit(); + if ($unit !== '') { + print '  '.$langs->trans($unit); + } + } + } // Vat rate $default_vat = ''; diff --git a/htdocs/product/inventory/list.php b/htdocs/product/inventory/list.php index 09947e80ac7..5a19906d088 100644 --- a/htdocs/product/inventory/list.php +++ b/htdocs/product/inventory/list.php @@ -371,7 +371,7 @@ foreach ($object->fields as $key => $val) if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; diff --git a/htdocs/product/list.php b/htdocs/product/list.php index a0bfa073afa..db77e7714f1 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -40,6 +40,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; @@ -75,6 +76,7 @@ $search_accountancy_code_sell_export = GETPOST("search_accountancy_code_sell_exp $search_accountancy_code_buy = GETPOST("search_accountancy_code_buy", 'alpha'); $search_accountancy_code_buy_intra = GETPOST("search_accountancy_code_buy_intra", 'alpha'); $search_accountancy_code_buy_export = GETPOST("search_accountancy_code_buy_export", 'alpha'); +$search_finished = GETPOST("search_finished", 'int'); $optioncss = GETPOST('optioncss', 'alpha'); $type = GETPOST("type", "int"); @@ -109,6 +111,7 @@ $hookmanager->initHooks(array('productservicelist')); $extrafields = new ExtraFields($db); $form = new Form($db); $formcompany = new FormCompany($db); +$formproduct = new FormProduct($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -212,7 +215,7 @@ $arrayfields = array( 'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>60), 'p.fk_country'=>array('label'=>$langs->trans("Country"), 'checked'=>0, 'position'=>100), 'p.fk_state'=>array('label'=>$langs->trans("State"), 'checked'=>0, 'position'=>101), - 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0, 'position'=>400), + 'p.accountancy_code_sell'=>array('label'=>$langs->trans("ProductAccountancySellCode"), 'checked'=>0, 'position'=>400), 'p.accountancy_code_sell_intra'=>array('label'=>$langs->trans("ProductAccountancySellIntraCode"), 'checked'=>0, 'enabled'=>$isInEEC, 'position'=>401), 'p.accountancy_code_sell_export'=>array('label'=>$langs->trans("ProductAccountancySellExportCode"), 'checked'=>0, 'position'=>402), 'p.accountancy_code_buy'=>array('label'=>$langs->trans("ProductAccountancyBuyCode"), 'checked'=>0, 'position'=>403), @@ -285,6 +288,7 @@ if (empty($reshook)) $search_state = ""; $search_vatrate = ""; $search_tobatch = ''; + $search_finished = ''; //$search_type=''; // There is 2 types of list: a list of product and a list of services. No list with both. So when we clear search criteria, we must keep the filter on type. $show_childproducts = ''; @@ -409,6 +413,7 @@ if ($fourn_id > 0) $sql .= " AND pfp.fk_soc = ".$fourn_id; if ($search_tobatch != '' && $search_tobatch >= 0) $sql .= " AND p.tobatch = ".$db->escape($search_tobatch); if ($search_country) $sql .= " AND p.fk_country = ".$search_country; if ($search_state) $sql .= " AND p.fk_state = ".$search_state; +if ($search_finished>=0 && $search_finished!=='') $sql .= " AND p.finished = ".$search_finished; if ($search_accountancy_code_sell) $sql .= natural_search('p.accountancy_code_sell', $search_accountancy_code_sell); if ($search_accountancy_code_sell_intra) $sql .= natural_search('p.accountancy_code_sell_intra', $search_accountancy_code_sell_intra); if ($search_accountancy_code_sell_export) $sql .= natural_search('p.accountancy_code_sell_export', $search_accountancy_code_sell_export); @@ -522,6 +527,7 @@ if ($resql) if ($search_accountancy_code_buy) $param = "&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); if ($search_accountancy_code_buy_intra) $param = "&search_accountancy_code_buy_intra=".urlencode($search_accountancy_code_buy_intra); if ($search_accountancy_code_buy_export) $param = "&search_accountancy_code_buy_export=".urlencode($search_accountancy_code_buy_export); + if ($search_finished) $param = "&search_finished=".urlencode($search_finished); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -593,7 +599,7 @@ if ($resql) // Filter on categories $moreforfilter = ''; - if (!empty($conf->categorie->enabled)) + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('Categories').': '; @@ -677,6 +683,7 @@ if ($resql) if (!empty($arrayfields['p.finished']['checked'])) { print ''; + print $formproduct->selectProductNature('search_finished', $search_finished); print ''; } // Weight diff --git a/htdocs/product/price.php b/htdocs/product/price.php index 847292fa367..c97e22b9166 100644 --- a/htdocs/product/price.php +++ b/htdocs/product/price.php @@ -90,94 +90,94 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { - $search_soc = ''; - } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers + { + $search_soc = ''; + } - if ($action == 'setlabelsellingprice' && $user->admin) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; - $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel'); - dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice', 'alpha'), 'chaine', 0, '', $conf->entity); - $action = ''; - } + if ($action == 'setlabelsellingprice' && $user->admin) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; + $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel'); + dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice', 'alpha'), 'chaine', 0, '', $conf->entity); + $action = ''; + } if (($action == 'update_vat') && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) { - $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' + $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' - // We must define tva_tx, npr and local taxes - $tva_tx = $tva_tx_txt; - $vatratecode = ''; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. - } + // We must define tva_tx, npr and local taxes + $tva_tx = $tva_tx_txt; + $vatratecode = ''; + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + $vat_src_code = $reg[1]; + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot - $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; - $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; - // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in create product. - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } - } + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; + $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; + // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in create product. + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } + } - $object->default_vat_code = $vatratecode; - $object->tva_tx = $tva_tx; - $object->tva_npr = $npr; - $object->localtax1_tx = $localtax1; - $object->localtax2_tx = $localtax2; - $object->localtax1_type = $localtax1_type; - $object->localtax2_type = $localtax2_type; + $object->default_vat_code = $vatratecode; + $object->tva_tx = $tva_tx; + $object->tva_npr = $npr; + $object->localtax1_tx = $localtax1; + $object->localtax2_tx = $localtax2; + $object->localtax1_type = $localtax1_type; + $object->localtax2_type = $localtax2_type; - $db->begin(); + $db->begin(); - $resql = $object->update($object->id, $user); - if ($resql <= 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } + $resql = $object->update($object->id, $user); + if ($resql <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } - if ($error) - { - //$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2); - $localtaxarray = array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them. - $object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode); - } + if ($error) + { + //$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2); + $localtaxarray = array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them. + $object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode); + } - if (!$error) - { - $db->commit(); - } else { - $db->rollback(); - } + if (!$error) + { + $db->commit(); + } else { + $db->rollback(); + } - $action = ''; + $action = ''; } if (($action == 'update_price') && !$cancel && $object->getRights()->creer) - { + { $error = 0; $pricestoupdate = array(); @@ -231,41 +231,41 @@ if (empty($reshook)) } $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot - $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; + $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = $newlocaltax1_tx[$i]; $localtax1_type = $newlocaltax1_type[$i]; $localtax2 = $newlocaltax2_tx[$i]; $localtax2_type = $newlocaltax2_type[$i]; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } - } + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } + } $pricestoupdate[$i] = array( 'price' => $newprice[$i], 'price_min' => $newprice_min[$i], 'price_base_type' => $newpricebase[$i], - 'default_vat_code' => $vatratecode, + 'default_vat_code' => $vatratecode, 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future 'npr' => $npr, // default_vat_code should be used in priority in a future - 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future + 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future ); //If autogeneration is enabled, then we only set the first level @@ -286,45 +286,45 @@ if (empty($reshook)) } $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot - $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; - $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; - // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; + $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; + $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; + // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; - // If spain, we don't use the localtax found into tax record in database with same code, but using the get_localtax rule - if (in_array($mysoc->country_code, array('ES'))) - { - $localtax1 = get_localtax($tva_tx, 1); - $localtax2 = get_localtax($tva_tx, 2); - } - } - } + // If spain, we don't use the localtax found into tax record in database with same code, but using the get_localtax rule + if (in_array($mysoc->country_code, array('ES'))) + { + $localtax1 = get_localtax($tva_tx, 1); + $localtax2 = get_localtax($tva_tx, 2); + } + } + } $pricestoupdate[0] = array( 'price' => $_POST["price"], 'price_min' => $_POST["price_min"], 'price_base_type' => $_POST["price_base_type"], - 'default_vat_code' => $vatratecode, + 'default_vat_code' => $vatratecode, 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future 'npr' => $npr, // default_vat_code should be used in priority in a future - 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future + 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future ); } @@ -348,7 +348,7 @@ if (empty($reshook)) } if ($object->multiprices[$key] != $newprice || $object->multiprices_min[$key] != $newprice_min || $object->multiprices_base_type[$key] != $val['price_base_type']) - $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); + $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); else $res = 0; @@ -520,24 +520,24 @@ if (empty($reshook)) // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } } $prodcustprice->default_vat_code = $vatratecode; @@ -550,14 +550,14 @@ if (empty($reshook)) if (!($prodcustprice->fk_soc > 0)) { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); - $error++; - $action = 'add_customer_price'; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); + $error++; + $action = 'add_customer_price'; } if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier) { - $langs->load("errors"); + $langs->load("errors"); setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')), null, 'errors'); $error++; $action = 'add_customer_price'; @@ -620,24 +620,24 @@ if (empty($reshook)) // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } } $prodcustprice->default_vat_code = $vatratecode; @@ -770,22 +770,22 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ //print vatrate($object->multiprices_tva_tx[$soc->price_level], true); print ''; } else { - // TVA - print ''.$langs->trans("DefaultTaxRate").''; + // TVA + print ''.$langs->trans("DefaultTaxRate").''; - $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; - echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) { print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; } else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ - print ''; + print ''; } } else { if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility @@ -795,28 +795,28 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print ''.vatrate($object->multiprices_tva_tx[1], true).''; print ''; } else { - // TVA - print ''.$langs->trans("DefaultTaxRate").''; + // TVA + print ''.$langs->trans("DefaultTaxRate").''; - $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; - echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); - /* + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); + /* if ($object->default_vat_code) { print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; } else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ - print ''; + print ''; } - print ''; + print ''; - print '
    '; + print '
    '; - print ''; + print '
    '; print ''; @@ -875,7 +875,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form included into a tr instead of a td { print ''; + print '   '.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().''; } print ''; print ''; @@ -1282,8 +1282,8 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '
    '; } else { - print ''."\n"; - ?> + print ''."\n"; + ?> '; + print dolButtonToOpenUrlInDialogPopup('categories', $langs->transnoentitiesnoconv("Categories"), '', '/categories/index.php?leftmenu=website&nosearch=1&type=website_page&website='.$website->ref, $disabled); } print ''; @@ -2451,28 +2434,28 @@ if (!GETPOST('hide_websitemenu')) $htmltext = ''; if (empty($object->fk_default_home)) { - $htmltext .= '
    '.$langs->trans("YouMustDefineTheHomePage").'

    '; + $htmltext .= '
    '.$langs->trans("YouMustDefineTheHomePage").'

    '; } elseif (empty($virtualurl)) { - //$htmltext .= '
    '.$langs->trans("VirtualHostUrlNotDefined").'

    '; + //$htmltext .= '
    '.$langs->trans("VirtualHostUrlNotDefined").'

    '; } else { - $htmltext .= '
    '.$langs->trans("GoTo").' '.$virtualurl.'

    '; + $htmltext .= '
    '.$langs->trans("GoTo").' '.$virtualurl.'

    '; } if (!empty($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER)) { - $htmltext .= '
    '.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER); + $htmltext .= '
    '.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER); } else { - $htmltext .= $langs->trans("SetHereVirtualHost", $dataroot); - $htmltext .= '
    '; - $htmltext .= '
    '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); - $htmltext .= '
    '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website
    '.DOL_DATA_ROOT.'/medias'); + $htmltext .= $langs->trans("SetHereVirtualHost", $dataroot); + $htmltext .= '
    '; + $htmltext .= '
    '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); + $htmltext .= '
    '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website
    '.DOL_DATA_ROOT.'/medias'); - $examplewithapache = '#php_admin_value open_basedir /tmp/:'.DOL_DOCUMENT_ROOT.':'.DOL_DATA_ROOT.':/dev/urandom'."\n"; - $examplewithapache .= ''."\n"; - $examplewithapache .= 'AllowOverride FileInfo Options + $examplewithapache = '#php_admin_value open_basedir /tmp/:'.DOL_DOCUMENT_ROOT.':'.DOL_DATA_ROOT.':/dev/urandom'."\n"; + $examplewithapache .= ''."\n"; + $examplewithapache .= 'AllowOverride FileInfo Options Options -Indexes -MultiViews -FollowSymLinks -ExecCGI Require all granted @@ -2487,14 +2470,14 @@ if (!GETPOST('hide_websitemenu')) Require all granted '; - $htmltext .= '
    '.$langs->trans("ExampleToUseInApacheVirtualHostConfig").':
    '; - $htmltext .= '
    '.dol_nl2br(dol_escape_htmltag($examplewithapache, 1, 1)).'
    '; + $htmltext .= '
    '.$langs->trans("ExampleToUseInApacheVirtualHostConfig").':
    '; + $htmltext .= '
    '.dol_nl2br(dol_escape_htmltag($examplewithapache, 1, 1)).'
    '; - $htmltext .= '
    '; - $htmltext .= $langs->trans("YouCanAlsoTestWithPHPS", $dataroot); - $htmltext .= '
    '; - $htmltext .= '
    '; - $htmltext .= $langs->trans("YouCanAlsoDeployToAnotherWHP"); + $htmltext .= '
    '; + $htmltext .= $langs->trans("YouCanAlsoTestWithPHPS", $dataroot); + $htmltext .= '
    '; + $htmltext .= '
    '; + $htmltext .= $langs->trans("YouCanAlsoDeployToAnotherWHP"); } print $form->textwithpicto($linktotestonwebserver, $htmltext, 1, 'none', 'valignmiddle', 0, 3, 'helpvirtualhost'); print '
    '; @@ -2835,14 +2818,14 @@ if (!GETPOST('hide_websitemenu')) $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource2", $url); $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceMore", $url); $htmltext .= '
    '; - if ($conf->browser->layout == 'phone') - { - print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution'); - } - else { - //img_help(($tooltiptrigger != '' ? 2 : 1), $alt) - print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution'); - } + if ($conf->browser->layout == 'phone') + { + print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution'); + } + else { + //img_help(($tooltiptrigger != '' ? 2 : 1), $alt) + print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution'); + } } print ''; // end websitehelp @@ -3583,16 +3566,16 @@ if ($action == 'editmeta' || $action == 'createcontainer') } print ''; + print 'ObjectClass'; + print ''; - print ''; + print ''; $fuser = new User($db); @@ -3602,8 +3585,8 @@ if ($action == 'editmeta' || $action == 'createcontainer') print ''; + print ''; - print '
    '; print $langs->trans("PriceLevel"); if ($user->admin) print ' id.'">'.img_edit($langs->trans('EditSellingPriceLabel'), 0).''; @@ -834,17 +834,17 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; if (preg_match('/editlabelsellingprice/', $action)) { - print '
    '; - print ''; - print ''; - print ''; - print $langs->trans("SellingPrice").' '.$i.' - '; - print ''; - print ' '; - print '
    '; + print '
    '; + print ''; + print ''; + print ''; + print $langs->trans("SellingPrice").' '.$i.' - '; + print ''; + print ' '; + print '
    '; } else { - print $langs->trans("SellingPrice").' '.$i; - if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + print $langs->trans("SellingPrice").' '.$i; + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); } print '
    '.$langs->trans("PriceByQuantity").' '.$i; - if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); print ''; if ($object->prices_by_qty[$i] == 1) { @@ -1102,7 +1102,7 @@ if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $a { print "\n".'
    '."\n"; - if ($object->isVariant()) { + if ($object->isVariant()) { if ($user->rights->produit->creer || $user->rights->service->creer) { print ''; } @@ -1128,7 +1128,7 @@ if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $a print ''; } } - } + } print "\n
    \n"; } @@ -1176,7 +1176,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - print ''."\n"; + print ''."\n"; print '
    '; print ''; print ''; @@ -1262,7 +1262,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) } if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { - print '   '.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'
    '; - print 'ObjectClass'; - print ''; - print ''; - print '
    '; + print ''; + print '
    '; - print 'ObjectID'; - print ''; - print ''; - print '
    '; + print 'ObjectID'; + print ''; + print ''; + print '
    '; if ($pageauthorid > 0) { - $fuser->fetch($pageauthorid); - print $fuser->getNomUrl(1); + $fuser->fetch($pageauthorid); + print $fuser->getNomUrl(1); } else { print ''.$langs->trans("Unknown").''; } @@ -3624,17 +3607,17 @@ if ($action == 'editmeta' || $action == 'createcontainer') if ($action != 'createcontainer') { - print '
    '; - print $langs->trans('UserModif'); - print ''; - if ($pageusermodifid > 0) - { - $fuser->fetch($pageusermodifid); - print $fuser->getNomUrl(1); - } - print '
    '; + print $langs->trans('UserModif'); + print ''; + if ($pageusermodifid > 0) + { + $fuser->fetch($pageusermodifid); + print $fuser->getNomUrl(1); + } + print '
    '; + print '
    '; print $langs->trans('DateModification'); print ''; print dol_print_date($pagedatemodification, 'dayhour', 'tzuser'); @@ -4249,7 +4232,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa // Change the contenteditable to "true" or "false" when mode Edit Inline is on or off if (empty($conf->global->WEBSITE_EDITINLINE)) { - // Remove the contenteditable="true" + // Remove the contenteditable="true" $newcontent = preg_replace('/(div|section)(\s[^\>]*)contenteditable="true"/', '\1\2', $newcontent); } else { diff --git a/htdocs/website/websiteaccount_card.php b/htdocs/website/websiteaccount_card.php index 403128a0f8b..1c976ecc74b 100644 --- a/htdocs/website/websiteaccount_card.php +++ b/htdocs/website/websiteaccount_card.php @@ -55,7 +55,7 @@ $search_all = GETPOST("search_all", 'alpha'); $search = array(); foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); + if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); } if (empty($action) && empty($id) && empty($ref)) $action = 'view'; @@ -198,7 +198,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea { if ($object->fk_soc > 0 && empty($socid)) $socid = $object->fk_soc; - $res = $object->fetch_optionals(); + $res = $object->fetch_optionals(); $head = websiteaccountPrepareHead($object); dol_fiche_head($head, 'card', $langs->trans("WebsiteAccount"), -1, 'websiteaccount@website'); @@ -207,7 +207,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1); } // Call Hook formConfirm @@ -298,24 +298,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Buttons for actions if ($action != 'presend' && $action != 'editline') { - print '
    '."\n"; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print '
    '."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) - { - // Send - if (empty($user->socid)) { - print ''."\n"; - } + if (empty($reshook)) + { + // Send + if (empty($user->socid)) { + print ''."\n"; + } - if ($user->rights->website->write) - { - print ''."\n"; - } + if ($user->rights->website->write) + { + print ''."\n"; + } - /* + /* if ($user->rights->sellyoursaas->create) { if ($object->status == 1) @@ -329,28 +329,28 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } */ - if ($user->rights->website->delete) - { - print ''."\n"; - } - } - print '
    '."\n"; + if ($user->rights->website->delete) + { + print ''."\n"; + } + } + print '
    '."\n"; } // Select mail models is same action as presend if (GETPOST('modelselected')) { - $action = 'presend'; + $action = 'presend'; } if ($action != 'presend') { - print '
    '; - print ''; // ancre + print '
    '; + print ''; // ancre - print '
    '; + print '
    '; - /* + /* $MAXEVENT = 10; // List of actions on element @@ -359,7 +359,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); */ - print '
    '; + print '
    '; } // Presend form diff --git a/htdocs/zapier/hook_card.php b/htdocs/zapier/hook_card.php index 721b40ebfd9..b0441c34f06 100644 --- a/htdocs/zapier/hook_card.php +++ b/htdocs/zapier/hook_card.php @@ -82,31 +82,31 @@ $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { - $error = 0; + $error = 0; - $permissiontoadd = $user->rights->mymodule->write; - $permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0); - $backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1); - if (empty($backtopage)) { - if (empty($id)) $backtopage = $backurlforlist; - else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__'); - } - $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record + $permissiontoadd = $user->rights->mymodule->write; + $permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0); + $backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1); + if (empty($backtopage)) { + if (empty($id)) $backtopage = $backurlforlist; + else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__'); + } + $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record - // Actions cancel, add, update, delete or clone - include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + // Actions cancel, add, update, delete or clone + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; - // Actions when linking object each other - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; + // Actions when linking object each other + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; - // Actions when printing a doc from card - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - // Actions to send emails - $triggersendname = 'MYOBJECT_SENTBYMAIL'; - $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; - $trackid = 'myobject'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to send emails + $triggersendname = 'MYOBJECT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; + $trackid = 'myobject'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -176,7 +176,7 @@ if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("MyObject")); print '
    '; - print ''; + print ''; print ''; print ''; print ''; @@ -204,7 +204,7 @@ if (($id || $ref) && $action == 'edit') { // Part to show record if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { - $res = $object->fetch_optionals(); + $res = $object->fetch_optionals(); $head = myobjectPrepareHead($object); dol_fiche_head($head, 'card', $langs->trans("MyObject"), -1, 'myobject@mymodule'); @@ -213,7 +213,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1); } // Clone confirmation @@ -226,7 +226,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation of action xxxx if ($action == 'xxx') { $formquestion = array(); - /* + /* $forcecombo=0; if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy $formquestion = array( @@ -236,7 +236,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) ); */ - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); } // Call Hook formConfirm @@ -320,25 +320,25 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Buttons for actions if ($action != 'presend' && $action != 'editline') { - print '
    '."\n"; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print '
    '."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) { - // Modify - if ($user->rights->mymodule->write) { - print ''.$langs->trans("Modify").''."\n"; - } else { - print ''.$langs->trans('Modify').''."\n"; - } + if (empty($reshook)) { + // Modify + if ($user->rights->mymodule->write) { + print ''.$langs->trans("Modify").''."\n"; + } else { + print ''.$langs->trans('Modify').''."\n"; + } - // Clone - if ($user->rights->mymodule->write) { - print ''; - } + // Clone + if ($user->rights->mymodule->write) { + print ''; + } - /* + /* if ($user->rights->mymodule->write) { if ($object->status == 1) @@ -352,13 +352,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } */ - if ($user->rights->mymodule->delete) { - print ''.$langs->trans('Delete').''."\n"; - } else { - print ''.$langs->trans('Delete').''."\n"; - } - } - print '
    '."\n"; + if ($user->rights->mymodule->delete) { + print ''.$langs->trans('Delete').''."\n"; + } else { + print ''.$langs->trans('Delete').''."\n"; + } + } + print '
    '."\n"; } @@ -368,28 +368,28 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } if ($action != 'presend') { - print '
    '; - print ''; // ancre + print '
    '; + print ''; // ancre - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; + print '
    '; - $MAXEVENT = 10; + $MAXEVENT = 10; - $morehtmlright = ''; - $morehtmlright .= $langs->trans("SeeAll"); - $morehtmlright .= ''; + $morehtmlright = ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT, '', $morehtmlright); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT, '', $morehtmlright); - print '
    '; + print '
    '; } //Select mail models is same action as presend diff --git a/nightwatch.conf.js b/nightwatch.conf.js new file mode 100644 index 00000000000..e72febea918 --- /dev/null +++ b/nightwatch.conf.js @@ -0,0 +1,27 @@ +const admin_username = process.env.ADMIN_USERNAME || 'admin'; +const admin_password = process.env.ADMIN_PASSWORD || 'password'; +const launch_url = process.env.LAUNCH_URL || 'http://localhost/dolibarr/htdocs/'; +module.exports = { + page_objects_path : './test/acceptance/pageObjects/', // jshint ignore:line + src_folders : ['test'], + + test_settings : { + default : { + selenium_host : '127.0.0.1', + launchUrl : launch_url, + globals : { + backend_url : launch_url, + adminUsername : admin_username, + adminPassword : admin_password + }, + desiredCapabilities : { + browserName : 'chrome', + javascriptEnabled : true, + chromeOptions : { + args : ['disable-gpu', 'window-size=1280,1024'], + w3c : false + } + } + } + } +}; diff --git a/package.json b/package.json new file mode 100644 index 00000000000..01d3a4300ee --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "devDependencies": { + "cucumber": "^6.0.5", + "nightwatch": "^1.4.3", + "nightwatch-api": "^3.0.1" + }, + "scripts": { + "test:e2e": "node_modules/cucumber/bin/cucumber-js --require test/acceptance/index.js --require test/acceptance/setup.js --require test/acceptance/stepDefinitions -f node_modules/cucumber-pretty" + }, + "dependencies": { + "cucumber-pretty": "^6.0.0", + "node-fetch": "^2.6.1" + } +} diff --git a/test/acceptance/README.md b/test/acceptance/README.md new file mode 100644 index 00000000000..ada096c0b69 --- /dev/null +++ b/test/acceptance/README.md @@ -0,0 +1,78 @@ +# Run End-to-End Tests + +### Run Selenium + +Selenium has been used for automating the browser. + +[Download](https://www.selenium.dev/downloads/) the `latest stable version` of the `Selenium standalone server JAR file`. + +Also [download](https://chromedriver.chromium.org/downloads) the `latest stable version` of `Chrome Driver`. + +Once you have downloaded Chrome Driver, you need to unzip it by running the following command: + + `unzip chromedriver_linux64.zip` + +Once you have unzipped it, you need to move the *chromedriver* file (shared library) and place it inside the same folder where you have placed the Selenium standalone server file. + +Now we can run selenium by two ways: + +* Start selenium server with a command which usually looks like: + + `java -jar selenium-server-standalone-.jar -port 4444` + + +* Run selenium in docker with + + `docker run -d -p 4444:4444 -p 5900:5900 -v /dev/shm:/dev/shm selenium/standalone-chrome-debug` + + or `docker run -d --network="host" -v /dev/shm:/dev/shm selenium/standalone-chrome-debug` + + or `docker run -d --network host -v /dev/shm:/dev/shm selenium/standalone-chrome-debug` + +### Run the acceptance tests + +* Install *yarn*. For example on Ubuntu: + + ``` + apt install yarnpkg + ``` + +* Install *nodejs* libraries. For example on Ubuntu: + + ``` + apt install npm + npm install cucumber + npm install nightwatch-api + npm install nightwatch + npm update + ``` + +* In *nightwatch.conf.js* file inside the root directory of the project and inside the configuration file following environment variable has been specified. We can change the default values according to our local configuration. + + ``` + const admin_username = process.env.ADMIN_USERNAME || 'admin'; + + const admin_password = process.env.ADMIN_PASSWORD || 'password'; + + const launch_url = process.env.LAUNCH_URL || 'http://localhost/dolibarr/htdocs/'; + ``` + +* You can run a test using following commands + + `LAUNCH_URL=''; ADMIN_USERNAME=''; ADMIN_PASSWORD='';` + + `yarn run test:e2e test/acceptance/features/` + + For example: `yarn run test:e2e test/acceptance/features/WebUI/addUsers.feature` + + Note: The script to run all the acceptance tests is specified in `scripts` object of `package.json` file inside the project's root directory as : + + `"test:e2e": "node_modules/cucumber/bin/cucumber-js --require test/acceptance/index.js --require test/acceptance/stepDefinitions -f node_modules/cucumber-pretty"` + + After you run the above command you can see the test running. For that : + +* open `Remmina` (Remmina is a Remote Desktop Client and comes installed with Ubuntu) + +* choose `VNC` and enter `localhost` on the address bar + +* enter `secret` as the password diff --git a/test/acceptance/features/Api/apiAddUsers.feature b/test/acceptance/features/Api/apiAddUsers.feature new file mode 100644 index 00000000000..32d94a7b3cf --- /dev/null +++ b/test/acceptance/features/Api/apiAddUsers.feature @@ -0,0 +1,67 @@ +Feature: Add user + As an admin + I want to add users + So that the authorized access is possible + + Scenario: Admin adds user without permission + Given the user with login "harrypotter@gmail.com" does not exist + When the admin creates user with following details using API + | last name | Potter | + | login | harrypotter@gmail.com | + | password | password | + Then the response status code should be "200" + And user with login "harrypotter@gmail.com" should exist + + Scenario: Admin creates already existing user + Given the admin has created the following users + | login | last name | password | + | Harry | Potter | hello123 | + When the admin creates user with following details using API + | last name | Potter | + | login | Harry | + | password | hello123 | + Then the response status code should be "500" + And the response message should be "ErrorLoginAlreadyExists" + + Scenario Outline: Admin adds user with incomplete essential credentials + Given the user with login "Harry" does not exist + When the admin creates user with following details using API + | last name | | + | login | Harry | + | password | | + Then the response status code should be "200" + And user with login "Harry" should exist + Examples: + | last name | password | + | | | + | Manson | | + | | 123 | + + Scenario Outline: Admin adds user without login + Given the user with login "harrypotter@gmail.com" does not exist + When the admin creates user with following details using API + | last name | | + | login | | + | password | | + Then the response status code should be "500" + And the response message should be "Field 'Login' is required" + Examples: + | last name | password | + | Potter | Hello123 | + | Potter | | + | | hello123 | + + Scenario Outline: Admin adds user with last name as special characters + Given the user with login "" does not exist + When the admin creates user with following details using API + | last name | | + | login | | + | password | password | + Then the response status code should be "200" + And user with login "" should exist + Examples: + | last name | login | + | swi@ | s$5^2 | + | g!!@%ui | नेपाली | + | swikriti@h | सिमप्ले $%#?&@name.txt | + | !@#$%^&*()-_+ | España§àôœ€ | \ No newline at end of file diff --git a/test/acceptance/features/WebUI/addUsers.feature b/test/acceptance/features/WebUI/addUsers.feature new file mode 100644 index 00000000000..918bff771c2 --- /dev/null +++ b/test/acceptance/features/WebUI/addUsers.feature @@ -0,0 +1,86 @@ +Feature: Add user + As an admin + I want to add users + So that the authorized access is possible + + Background: + Given the administrator has logged in using the webUI + And the administrator has browsed to the new users page + + Scenario: Admin adds user without permission + When the admin creates user with following details + | last name | Potter | + | login | harrypotter@gmail.com | + | password | password | + Then new user "Potter" should be created + And message "This user has no permissions defined" should be displayed in the webUI + + Scenario Outline: Admin adds user with permission + When the admin creates user with following details + | last name | Potter | + | login | harrypotter@gmail.com | + | password | password | + | administrator | | + | gender | | + Then message "This user has no permissions defined" be displayed in the webUI + And new user "Potter" should be created + Examples: + | administrator | gender | shouldOrShouldNot | + | No | | should | + | No | Man | should | + | No | Woman | should | + | Yes | | should not | + | Yes | Man | should not | + | Yes | Woman | should not | + + Scenario Outline: Admin adds user with last name as special characters + When the admin creates user with following details + | last name | | + | login | harry | + | password | password | + Then message "This user has no permissions defined" should be displayed in the webUI + And new user "" should be created + Examples: + | last name | + | swi@ | + | g!!@%ui | + | swikriti@h | + | !@#$%^&*()-_+=[]{}:;,.<>?~ | + | $w!kr!t! | + | España§àôœ€ | + | नेपाली | + | सिमप्ले $%#?&@name.txt | + + Scenario Outline: Admin adds user with incomplete essential credentials + When the admin creates user with following details + | last name | | + | login | | + | password | | + Then message "" should be displayed in the webUI + And new user "" should not be created + Examples: + | last name | login | password | message | + | | | | Name is not defined.\nLogin is not defined. | + | Joseph | | | Login is not defined. | + | | john@gmail.com | | Name is not defined. | + | Joseph | | hihi | Login is not defined. | + + Scenario: Admin adds user with incomplete essential credentials + When the admin creates user with following details + | last name | Doe | + | login | John | + | password | | + Then message "This user has no permissions defined" should be displayed in the webUI + And new user "Doe" should be created + + Scenario: Admin tries to add user with pre-existing login credential + Given a user has been created with following details + | login | last name | password | + | Tyler | Joseph | pass1234 | + And the administrator has browsed to the new users page + When the admin creates user with following details + | last name | Dun | + | login | Tyler | + | password | pass1234 | + Then message "Login already exists." should be displayed in the webUI + And new user "Dun" should not be created diff --git a/test/acceptance/features/WebUI/listUsers.feature b/test/acceptance/features/WebUI/listUsers.feature new file mode 100644 index 00000000000..e9c0443cdd4 --- /dev/null +++ b/test/acceptance/features/WebUI/listUsers.feature @@ -0,0 +1,29 @@ +Feature: list users + As an admin user + I want to view the list of users + So that I can manage users + + Background: + Given the administrator has logged in using the webUI + + Scenario: Admin user should be able to see list of created users when no new users are created + When the administrator browses to the list of users page using the webUI + Then following users should be displayed in the users list + | login | last name | + | dolibarr | SuperAdmin | + And the number of created users should be 1 + + Scenario: Admin user should be able to see number of created users + Given the admin has created the following users + | login | last name | password | + | Harry | Potter | hello123 | + | Hermoine | Granger | hello123 | + | Ron | Weasley | hello123 | + When the administrator browses to the list of users page using the webUI + Then following users should be displayed in the users list + | login | last name | + | dolibarr | SuperAdmin | + | Harry | Potter | + | Hermoine | Granger | + | Ron | Weasley | + And the number of created users should be 4 diff --git a/test/acceptance/features/WebUI/login.feature b/test/acceptance/features/WebUI/login.feature new file mode 100644 index 00000000000..fd7058812cf --- /dev/null +++ b/test/acceptance/features/WebUI/login.feature @@ -0,0 +1,27 @@ +Feature: user login + As a user/admin + I want to login to my account + So that I can have access to my functionality + + Background: + Given the user has browsed to the login page + + Scenario: Admin user should be able to login successfully + When user logs in with username "dolibarr" and password "password" + Then the user should be directed to the homepage + + Scenario: Admin user with empty credentials should not be able to login + When user logs in with username "" and password "" + Then the user should not be able to login + + Scenario Outline: user logs in with invalid credentials + When user logs in with username "" and password "" + Then the user should not be able to login + And error message "Bad value for login or password" should be displayed in the webUI + Examples: + | username | password | + | dolibar | pass | + | dolibarr | passw | + | dolibar | | + | dolibarr | | + | dolibar | password | diff --git a/test/acceptance/features/WebUI/logout.feature b/test/acceptance/features/WebUI/logout.feature new file mode 100644 index 00000000000..137c5260008 --- /dev/null +++ b/test/acceptance/features/WebUI/logout.feature @@ -0,0 +1,10 @@ +Feature: user logs out + As a user + I want to log out of my account + So that I can protect my work, identity and be assured of my privacy + + Scenario: User can logout + Given the administrator has logged in using the webUI + When the user opens the user profile using the webUI + And the user logs out using the webUI + Then the user should be logged out successfully diff --git a/test/acceptance/index.js b/test/acceptance/index.js new file mode 100644 index 00000000000..a9fcda8105a --- /dev/null +++ b/test/acceptance/index.js @@ -0,0 +1,14 @@ +const { setDefaultTimeout, After, Before } = require('cucumber') +const { createSession, closeSession, startWebDriver, stopWebDriver } = require('nightwatch-api') + +setDefaultTimeout(60000) + +Before(async () => { + await startWebDriver(); + await createSession(); +}) + +After(async () => { + await closeSession(); + await stopWebDriver(); +}) diff --git a/test/acceptance/pageObjects/addUsersPage.js b/test/acceptance/pageObjects/addUsersPage.js new file mode 100644 index 00000000000..7f31523b842 --- /dev/null +++ b/test/acceptance/pageObjects/addUsersPage.js @@ -0,0 +1,128 @@ +const util = require('util'); +module.exports = { + url: function () { + return this.api.launchUrl + 'user/card.php?leftmenu=users&action=create'; + }, + + commands: [ + { + adminCreatesUser: async function (dataTable) { + const userDetails = dataTable.rowsHash(); + let administrator = userDetails['administrator']; + let gender = userDetails['gender']; + await this.waitForElementVisible('@newUserAddOption') + .useXpath() + .waitForElementVisible('@lastnameField') + .clearValue('@lastnameField') + .setValue('@lastnameField', userDetails['last name']) + .waitForElementVisible('@loginField') + .clearValue('@loginField') + .setValue('@loginField', userDetails['login']) + .waitForElementVisible('@newUserPasswordField') + .clearValue('@newUserPasswordField') + .setValue('@newUserPasswordField', userDetails['password']); + + if (userDetails['administrator']) { + const admin = util.format(this.elements.administratorSelectOption.selector, administrator); + await this.waitForElementVisible('@administratorField') + .click('@administratorField') + .waitForElementVisible(admin) + .click(admin); + } + + if (userDetails['gender']) { + const genderValue = util.format(this.elements.genderSelectOption.selector, gender) + await this.waitForElementVisible('@genderField') + .click('@genderField') + .waitForElementVisible(genderValue) + .click(genderValue); + } + return this.waitForElementVisible('@submitButton') + .click('@submitButton') + .useCss(); + }, + + noPermissionMessage: async function (message) { + await this.useXpath() + .waitForElementVisible('@noPermissionDefinedMessage') + .expect.element('@noPermissionDefinedMessage') + .text.to.equal(message); + return this.useCss(); + }, + + newUserShouldBeCreated: async function (lastname) { + await this.useXpath() + .waitForElementVisible('@newUserCreated') + .expect.element('@newUserCreated') + .text.to.equal(lastname); + return this.useCss(); + }, + + noPermissionDefinedMessageNotShown: function (message) { + return this.useXpath() + .waitForElementNotPresent('@noPermissionDefinedMessage') + .useCss(); + }, + + userNotCreated: function (lastname) { + return this.waitForElementVisible('@newUserAddOption'); + } + } + ], + + elements: { + newUserAddOption: { + selector: '.fiche' + }, + + lastnameField: { + selector: '//table[@class="border centpercent"]/tbody/tr/td//input[@id="lastname"]', + locateStrategy: 'xpath' + }, + + loginField: { + selector: '//table[@class="border centpercent"]/tbody/tr/td//input[@name="login"]', + locateStrategy: 'xpath' + }, + + newUserPasswordField: { + selector: '//table[@class="border centpercent"]/tbody/tr/td//input[@name="password"]', + locateStrategy: 'xpath' + }, + + submitButton: { + selector: '//div[@class="center"]/input[@class="button"]', + locateStrategy: 'xpath' + }, + + administratorField: { + selector: '//table[@class="border centpercent"]/tbody/tr/td//select[@id="admin"]', + locateStrategy: 'xpath' + }, + + administratorSelectOption: { + selector: '//select[@id="admin"]/option[.="%s"]', + locateStrategy: 'xpath' + + }, + + genderField: { + selector: '//table[@class="border centpercent"]/tbody/tr/td//select[@id="gender"]', + locateStrategy: 'xpath' + }, + genderSelectOption: { + selector: '//select[@id="gender"]/option[.="%s"]', + locateStrategy: 'xpath' + }, + + noPermissionDefinedMessage: { + selector: '//div[@class="jnotify-message"]', + locateStrategy: 'xpath' + }, + + newUserCreated: { + selector: '//div[contains(@class,"valignmiddle")]//div[contains(@class,"inline-block floatleft valignmiddle")]', + locateStrategy: 'xpath' + } + } +}; diff --git a/test/acceptance/pageObjects/homePage.js b/test/acceptance/pageObjects/homePage.js new file mode 100644 index 00000000000..7c225e90f5a --- /dev/null +++ b/test/acceptance/pageObjects/homePage.js @@ -0,0 +1,44 @@ +module.exports = { + url: function () { + return this.api.launchUrl + 'admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete'; + }, + + commands: [ + { + browsedToNewUserPage: function () { + return this.useXpath() + .waitForElementVisible('@usersAndGroups') + .click('@usersAndGroups') + .waitForElementVisible('@newUser') + .click('@newUser') + .useCss(); + }, + + browsedToListOfUsers: function () { + return this.useXpath() + .waitForElementVisible('@usersAndGroups') + .click('@usersAndGroups') + .waitForElementVisible('@listOfUsers') + .click('@listOfUsers') + .useCss(); + } + } + ], + + elements: { + usersAndGroups: { + selector: '//div[@class="menu_titre"]/a[@title="Users & Groups"]', + locateStrategy: 'xpath' + }, + + newUser: { + selector: '//div[@class="menu_contenu menu_contenu_user_card"]/a[@title="New user"]', + locateStrategy: 'xpath' + }, + + listOfUsers: { + selector: '//a[@class="vsmenu"][@title="List of users"]', + locateStrategy: 'xpath' + } + } +}; diff --git a/test/acceptance/pageObjects/listUsersPage.js b/test/acceptance/pageObjects/listUsersPage.js new file mode 100644 index 00000000000..3567bb576ab --- /dev/null +++ b/test/acceptance/pageObjects/listUsersPage.js @@ -0,0 +1,47 @@ +const util = require('util'); +module.exports = { + url: function () { + return this.api.launchUrl + 'user/list.php?leftmenu=users'; + }, + + commands: [ + { + listOfUsersDisplayed: async function (dataTable) { + const usersList = dataTable.hashes(); + this.useXpath(); + for (const row of usersList) { + let login = row['login']; + let lastName = row['last name']; + const userDetail = util.format(this.elements.userList.selector, login, lastName); + await this.waitForElementVisible('@userRow') + .waitForElementVisible(userDetail); + } + return this.useCss(); + }, + + numberOfUsersDisplayed: async function (number) { + const userCount = util.format(this.elements.numberOfUsers.selector, number); + await this.useXpath() + .waitForElementVisible(userCount); + return this.useCss(); + } + } + ], + + elements: { + userRow: { + selector: '//table[contains(@class,"tagtable")]/tbody/tr[position()>2]', + locateStrategy: 'xpath' + }, + + numberOfUsers: { + selector: '//div[contains(@class, "titre inline-block") and contains(., "List of users")]/span[.="(%d)"]', + locateStrategy: 'xpath' + }, + + userList: { + selector: '//table[contains(@class,"tagtable")]/tbody/tr[position()>2]/td/a//span[normalize-space(@class="nopadding usertext")][.="%s"]/../../following-sibling::td[.="%s"]', + locateStrategy: 'xpath' + } + } +}; diff --git a/test/acceptance/pageObjects/loginPage.js b/test/acceptance/pageObjects/loginPage.js new file mode 100644 index 00000000000..b95fd1645ab --- /dev/null +++ b/test/acceptance/pageObjects/loginPage.js @@ -0,0 +1,84 @@ +module.exports = { + url: function () { + return this.api.launchUrl; + }, + + commands: [ + { + waitForLoginPage: function () { + return this.waitForElementVisible('@loginTable'); + }, + + userLogsInWithUsernameAndPassword: function (username, password) { + return this.waitForElementVisible('@userNameField') + .setValue('@userNameField', username) + .waitForElementVisible('@passwordField') + .setValue('@passwordField', password) + .useXpath() + .waitForElementVisible('@loginButton') + .click('@loginButton') + .useCss(); + }, + + successfulLogin: function () { + return this.waitForElementNotPresent('@loginTable') + .waitForElementVisible('@userProfileDropdown'); + }, + + userIsLoggedIn: async function (login) { + await this.waitForElementNotPresent('@loginTable') + .useXpath() + .waitForElementVisible('@userLogin') + .expect.element('@userLogin') + .text.to.equal(login); + return this.useCss(); + }, + + unsuccessfulLogin: function () { + return this.waitForElementVisible('@loginTable') + .waitForElementNotPresent('@userProfileDropdown'); + }, + + loginErrorDisplayed: async function (errorMessage) { + await this.useXpath() + .waitForElementVisible('@loginError') + .expect.element('@loginError') + .text.to.equal(errorMessage); + return this.useCss(); + } + } + ], + + elements: { + loginButton: { + selector: '//div[@id="login-submit-wrapper"]/input[@type="submit"]', + locateStrategy: 'xpath' + }, + + userNameField: { + selector: '#username' + }, + + passwordField: { + selector: '#password' + }, + + loginTable: { + selector: '.login_table' + }, + + userProfileDropdown: { + selector: '#topmenu-login-dropdown' + }, + + userLogin: { + selector: '//div[@id="topmenu-login-dropdown"]/a//span[contains(@class,"atoploginusername")]', + locateStrategy: 'xpath' + }, + + loginError: { + selector: '//div[@class="center login_main_message"]/div[@class="error"]', + locateStrategy: 'xpath' + } + } +}; diff --git a/test/acceptance/pageObjects/logoutPage.js b/test/acceptance/pageObjects/logoutPage.js new file mode 100644 index 00000000000..a63b8415238 --- /dev/null +++ b/test/acceptance/pageObjects/logoutPage.js @@ -0,0 +1,34 @@ +module.exports = { + url: function () { + return this.api.launchUrl + 'admin/index.php?mainmenu=home&leftmenu=setup&mesg=setupnotcomplete'; + }, + + commands: + [ + { + userOpensProfile: async function () { + await this.useXpath() + .waitForElementVisible('@userProfileDropdown') + .click('@userProfileDropdown') + return this.useCss(); + }, + + userLogsOut: function () { + return this.waitForElementVisible('@logoutButton') + .click('@logoutButton'); + } + } + ], + + elements: { + + logoutButton: { + selector: '.pull-right' + }, + + userProfileDropdown: { + selector: '//div[@id="topmenu-login-dropdown"]', + locateStrategy: 'xpath' + } + } +}; diff --git a/test/acceptance/setup.js b/test/acceptance/setup.js new file mode 100644 index 00000000000..123d6b3c5ec --- /dev/null +++ b/test/acceptance/setup.js @@ -0,0 +1,77 @@ +const { Before, After } = require('cucumber'); +const { client } = require('nightwatch-api'); +const fetch = require('node-fetch'); +let initialUsers = {}; +let dolApiKey = ''; + +const getUsers = async function () { + const header = {}; + const url = client.globals.backend_url + 'api/index.php/users'; + const users = {}; + header['Accept'] = 'application/json'; + header['DOLAPIKEY'] = dolApiKey; + await fetch(url, { + method: 'GET', + headers: header + }) + .then(async (response) => { + const json_response = await response.json(); + for (const user of json_response) { + users[user.id] = user.id; + } + }); + return users; +}; + +Before(async function getDolApiKey() { + const header = {} + const adminUsername = client.globals.adminUsername; + const adminPassword = client.globals.adminPassword; + const params = new URLSearchParams() + params.set('login', adminUsername) + params.set('password', adminPassword) + const apiKey = client.globals.backend_url + `api/index.php/login?${params.toString()}`; + header['Accept'] = 'application/json' + await fetch(apiKey, { + method: 'GET', + headers: header + }) + .then(async (response) => { + const jsonResponse = await response.json() + dolApiKey = jsonResponse['success']['token'] + client.globals.dolApiKey = dolApiKey + }) +}) + +Before(async () => { + initialUsers = await getUsers(); +}); + +After(async () => { + const finalUsers = await getUsers(); + const header = {}; + const url = client.globals.backend_url + 'api/index.php/users/'; + header['Accept'] = 'application/json'; + header['DOLAPIKEY'] = dolApiKey; + let found; + for (const finaluser in finalUsers) { + for (const initialuser in initialUsers) { + found = false; + if (initialuser === finaluser) { + found = true; + break; + } + } + if (!found) { + await fetch(url + finaluser, { + method: 'DELETE', + headers: header + }) + .then(res => { + if (res.status < 200 || res.status >= 400) { + throw new Error("Failed to delete user: " + res.statusText); + } + }); + } + } +}); diff --git a/test/acceptance/stepDefinitions/addUsersContext.js b/test/acceptance/stepDefinitions/addUsersContext.js new file mode 100644 index 00000000000..076c5d24226 --- /dev/null +++ b/test/acceptance/stepDefinitions/addUsersContext.js @@ -0,0 +1,150 @@ +const {Given, When, Then} = require('cucumber'); +const {client} = require('nightwatch-api'); +const fetch = require('node-fetch'); +const assert = require('assert'); +let response; +let Login = {}; + +Given('the administrator has browsed to the new users page', function () { + return client.page.homePage().browsedToNewUserPage(); +}); + +When('the admin creates user with following details', function (datatable) { + return client.page.addUsersPage().adminCreatesUser(datatable); +}); + +Then('new user {string} should be created', function (lastname) { + return client.page.addUsersPage().newUserShouldBeCreated(lastname); +}); + +Then('message {string} should be displayed in the webUI', function (message) { + return client.page.addUsersPage().noPermissionMessage(message); +}); + +Then('message {string} should not be displayed in the webUI', function (message) { + return client.page.addUsersPage().noPermissionDefinedMessageNotShown(message); +}); + +Then('new user {string} should not be created', function (lastname) { + return client.page.addUsersPage().userNotCreated(lastname); +}); + +Given('a user has been created with following details', function (dataTable) { + return adminHasCreatedUser(dataTable); +}); + +Given('the admin has created the following users', function (dataTable) { + return adminHasCreatedUser(dataTable); +}); + +When('the admin creates user with following details using API', function (dataTable) { + return adminCreatesUserWithAPI(dataTable); +}); + +Given('the user with login {string} does not exist', async function (login) { + await userDoesNotExist(login); +}); + +Then('the response status code should be {string}', function (expectedStatusCode) { + return getStatusCode(expectedStatusCode); +}); + +Then('user with login {string} should exist', function (login) { + return userShouldExist(login); +}); + +Then('the response message should be {string}', function (expectedResponseMessage) { + return getResponseMessage(expectedResponseMessage); +}); + +const createUserRequest = function (login, lastname, password) { + const header = {}; + const url = client.globals.backend_url + 'api/index.php/users'; + header['Accept'] = 'application/json'; + header['DOLAPIKEY'] = client.globals.dolApiKey; + header['Content-Type'] = 'application/json'; + return fetch(url, { + method: 'POST', + headers: header, + body: JSON.stringify( + { + login: login, + lastname: lastname, + pass: password + } + ) + }); +}; + +const adminCreatesUserWithAPI = function (dataTable) { + const userDetails = dataTable.rowsHash(); + return createUserRequest(userDetails['login'], userDetails['last name'], userDetails['password']) + .then((res) => { + response = res; + }); +}; + +const adminHasCreatedUser = async function (dataTable) { + const userDetails = dataTable.hashes(); + for (const user of userDetails) { + await createUserRequest(user['login'], user['last name'], user['password']) + .then((response) => { + if (response.status < 200 || response.status >= 400) { + throw new Error('Failed to create user: ' + user['login'] + + ' ' + response.statusText); + } + }); + } +}; + +const getUsersLogin = async function () { + const header = {}; + const url = client.globals.backend_url + 'api/index.php/users/'; + header['Accept'] = 'application/json'; + header['DOLAPIKEY'] = client.globals.dolApiKey; + header['Content-Type'] = 'application/json'; + await fetch(url, { + method: 'GET', + headers: header + }) + .then(async (response) => { + const json_response = await response.json(); + for (const user of json_response) { + Login[user.login] = user.login; + } + }); +}; + +const userDoesNotExist = async function (login) { + await getUsersLogin(); + if (login in Login) { + Login = {}; + throw new Error(`user ${login} exists`); + } + Login = {}; + return; +}; + +const userShouldExist = async function (login) { + await getUsersLogin(); + if (login in Login) { + Login = {}; + return; + } else { + Login = {}; + throw new Error(`User ${login} does not Exist`); + } +}; + +const getStatusCode = async function (expectedStatusCode) { + const actualStatusCode = response.status.toString(); + return assert.strictEqual(actualStatusCode, expectedStatusCode, + `The expected status code was ${expectedStatusCode} but got ${actualStatusCode}`); +}; + +const getResponseMessage = async function (expectedResponseMessage) { + const json_response = await response.json(); + const actualResponseMessage = json_response['error']['0']; + return assert.strictEqual(actualResponseMessage, expectedResponseMessage, + `the expected response message was ${expectedResponseMessage} but got ${actualResponseMessage}`); +}; diff --git a/test/acceptance/stepDefinitions/listUsersContext.js b/test/acceptance/stepDefinitions/listUsersContext.js new file mode 100644 index 00000000000..78912abd3a0 --- /dev/null +++ b/test/acceptance/stepDefinitions/listUsersContext.js @@ -0,0 +1,14 @@ +const { When, Then } = require('cucumber'); +const { client } = require('nightwatch-api'); + +When('the administrator browses to the list of users page using the webUI', function () { + return client.page.homePage().browsedToListOfUsers(); +}); + +Then('following users should be displayed in the users list', function (dataTable) { + return client.page.listUsersPage().listOfUsersDisplayed(dataTable); +}); + +Then('the number of created users should be {int}', function (number) { + return client.page.listUsersPage().numberOfUsersDisplayed(number); +}); diff --git a/test/acceptance/stepDefinitions/loginContext.js b/test/acceptance/stepDefinitions/loginContext.js new file mode 100644 index 00000000000..ea9aa07949b --- /dev/null +++ b/test/acceptance/stepDefinitions/loginContext.js @@ -0,0 +1,28 @@ +const { Given, When, Then } = require('cucumber') +const { client } = require('nightwatch-api') + +Given('the administrator has logged in using the webUI', async function () { + await client.page.loginPage().navigate().waitForLoginPage(); + await client.page.loginPage().userLogsInWithUsernameAndPassword(client.globals.adminUsername, client.globals.adminPassword); + return client.page.loginPage().userIsLoggedIn(client.globals.adminUsername); +}); + +Given('the user has browsed to the login page', function () { + return client.page.loginPage().navigate(); +}); + +When('user logs in with username {string} and password {string}', function (username, password) { + return client.page.loginPage().userLogsInWithUsernameAndPassword(username, password); +}); + +Then('the user should be directed to the homepage', function () { + return client.page.loginPage().successfulLogin(); +}); + +Then('the user should not be able to login', function () { + return client.page.loginPage().unsuccessfulLogin(); +}); + +Then('error message {string} should be displayed in the webUI', function (errormessage) { + return client.page.loginPage().loginErrorDisplayed(errormessage); +}); diff --git a/test/acceptance/stepDefinitions/logoutContext.js b/test/acceptance/stepDefinitions/logoutContext.js new file mode 100644 index 00000000000..018bf566cfb --- /dev/null +++ b/test/acceptance/stepDefinitions/logoutContext.js @@ -0,0 +1,14 @@ +const { When, Then } = require('cucumber'); +const { client } = require('nightwatch-api'); + +When('the user opens the user profile using the webUI', function () { + return client.page.logoutPage().userOpensProfile(); +}); + +When('the user logs out using the webUI', function () { + return client.page.logoutPage().userLogsOut(); +}); + +Then('the user should be logged out successfully', function () { + return client.page.loginPage().waitForLoginPage(); +}); diff --git a/test/phpunit/CodingPhpTest.php b/test/phpunit/CodingPhpTest.php index b819671578c..4326f536f92 100644 --- a/test/phpunit/CodingPhpTest.php +++ b/test/phpunit/CodingPhpTest.php @@ -341,7 +341,7 @@ class CodingPhpTest extends PHPUnit\Framework\TestCase $ok=true; $matches=array(); // Check string name="token" value="'.$_SESSINON - preg_match_all('/name="token" value="\'\.\$_SESSION/', $filecontent, $matches, PREG_SET_ORDER); + preg_match_all('/name="token" value="\'\s*\.\s*\$_SESSION/', $filecontent, $matches, PREG_SET_ORDER); foreach ($matches as $key => $val) { if ($file['name'] != 'excludefile.php') diff --git a/test/phpunit/FunctionsLibTest.php b/test/phpunit/FunctionsLibTest.php index d113cde8035..2cb4d98610c 100644 --- a/test/phpunit/FunctionsLibTest.php +++ b/test/phpunit/FunctionsLibTest.php @@ -1257,9 +1257,6 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase $conf->global->MAIN_START_WEEK = 0; - $tmp=dol_getdate(1); // 1/1/1970 and 1 second = thirday - $this->assertEquals(4, $tmp['wday']); - $tmp=dol_getdate(24*60*60+1); // 2/1/1970 and 1 second = friday $this->assertEquals(5, $tmp['wday']); @@ -1271,12 +1268,77 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase $tmp=dol_getdate(24*60*60+1); // 2/1/1970 and 1 second = friday $this->assertEquals(5, $tmp['wday']); + $tmp=dol_getdate(1, false, "Europe/Paris"); // 1/1/1970 and 1 second = thirday + $this->assertEquals(1970, $tmp['year']); + $this->assertEquals(1, $tmp['mon']); + $this->assertEquals(1, $tmp['mday']); + $this->assertEquals(4, $tmp['wday']); + $this->assertEquals(0, $tmp['yday']); + $this->assertEquals(1, $tmp['hours']); // We are winter, so we are GMT+1 even during summer + $this->assertEquals(0, $tmp['minutes']); + $this->assertEquals(1, $tmp['seconds']); + + $tmp=dol_getdate(15638401, false, "Europe/Paris"); // 1/7/1970 and 1 second = wednesday + $this->assertEquals(1970, $tmp['year']); + $this->assertEquals(7, $tmp['mon']); + $this->assertEquals(1, $tmp['mday']); + $this->assertEquals(3, $tmp['wday']); + $this->assertEquals(181, $tmp['yday']); + $this->assertEquals(1, $tmp['hours']); // There is no daylight in 1970, so we are GMT+1 even during summer + $this->assertEquals(0, $tmp['minutes']); + $this->assertEquals(1, $tmp['seconds']); + + $tmp=dol_getdate(1593561601, false, "Europe/Paris"); // 1/7/2020 and 1 second = wednesday + $this->assertEquals(2020, $tmp['year']); + $this->assertEquals(7, $tmp['mon']); + $this->assertEquals(1, $tmp['mday']); + $this->assertEquals(3, $tmp['wday']); + $this->assertEquals(182, $tmp['yday']); // 182 and not 181, due to the 29th february + $this->assertEquals(2, $tmp['hours']); // There is a daylight, so we are GMT+2 + $this->assertEquals(0, $tmp['minutes']); + $this->assertEquals(1, $tmp['seconds']); + + $conf->global->MAIN_USE_OLD_FUNCTIONS_FOR_GETDATE = 1; + + $tmp=dol_getdate(1); // 1/1/1970 and 1 second = thirday + $this->assertEquals(1970, $tmp['year']); + $this->assertEquals(1, $tmp['mon']); + $this->assertEquals(1, $tmp['mday']); + $this->assertEquals(4, $tmp['wday']); + $this->assertEquals(0, $tmp['yday']); + // We must disable this because on CI, timezone is may be UTC or something else + //$this->assertEquals(1, $tmp['hours']); // We are winter, so we are GMT+1 even during summer + $this->assertEquals(0, $tmp['minutes']); + $this->assertEquals(1, $tmp['seconds']); + + $tmp=dol_getdate(15638401); // 1/7/1970 and 1 second = wednesday + $this->assertEquals(1970, $tmp['year']); + $this->assertEquals(7, $tmp['mon']); + $this->assertEquals(1, $tmp['mday']); + $this->assertEquals(3, $tmp['wday']); + $this->assertEquals(181, $tmp['yday']); + // We must disable this because on CI, timezone is may be UTC or something else + //$this->assertEquals(1, $tmp['hours']); // There is no daylight in 1970, so we are GMT+1 even during summer + $this->assertEquals(0, $tmp['minutes']); + $this->assertEquals(1, $tmp['seconds']); + + $tmp=dol_getdate(1593561601); // 1/7/2020 and 1 second = wednesday + $this->assertEquals(2020, $tmp['year']); + $this->assertEquals(7, $tmp['mon']); + $this->assertEquals(1, $tmp['mday']); + $this->assertEquals(3, $tmp['wday']); + $this->assertEquals(182, $tmp['yday']); // 182 and not 181, due to the 29th february + // We must disable this because on CI, timezone is may be UTC or something else + //$this->assertEquals(2, $tmp['hours']); // There is a daylight, so we are GMT+2 + $this->assertEquals(0, $tmp['minutes']); + $this->assertEquals(1, $tmp['seconds']); + return true; } /** - * testDolGetDate + * testMakeSubstitutions * * @return boolean */ diff --git a/test/phpunit/SecurityTest.php b/test/phpunit/SecurityTest.php index 6c4d2270d1a..4430b377b26 100644 --- a/test/phpunit/SecurityTest.php +++ b/test/phpunit/SecurityTest.php @@ -294,6 +294,46 @@ class SecurityTest extends PHPUnit\Framework\TestCase return 0; } + /** + * testDolStringOnlyTheseHtmlTags + * + * @return number + */ + public function testDolHTMLEntityDecode() + { + $stringtotest = 'a : b " c ' d ' e é'; + $decodedstring = dol_html_entity_decode($stringtotest, ENT_QUOTES); + $this->assertEquals('a : b " c \' d ' e é', $decodedstring, 'Function did not sanitize correclty'); + + $stringtotest = 'a : b " c ' d ' e é'; + $decodedstring = dol_html_entity_decode($stringtotest, ENT_QUOTES|ENT_HTML5); + $this->assertEquals('a : b " c \' d \' e é', $decodedstring, 'Function did not sanitize correclty'); + + return 0; + } + + /** + * testDolStringOnlyTheseHtmlTags + * + * @return number + */ + public function testDolStringOnlyTheseHtmlTags() + { + $stringtotest = 'bbbڴ'; + $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1); + $this->assertEquals('bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 1'); + + $stringtotest = 'bbbڴ'; + $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1); + $this->assertEquals('bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 2'); + + $stringtotest = 'bbbڴ'; + $decodedstring = dol_string_onlythesehtmltags($stringtotest, 1, 1, 1); + $this->assertEquals('bbbڴ', $decodedstring, 'Function did not sanitize correclty with test 3'); + + return 0; + } + /** * testGetRandomPassword *