diff --git a/.github/workflows/exakat.yml b/.github/workflows/exakat.yml index c2f8cc12765..1d134ff2455 100644 --- a/.github/workflows/exakat.yml +++ b/.github/workflows/exakat.yml @@ -5,6 +5,9 @@ on: schedule: - cron: "0 20 * * *" +permissions: + contents: read + jobs: exakat: runs-on: ubuntu-latest diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index b648bd7aff7..556ce9d0a7e 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -499,8 +499,9 @@ if ($nboftargetok) { $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/cache.manifest`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.mysql`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.nova*`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.old`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.postgres`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.pgsql`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf*sav*`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/mssql/README`; diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php index acc4bcc23db..d0a0ab671d4 100644 --- a/htdocs/accountancy/admin/export.php +++ b/htdocs/accountancy/admin/export.php @@ -211,8 +211,7 @@ if ($num) { // Value print ''; - $key_value = getDolGlobalString($conf->global->$key, $conf->global->$key); - print ''; + print ''; print ''; } } @@ -240,7 +239,7 @@ if (!$conf->use_javascript_ajax) { } else { print ''; $listmodelcsv = $accountancyexport->getType(); - print $form->selectarray("ACCOUNTING_EXPORT_MODELCSV", $listmodelcsv, $conf->global->ACCOUNTING_EXPORT_MODELCSV, 0, 0, 0, '', 0, 0, 0, '', '', 1); + print $form->selectarray("ACCOUNTING_EXPORT_MODELCSV", $listmodelcsv, getDolGlobalString('ACCOUNTING_EXPORT_MODELCSV'), 0, 0, 0, '', 0, 0, 0, '', '', 1); print ''; } diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 543d32dedcc..0210fa10e75 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -358,7 +358,7 @@ foreach ($list as $key) { print ''.$label.''; // Value print ''; - print ''; + print ''; print ''; print ''; @@ -414,7 +414,7 @@ foreach ($list_binding as $key) { $array = array(0=>$langs->trans("PreviousMonth"), 1=>$langs->trans("CurrentMonth"), 2=>$langs->trans("Fiscalyear")); print $form->selectarray($key, $array, (isset($conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER) ? $conf->global->ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER : 0)); } else { - print ''; + print ''; } print ''; diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 8dd004fcc35..4bc6d50de89 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -207,7 +207,7 @@ if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) { $accountancyexport = new AccountancyExport($db); $listofformat = $accountancyexport->getType(); -$formatexportset = $conf->global->ACCOUNTING_EXPORT_MODELCSV; +$formatexportset = getDolGlobalString('ACCOUNTING_EXPORT_MODELCSV'); if (empty($listofformat[$formatexportset])) { $formatexportset = 1; } diff --git a/htdocs/adherents/type_translation.php b/htdocs/adherents/type_translation.php index 256f29b6b81..72976d4e65f 100644 --- a/htdocs/adherents/type_translation.php +++ b/htdocs/adherents/type_translation.php @@ -220,7 +220,7 @@ if ($action == 'edit') { print ''; print ''; print ''; print ''; @@ -283,7 +283,7 @@ if ($action == 'create' && $user->rights->adherent->configurer) { print ''; print ''; print ''; diff --git a/htdocs/admin/bom.php b/htdocs/admin/bom.php index dc56d3ae79f..459d9c47227 100644 --- a/htdocs/admin/bom.php +++ b/htdocs/admin/bom.php @@ -453,10 +453,10 @@ print ''; } diff --git a/htdocs/admin/contract.php b/htdocs/admin/contract.php index 0c8aba5ae2d..e8a1fc85790 100644 --- a/htdocs/admin/contract.php +++ b/htdocs/admin/contract.php @@ -445,10 +445,10 @@ print $form->textwithpicto($langs->trans("FreeLegalTextOnContracts"), $langs->tr print '
'; $variablename = 'CONTRACT_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''."\n"; diff --git a/htdocs/admin/dav.php b/htdocs/admin/dav.php index e12848e3de1..698bb187d67 100644 --- a/htdocs/admin/dav.php +++ b/htdocs/admin/dav.php @@ -105,7 +105,7 @@ if ($action == 'edit') { } elseif ($key == 'DAV_ALLOW_PUBLIC_DIR' || $key == 'DAV_ALLOW_ECM_DIR') { print $form->selectyesno($key, $conf->global->$key, 1); } else { - print ''; + print ''; } print ''; } diff --git a/htdocs/admin/delivery.php b/htdocs/admin/delivery.php index 6f0f4c1b415..de26d237d01 100644 --- a/htdocs/admin/delivery.php +++ b/htdocs/admin/delivery.php @@ -434,10 +434,10 @@ print '\n"; print '\n"; print '
'.$langs->trans('Label').'
'.$langs->trans('Description').''; - $doleditor = new DolEditor("desc-$key", $object->multilangs[$key]["description"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor("desc-$key", $object->multilangs[$key]["description"], '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print '
'.$langs->trans('Label').'
'.$langs->trans('Description').''; - $doleditor = new DolEditor('desc', '', '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor('desc', '', '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print '
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnBOMs"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'BOM_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; diff --git a/htdocs/admin/chequereceipts.php b/htdocs/admin/chequereceipts.php index 3ba8c3b854a..396d44625a7 100644 --- a/htdocs/admin/chequereceipts.php +++ b/htdocs/admin/chequereceipts.php @@ -261,10 +261,10 @@ print '
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnChequeReceipts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'BANK_CHEQUERECEIPT_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; diff --git a/htdocs/admin/commande.php b/htdocs/admin/commande.php index f4afd27d46b..1369c5667a8 100644 --- a/htdocs/admin/commande.php +++ b/htdocs/admin/commande.php @@ -612,7 +612,7 @@ print '
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnOrders"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'ORDER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); @@ -661,7 +661,7 @@ if ($conf->banque->enabled) { } // Ask for warehouse during order -if ($conf->stock->enabled) { +if (isModEnabled('stock')) { print '
'; print $langs->trans("WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER").' '; if (! empty($conf->use_javascript_ajax)) { diff --git a/htdocs/admin/compta.php b/htdocs/admin/compta.php index 047b87ff014..d215125d51e 100644 --- a/htdocs/admin/compta.php +++ b/htdocs/admin/compta.php @@ -179,7 +179,7 @@ foreach ($list as $key) { // Value print ''; - print ''; + print ''; print '
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnDeliveryReceipts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'DELIVERY_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print '
'; diff --git a/htdocs/admin/expedition.php b/htdocs/admin/expedition.php index 12e0d0a6d01..cb49404a8b9 100644 --- a/htdocs/admin/expedition.php +++ b/htdocs/admin/expedition.php @@ -132,7 +132,7 @@ if ($action == 'updateMask') { } elseif ($action == 'del') { $ret = delDocumentModel($value, $type); if ($ret > 0) { - if ($conf->global->EXPEDITION_ADDON_PDF == "$value") { + if (getDolGlobalString('EXPEDITION_ADDON_PDF') == "$value") { dolibarr_del_const($db, 'EXPEDITION_ADDON_PDF', $conf->entity); } } @@ -231,7 +231,7 @@ foreach ($dirmodels as $reldir) { if ($conf->global->EXPEDITION_ADDON_NUMBER == "$file") { print img_picto($langs->trans("Activated"), 'switch_on'); } else { - print 'scandir).'&label='.urlencode($module->name).'">'; + print 'name).'">'; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } @@ -367,7 +367,7 @@ foreach ($dirmodels as $reldir) { // Defaut print ''; - if ($conf->global->EXPEDITION_ADDON_PDF == $name) { + if (getDolGlobalString('EXPEDITION_ADDON_PDF') == $name) { print img_picto($langs->trans("Default"), 'on'); } else { print 'scandir).'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; @@ -441,17 +441,17 @@ print '
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnShippings"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'SHIPPING_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print "
'; print $form->textwithpicto($langs->trans("WatermarkOnDraftContractCards"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
'; -print ''; +print ''; print "
'; diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php index e5169ce55cc..0c54eade6da 100644 --- a/htdocs/admin/expensereport.php +++ b/htdocs/admin/expensereport.php @@ -456,10 +456,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnExpenseReports"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'EXPENSEREPORT_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''."\n"; diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index 599aac27c3f..accb3d850a0 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -743,10 +743,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'INVOICE_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php index c95f354a189..36a55be9a95 100644 --- a/htdocs/admin/fichinter.php +++ b/htdocs/admin/fichinter.php @@ -507,10 +507,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnInterventions"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'FICHINTER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/holiday.php b/htdocs/admin/holiday.php index 7b0aa577a87..f208e2a658a 100644 --- a/htdocs/admin/holiday.php +++ b/htdocs/admin/holiday.php @@ -538,10 +538,10 @@ if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { print '
'; $variablename = 'HOLIDAY_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''."\n"; diff --git a/htdocs/admin/loan.php b/htdocs/admin/loan.php index 59b7eb8b463..72b2a15d678 100644 --- a/htdocs/admin/loan.php +++ b/htdocs/admin/loan.php @@ -107,7 +107,7 @@ foreach ($list as $key) { if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account(getDolGlobalString($key), $key, 1, '', 1, 1); } else { - print ''; + print ''; } print ''; } diff --git a/htdocs/admin/mrp.php b/htdocs/admin/mrp.php index fac6a3f3d41..f4283373b95 100644 --- a/htdocs/admin/mrp.php +++ b/htdocs/admin/mrp.php @@ -446,10 +446,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnMOs"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'MRP_MO_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index 3bc745a1101..fe8db9818f7 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -675,10 +675,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'PROPOSAL_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/reception_setup.php b/htdocs/admin/reception_setup.php index 26300ece329..1ca874c69b5 100644 --- a/htdocs/admin/reception_setup.php +++ b/htdocs/admin/reception_setup.php @@ -455,12 +455,12 @@ print $form->textwithpicto($langs->trans("FreeLegalTextOnReceptions"), $langs->t $variablename='RECEPTION_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($variablename, $conf->global->$variablename,'',80,'dolibarr_notes'); + $doleditor=new DolEditor($variablename, getDolGlobalString($variablename),'',80,'dolibarr_notes'); print $doleditor->Create(); } print "\n"; diff --git a/htdocs/admin/stocktransfer.php b/htdocs/admin/stocktransfer.php index 541947bf442..0e504ec26f1 100644 --- a/htdocs/admin/stocktransfer.php +++ b/htdocs/admin/stocktransfer.php @@ -194,7 +194,7 @@ print ''.$langs->trans("StockTransferSetupPage").''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''; + print ''; } print ''; @@ -217,7 +217,7 @@ print ''.$langs->trans("StockTransferSetupPage").''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''.$conf->global->$key.''; + print ''.getDolGlobalString($key).''; } print ''; diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index 40fe58f68d6..aa337ff1f29 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -457,10 +457,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'SUPPLIER_INVOICE_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index 75f2badfda5..9482a06be41 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -505,10 +505,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnOrders"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'SUPPLIER_ORDER_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/supplier_proposal.php b/htdocs/admin/supplier_proposal.php index 80f2c6a62f4..bb0617c6700 100644 --- a/htdocs/admin/supplier_proposal.php +++ b/htdocs/admin/supplier_proposal.php @@ -474,10 +474,10 @@ print ''; print $form->textwithpicto($langs->trans("FreeLegalTextOnSupplierProposal"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename = 'SUPPLIER_PROPOSAL_FREE_TEXT'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print ''; diff --git a/htdocs/admin/ticket.php b/htdocs/admin/ticket.php index f902c3fb39b..99d1b34749f 100644 --- a/htdocs/admin/ticket.php +++ b/htdocs/admin/ticket.php @@ -642,7 +642,7 @@ $mail_intro = $conf->global->TICKET_MESSAGE_MAIL_INTRO ? $conf->global->TICKET_M print ''.$langs->trans("TicketMessageMailIntroLabelAdmin"); print ''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -$doleditor = new DolEditor('TICKET_MESSAGE_MAIL_INTRO', $mail_intro, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70); +$doleditor = new DolEditor('TICKET_MESSAGE_MAIL_INTRO', $mail_intro, '100%', 120, 'dolibarr_mailings', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_MAIL'), ROWS_2, 70); $doleditor->Create(); print ''; print ''; @@ -654,7 +654,7 @@ $mail_signature = $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE ? $conf->global-> print ''.$langs->trans("TicketMessageMailSignatureLabelAdmin").''; print ''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -$doleditor = new DolEditor('TICKET_MESSAGE_MAIL_SIGNATURE', $mail_signature, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70); +$doleditor = new DolEditor('TICKET_MESSAGE_MAIL_SIGNATURE', $mail_signature, '100%', 120, 'dolibarr_mailings', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_MAIL'), ROWS_2, 70); $doleditor->Create(); print ''; print ''; diff --git a/htdocs/admin/ticket_public.php b/htdocs/admin/ticket_public.php index 1a4e3342cd0..0fd654b5d28 100644 --- a/htdocs/admin/ticket_public.php +++ b/htdocs/admin/ticket_public.php @@ -375,7 +375,7 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { print ''.$langs->trans("TicketPublicInterfaceTextHomeLabelAdmin").''; print ''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HOME', $public_text_home, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); + $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HOME', $public_text_home, '100%', 180, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_2, 70); $doleditor->Create(); print ''; print ''; @@ -387,7 +387,7 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { print ''.$langs->trans("TicketPublicInterfaceTextHelpMessageLabelAdmin").''; print ''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HELP_MESSAGE', $public_text_help_message, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); + $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HELP_MESSAGE', $public_text_help_message, '100%', 180, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_2, 70); $doleditor->Create(); print ''; print ''; @@ -434,7 +434,7 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { print ''; print ''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('TICKET_MESSAGE_MAIL_NEW', $mail_mesg_new, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70); + $doleditor = new DolEditor('TICKET_MESSAGE_MAIL_NEW', $mail_mesg_new, '100%', 120, 'dolibarr_mailings', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_MAIL'), ROWS_2, 70); $doleditor->Create(); print ''; print ''; diff --git a/htdocs/admin/webhook.php b/htdocs/admin/webhook.php new file mode 100644 index 00000000000..963b76c238a --- /dev/null +++ b/htdocs/admin/webhook.php @@ -0,0 +1,733 @@ + + * Copyright (C) 2022 SuperAdmin + * + * 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 webhook/admin/webhook.php + * \ingroup webhook + * \brief Webhook setup page. + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +global $langs, $user; + +// Libraries +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT.'/webhook/lib/webhook.lib.php'; + +// Translations +$langs->loadLangs(array("admin", "webhook")); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('webhooksetup', 'globalsetup')); + +// Access control +if (!$user->admin) { + accessforbidden(); +} + +// Parameters +$action = GETPOST('action', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); +$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php + +$value = GETPOST('value', 'alpha'); +$label = GETPOST('label', 'alpha'); +$scandir = GETPOST('scan_dir', 'alpha'); +$type = 'myobject'; + +$arrayofparameters = array( + 'WEBHOOK_MYPARAM1'=>array('type'=>'string', 'css'=>'minwidth500' ,'enabled'=>0), + //'WEBHOOK_MYPARAM2'=>array('type'=>'textarea','enabled'=>1), + //'WEBHOOK_MYPARAM3'=>array('type'=>'category:'.Categorie::TYPE_CUSTOMER, 'enabled'=>1), + //'WEBHOOK_MYPARAM4'=>array('type'=>'emailtemplate:thirdparty', 'enabled'=>1), + //'WEBHOOK_MYPARAM5'=>array('type'=>'yesno', 'enabled'=>1), + //'WEBHOOK_MYPARAM5'=>array('type'=>'thirdparty_type', 'enabled'=>1), + //'WEBHOOK_MYPARAM6'=>array('type'=>'securekey', 'enabled'=>1), + //'WEBHOOK_MYPARAM7'=>array('type'=>'product', 'enabled'=>1), +); + +$error = 0; +$setupnotempty = 0; + +// Set this to 1 to use the factory to manage constants. Warning, the generated module will be compatible with version v15+ only +$useFormSetup = 0; +// Convert arrayofparameter into a formSetup object +if ($useFormSetup && (float) DOL_VERSION >= 15) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsetup.class.php'; + $formSetup = new FormSetup($db); + + // you can use the param convertor + $formSetup->addItemsFromParamsArray($arrayofparameters); + + // or use the new system see exemple as follow (or use both because you can ;-) ) + + /* + // Hôte + $item = $formSetup->newItem('NO_PARAM_JUST_TEXT'); + $item->fieldOverride = (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . $_SERVER['HTTP_HOST']; + $item->cssClass = 'minwidth500'; + + // Setup conf WEBHOOK_MYPARAM1 as a simple string input + $item = $formSetup->newItem('WEBHOOK_MYPARAM1'); + + // Setup conf WEBHOOK_MYPARAM1 as a simple textarea input but we replace the text of field title + $item = $formSetup->newItem('WEBHOOK_MYPARAM2'); + $item->nameText = $item->getNameText().' more html text '; + + // Setup conf WEBHOOK_MYPARAM3 + $item = $formSetup->newItem('WEBHOOK_MYPARAM3'); + $item->setAsThirdpartyType(); + + // Setup conf WEBHOOK_MYPARAM4 : exemple of quick define write style + $formSetup->newItem('WEBHOOK_MYPARAM4')->setAsYesNo(); + + // Setup conf WEBHOOK_MYPARAM5 + $formSetup->newItem('WEBHOOK_MYPARAM5')->setAsEmailTemplate('thirdparty'); + + // Setup conf WEBHOOK_MYPARAM6 + $formSetup->newItem('WEBHOOK_MYPARAM6')->setAsSecureKey()->enabled = 0; // disabled + + // Setup conf WEBHOOK_MYPARAM7 + $formSetup->newItem('WEBHOOK_MYPARAM7')->setAsProduct(); + */ + + $setupnotempty = count($formSetup->items); +} + + +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; + +if ($action == 'updateMask') { + $maskconst = GETPOST('maskconst', 'alpha'); + $maskvalue = GETPOST('maskvalue', 'alpha'); + + if ($maskconst) { + $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity); + if (!($res > 0)) { + $error++; + } + } + + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } +} elseif ($action == 'specimen') { + $modele = GETPOST('module', 'alpha'); + $tmpobjectkey = GETPOST('object'); + + $tmpobject = new $tmpobjectkey($db); + $tmpobject->initAsSpecimen(); + + // Search template files + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir."core/modules/webhook/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0); + if (file_exists($file)) { + $filefound = 1; + $classname = "pdf_".$modele; + break; + } + } + + if ($filefound) { + require_once $file; + + $module = new $classname($db); + + if ($module->write_file($tmpobject, $langs) > 0) { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); + return; + } else { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } else { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } +} elseif ($action == 'setmod') { + // TODO Check if numbering module chosen can be activated by calling method canBeActivated + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'WEBHOOK_'.strtoupper($tmpobjectkey)."_ADDON"; + dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); + } +} elseif ($action == 'set') { + // Activate a model + $ret = addDocumentModel($value, $type, $label, $scandir); +} elseif ($action == 'del') { + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'WEBHOOK_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; + if ($conf->global->$constforval == "$value") { + dolibarr_del_const($db, $constforval, $conf->entity); + } + } + } +} elseif ($action == 'setdoc') { + // Set or unset default model + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'WEBHOOK_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; + if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->$constforval = $value; + } + + // We disable/enable the document template (into llx_document_model table) + $ret = delDocumentModel($value, $type); + if ($ret > 0) { + $ret = addDocumentModel($value, $type, $label, $scandir); + } + } +} elseif ($action == 'unsetdoc') { + $tmpobjectkey = GETPOST('object'); + if (!empty($tmpobjectkey)) { + $constforval = 'WEBHOOK_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; + dolibarr_del_const($db, $constforval, $conf->entity); + } +} + + + +/* + * View + */ + +$form = new Form($db); + +$help_url = ''; +$page_name = "WebhookSetup"; + +llxHeader('', $langs->trans($page_name), $help_url); + +// Subheader +$linkback = ''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); + +// Configuration header +$head = webhookAdminPrepareHead(); +print dol_get_fiche_head($head, 'settings', $langs->trans($page_name), -1, "webhook@webhook"); + +// Setup page goes here +echo ''.$langs->trans("WebhookSetupPage").'

'; + + +if ($action == 'edit') { + if ($useFormSetup && (float) DOL_VERSION >= 15) { + print $formSetup->generateOutput(true); + } else { + print '
'; + print ''; + print ''; + + print ''; + print ''; + + foreach ($arrayofparameters as $constname => $val) { + if ($val['enabled']==1) { + $setupnotempty++; + print ''; + } + } + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + $tooltiphelp = (($langs->trans($constname . 'Tooltip') != $constname . 'Tooltip') ? $langs->trans($constname . 'Tooltip') : ''); + print ''.$form->textwithpicto($langs->trans($constname), $tooltiphelp, 1, 'info', '', 0, 3, 'tootips'.$constname).''; + print ''; + + if ($val['type'] == 'textarea') { + print '\n"; + } elseif ($val['type']== 'html') { + require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; + $doleditor = new DolEditor($constname, $conf->global->{$constname}, '', 160, 'dolibarr_notes', '', false, false, $conf->fckeditor->enabled, ROWS_5, '90%'); + $doleditor->Create(); + } elseif ($val['type'] == 'yesno') { + print $form->selectyesno($constname, $conf->global->{$constname}, 1); + } elseif (preg_match('/emailtemplate:/', $val['type'])) { + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $val['type']); + $nboftemplates = $formmail->fetchAllEMailTemplate($tmp[1], $user, null, 1); // We set lang=null to get in priority record with no lang + //$arraydefaultmessage = $formmail->getEMailTemplate($db, $tmp[1], $user, null, 0, 1, ''); + $arrayofmessagename = array(); + if (is_array($formmail->lines_model)) { + foreach ($formmail->lines_model as $modelmail) { + //var_dump($modelmail); + $moreonlabel = ''; + if (!empty($arrayofmessagename[$modelmail->label])) { + $moreonlabel = ' (' . $langs->trans("SeveralLangugeVariatFound") . ')'; + } + // The 'label' is the key that is unique if we exclude the language + $arrayofmessagename[$modelmail->id] = $langs->trans(preg_replace('/\(|\)/', '', $modelmail->label)) . $moreonlabel; + } + } + print $form->selectarray($constname, $arrayofmessagename, $conf->global->{$constname}, 'None', 0, 0, '', 0, 0, 0, '', '', 1); + } elseif (preg_match('/category:/', $val['type'])) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + $formother = new FormOther($db); + + $tmp = explode(':', $val['type']); + print img_picto('', 'category', 'class="pictofixedwidth"'); + print $formother->select_categories($tmp[1], $conf->global->{$constname}, $constname, 0, $langs->trans('CustomersProspectsCategoriesShort')); + } elseif (preg_match('/thirdparty_type/', $val['type'])) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; + $formcompany = new FormCompany($db); + print $formcompany->selectProspectCustomerType($conf->global->{$constname}, $constname); + } elseif ($val['type'] == 'securekey') { + print ''; + if (!empty($conf->use_javascript_ajax)) { + print ' '.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token'.$constname.'" class="linkobject"'); + } + if (!empty($conf->use_javascript_ajax)) { + print "\n".''; + } + } elseif ($val['type'] == 'product') { + if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + $selected = (empty($conf->global->$constname) ? '' : $conf->global->$constname); + $form->select_produits($selected, $constname, '', 0); + } + } else { + print ''; + } + print '
'; + + print '
'; + print ''; + print '
'; + + print '
'; + } + + print '
'; +} else { + if ($useFormSetup && (float) DOL_VERSION >= 15) { + if (!empty($formSetup->items)) { + print $formSetup->generateOutput(); + } + } else { + if (!empty($arrayofparameters)) { + print ''; + print ''; + + foreach ($arrayofparameters as $constname => $val) { + if ($val['enabled']==1) { + $setupnotempty++; + print ''; + } + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + $tooltiphelp = (($langs->trans($constname . 'Tooltip') != $constname . 'Tooltip') ? $langs->trans($constname . 'Tooltip') : ''); + print $form->textwithpicto($langs->trans($constname), $tooltiphelp); + print ''; + + if ($val['type'] == 'textarea') { + print dol_nl2br($conf->global->{$constname}); + } elseif ($val['type']== 'html') { + print $conf->global->{$constname}; + } elseif ($val['type'] == 'yesno') { + print ajax_constantonoff($constname); + } elseif (preg_match('/emailtemplate:/', $val['type'])) { + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; + $formmail = new FormMail($db); + + $tmp = explode(':', $val['type']); + + $template = $formmail->getEMailTemplate($db, $tmp[1], $user, $langs, $conf->global->{$constname}); + if ($template<0) { + setEventMessages(null, $formmail->errors, 'errors'); + } + print $langs->trans($template->label); + } elseif (preg_match('/category:/', $val['type'])) { + $c = new Categorie($db); + $result = $c->fetch($conf->global->{$constname}); + if ($result < 0) { + setEventMessages(null, $c->errors, 'errors'); + } elseif ($result > 0 ) { + $ways = $c->print_all_ways(' >> ', 'none', 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text + $toprint = array(); + foreach ($ways as $way) { + $toprint[] = '
  • color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '
  • '; + } + print '
      ' . implode(' ', $toprint) . '
    '; + } + } elseif (preg_match('/thirdparty_type/', $val['type'])) { + if ($conf->global->{$constname}==2) { + print $langs->trans("Prospect"); + } elseif ($conf->global->{$constname}==3) { + print $langs->trans("ProspectCustomer"); + } elseif ($conf->global->{$constname}==1) { + print $langs->trans("Customer"); + } elseif ($conf->global->{$constname}==0) { + print $langs->trans("NorProspectNorCustomer"); + } + } elseif ($val['type'] == 'product') { + $product = new Product($db); + $resprod = $product->fetch($conf->global->{$constname}); + if ($resprod > 0) { + print $product->ref; + } elseif ($resprod < 0) { + setEventMessages(null, $object->errors, "errors"); + } + } else { + print $conf->global->{$constname}; + } + print '
    '; + } + } + + if ($setupnotempty) { + print '
    '; + print ''.$langs->trans("Modify").''; + print '
    '; + } else { + //print '
    '.$langs->trans("NothingToSetup"); + } +} + + +$moduledir = 'webhook'; +$myTmpObjects['MyObject'] = array('includerefgeneration'=>0, 'includedocgeneration'=>0); + + +foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { + if ($myTmpObjectKey == 'MyObject') { + continue; + } + if ($myTmpObjectArray['includerefgeneration']) { + /* + * Orders Numbering model + */ + $setupnotempty++; + + print load_fiche_titre($langs->trans("NumberingModules", $myTmpObjectKey), '', ''); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''."\n"; + + clearstatcache(); + + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/".$moduledir); + + if (is_dir($dir)) { + $handle = opendir($dir); + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') { + $file = substr($file, 0, dol_strlen($file) - 4); + + require_once $dir.'/'.$file.'.php'; + + $module = new $file($db); + + // Show modules according to features level + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + continue; + } + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { + continue; + } + + if ($module->isEnabled()) { + dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); + + print ''; + + // Show example of numbering model + print ''."\n"; + + print ''; + + $mytmpinstance = new $myTmpObjectKey($db); + $mytmpinstance->initAsSpecimen(); + + // Info + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
    '; + + $nextval = $module->getNextValue($mytmpinstance); + if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval + $htmltooltip .= ''.$langs->trans("NextValue").': '; + if ($nextval) { + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') { + $nextval = $langs->trans($nextval); + } + $htmltooltip .= $nextval.'
    '; + } else { + $htmltooltip .= $langs->trans($module->error).'
    '; + } + } + + print ''; + + print "\n"; + } + } + } + closedir($handle); + } + } + } + print "
    '.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Example").''.$langs->trans("Status").''.$langs->trans("ShortInfo").'
    '.$module->name."\n"; + print $module->info(); + print ''; + $tmp = $module->getExample(); + if (preg_match('/^Error/', $tmp)) { + $langs->load("errors"); + print '
    '.$langs->trans($tmp).'
    '; + } elseif ($tmp == 'NotConfigured') { + print $langs->trans($tmp); + } else { + print $tmp; + } + print '
    '; + $constforvar = 'WEBHOOK_'.strtoupper($myTmpObjectKey).'_ADDON'; + if ($conf->global->$constforvar == $file) { + print img_picto($langs->trans("Activated"), 'switch_on'); + } else { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print '

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

    '.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
    '.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
    '.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + + print ''; + + // Preview + print ''; + + print "\n"; + } + } + } + } + } + } + } + } + + print '
    '.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status")."'.$langs->trans("Default")."'.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
    '; + print (empty($module->name) ? $name : $module->name); + print "\n"; + if (method_exists($module, 'info')) { + print $module->info($langs); + } else { + print $module->description; + } + print ''."\n"; + print ''; + print img_picto($langs->trans("Enabled"), 'switch_on'); + print ''; + print ''."\n"; + print 'scandir).'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print "'; + $constforvar = 'WEBHOOK_'.strtoupper($myTmpObjectKey).'_ADDON'; + if ($conf->global->$constforvar == $name) { + //print img_picto($langs->trans("Default"), 'on'); + // Even if choice is the default value, we allow to disable it. Replace this with previous line if you need to disable unset + print 'scandir).'&label='.urlencode($module->name).'&type='.urlencode($type).'" alt="'.$langs->trans("Disable").'">'.img_picto($langs->trans("Enabled"), 'on').''; + } else { + print 'scandir).'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print ''; + if ($module->type == 'pdf') { + print ''.img_object($langs->trans("Preview"), 'pdf').''; + } else { + print img_object($langs->trans("PreviewNotAvailable"), 'generic'); + } + print '
    '; + } +} + +if (empty($setupnotempty)) { + print '
    '.$langs->trans("NothingToSetup"); +} + +// Page end +print dol_get_fiche_end(); + +llxFooter(); +$db->close(); diff --git a/htdocs/admin/website_options.php b/htdocs/admin/website_options.php index f6c92888384..1f5ebaec4c6 100644 --- a/htdocs/admin/website_options.php +++ b/htdocs/admin/website_options.php @@ -112,7 +112,7 @@ if ($action == 'edit') { foreach ($arrayofparameters as $key => $val) { print ''; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print ''; + print ''; } print ''; @@ -130,7 +130,7 @@ if ($action == 'edit') { foreach ($arrayofparameters as $key => $val) { print ''; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print ''.$conf->global->$key.''; + print ''.getDolGlobalString($key).''; } print ''; diff --git a/htdocs/admin/workstation.php b/htdocs/admin/workstation.php index 6ac7a425246..bdd7ba662cd 100644 --- a/htdocs/admin/workstation.php +++ b/htdocs/admin/workstation.php @@ -188,7 +188,7 @@ if ($action == 'edit') { print ''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''; + print ''; } print ''; @@ -209,7 +209,7 @@ if ($action == 'edit') { print ''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''.$conf->global->$key.''; + print ''.getDolGlobalString($key).''; } print ''; diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index ec3d75dee1a..361f2a5f1ce 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -246,7 +246,7 @@ if ($user->rights->categorie->creer) { // Description print ''.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('description', $description, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_5, '90%'); + $doleditor = new DolEditor('description', $description, '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_5, '90%'); $doleditor->Create(); print ''; diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 2bbb4b5f0a8..512f25a67e2 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -263,7 +263,7 @@ if ($action == 'edit') { // Desc $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); print ''.$langs->trans('Description').''; - $doleditor = new DolEditor("desc-$key", $desc, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor("desc-$key", $desc, '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print ''; @@ -323,7 +323,7 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print ''.$langs->trans('Label').''; print ''; print ''.$langs->trans('Description').''; - $doleditor = new DolEditor('desc', GETPOST('desc', 'restricthtml'), '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor('desc', GETPOST('desc', 'restricthtml'), '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print ''; diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 01d7102a47c..115f986e6e2 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -1121,7 +1121,7 @@ if ($object->id > 0) { * Latest contracts */ if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { - $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut as contract_status, c.datec as dc, c.date_contrat as dcon, c.ref_customer as refcus, c.ref_supplier as refsup"; + $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut as contract_status, c.datec as dc, c.date_contrat as dcon, c.ref_customer as refcus, c.ref_supplier as refsup, c.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c"; $sql .= " WHERE c.fk_soc = s.rowid "; $sql .= " AND s.rowid = ".((int) $object->id); @@ -1191,7 +1191,7 @@ if ($object->id > 0) { } } $relativepath = dol_sanitizeFileName($objp->ref).'/'.dol_sanitizeFileName($objp->ref).'.pdf'; - print $formfile->showPreview($file_list, $contrat->element, $relativepath, 0, $param); + print $formfile->showPreview($file_list, $contrat->element, $relativepath, 0); } // $filename = dol_sanitizeFileName($objp->ref); // $filedir = $conf->contrat->multidir_output[$objp->entity].'/'.dol_sanitizeFileName($objp->ref); @@ -1409,6 +1409,7 @@ if ($object->id > 0) { $sql .= ', f.total_ht'; $sql .= ', f.total_tva'; $sql .= ', f.total_ttc'; + $sql .= ', f.entity'; $sql .= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as status'; $sql .= ', s.nom, s.rowid as socid'; $sql .= ', SUM(pf.amount) as am'; @@ -1475,7 +1476,7 @@ if ($object->id > 0) { } } $relativepath = dol_sanitizeFileName($objp->ref).'/'.dol_sanitizeFileName($objp->ref).'.pdf'; - print $formfile->showPreview($file_list, $facturestatic->element, $relativepath, 0, $param); + print $formfile->showPreview($file_list, $facturestatic->element, $relativepath, 0); } // $filename = dol_sanitizeFileName($objp->ref); // $filedir = $conf->facture->multidir_output[$objp->entity].'/'.dol_sanitizeFileName($objp->ref); diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 5903b7e4bdb..c63ece66cd2 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -39,6 +39,9 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php'; +if (!empty($conf->ficheinter->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; +} // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array $hookmanager = new HookManager($db); @@ -100,6 +103,10 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $supplierorderstatic = new CommandeFournisseur($db); } +if (!empty($conf->ficheinter->enabled)) { + $fichinterstatic = new Fichinter($db); +} + llxHeader("", $langs->trans("CommercialArea")); print load_fiche_titre($langs->trans("CommercialArea"), '', 'commercial'); @@ -508,7 +515,12 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU * Draft interventionals */ if (!empty($conf->ficheinter->enabled)) { - $sql = "SELECT f.rowid, f.ref, s.nom as name, s.rowid as socid"; + $sql = "SELECT f.rowid, f.ref, s.nom as name, f.fk_statut"; + $sql .= ", s.rowid as socid, s.nom as name, s.name_alias"; + $sql .= ", s.code_client, s.code_compta, s.client"; + $sql .= ", s.code_fournisseur, s.code_compta_fournisseur, s.fournisseur"; + $sql .= ", s.logo, s.email, s.entity"; + $sql .= ", s.canvas"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (empty($user->rights->societe->client->voir) && !$socid) { @@ -524,22 +536,46 @@ if (!empty($conf->ficheinter->enabled)) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); } + $resql = $db->query($sql); if ($resql) { + $num = $db->num_rows($resql); + $nbofloop = min($num, $maxofloop); + print '
    '; print ''; print ''; print ''; - $langs->load("fichinter"); - $num = $db->num_rows($resql); + if ($num) { $i = 0; - while ($i < $num) { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); + + $fichinterstatic->id=$obj->rowid; + $fichinterstatic->ref=$obj->ref; + $fichinterstatic->statut=$obj->fk_statut; + + $companystatic->id = $obj->socid; + $companystatic->name = $obj->name; + $companystatic->name_alias = $obj->name_alias; + $companystatic->code_client = $obj->code_client; + $companystatic->code_compta = $obj->code_compta; + $companystatic->client = $obj->client; + $companystatic->code_fournisseur = $obj->code_fournisseur; + $companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; + $companystatic->fournisseur = $obj->fournisseur; + $companystatic->logo = $obj->logo; + $companystatic->email = $obj->email; + $companystatic->entity = $obj->entity; + $companystatic->canvas = $obj->canvas; print ''; - print '"; - print ''; + print '"; + print ''; $i++; } } diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index 15406da9211..d46a02132a1 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -753,7 +753,7 @@ if ($action == 'create') { print '
    '; // wysiwyg editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('bodyemail', GETPOST('bodyemail', 'restricthtmlallowunvalid'), '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); + $doleditor = new DolEditor('bodyemail', GETPOST('bodyemail', 'restricthtmlallowunvalid'), '', 600, 'dolibarr_mailings', '', true, true, getDolGlobalInt('FCKEDITOR_ENABLE_MAILING'), 20, '90%'); $doleditor->Create(); print '
    '; @@ -1273,7 +1273,7 @@ if ($action == 'create') { if ($action == 'edit') { // wysiwyg editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, $conf->global->FCKEDITOR_ENABLE_MAILING, 20, '90%'); + $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, true, getDolGlobalInt('FCKEDITOR_ENABLE_MAILING'), 20, '90%'); $doleditor->Create(); } if ($action == 'edithtml') { diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index aaf100d191a..c9b48665c95 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -384,6 +384,7 @@ if ($object->fetch($id) >= 0) { if ($allowaddtarget) { print ''; print ''; + print ''; } else { print '
    '; } @@ -428,7 +429,7 @@ if ($object->fetch($id) >= 0) { print '
    '; if ($allowaddtarget) { - print ''; + print ''; } else { print ''; //print $langs->trans("MailNoChangePossible"); diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 3427e38d99e..b74d458ba3a 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -2264,8 +2264,8 @@ class Commande extends CommonOrder } $sql .= ' ed.fk_origin_line = cd.rowid'; $sql .= ' AND cd.fk_commande = '.((int) $this->id); - if ($this->fk_product > 0) { - $sql .= ' AND cd.fk_product = '.((int) $this->fk_product); + if ($fk_product > 0) { + $sql .= ' AND cd.fk_product = '.((int) $fk_product); } if ($filtre_statut >= 0) { $sql .= ' AND e.fk_statut >= '.((int) $filtre_statut); diff --git a/htdocs/commande/tpl/linkedobjectblock.tpl.php b/htdocs/commande/tpl/linkedobjectblock.tpl.php index 8c1df906ab7..819a6ecb74f 100644 --- a/htdocs/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/commande/tpl/linkedobjectblock.tpl.php @@ -53,7 +53,7 @@ foreach ($linkedObjectBlock as $key => $objectlink) { echo ''; echo '
    '; echo ''; - echo ''; + echo ''; echo ''; diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index 0091dc39512..f75ce6d4471 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2017-2022 Alexandre Spangaro * Copyright (C) 2017 Laurent Destailleur * Copyright (C) 2018 Frédéric France * Copyright (C) 2020 Tobias Sekan @@ -35,6 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page $langs->loadLangs(array("compta", "banks", "bills", "accountancy")); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'directdebitcredittransferlist'; // To manage different context of search + // Security check $socid = GETPOST("socid", "int"); if ($user->socid) { @@ -75,6 +77,7 @@ if (empty($search_datev_start)) { if (empty($search_datev_end)) { $search_datev_end = GETPOST("search_datev_end", 'int'); } +$search_type_id = GETPOST('search_type_id', 'int'); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); @@ -94,19 +97,6 @@ if (!$sortorder) { $filtre = GETPOST("filtre", 'alpha'); -if (!GETPOST('typeid')) { - $newfiltre = str_replace('filtre=', '', $filtre); - $filterarray = explode('-', $newfiltre); - foreach ($filterarray as $val) { - $part = explode(':', $val); - if ($part[0] == 'v.fk_typepayment') { - $typeid = $part[1]; - } - } -} else { - $typeid = GETPOST('typeid'); -} - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers $search_ref = ''; $search_label = ''; @@ -120,7 +110,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_bank_entry = ''; $search_accountancy_account = ''; $search_accountancy_subledger = ''; - $typeid = ''; + $search_type_id = ''; } $search_all = GETPOSTISSET("search_all") ? trim(GETPOST("search_all", 'alpha')) : trim(GETPOST('sall')); @@ -265,8 +255,8 @@ if ($search_accountancy_account > 0) { if ($search_accountancy_subledger > 0) { $sql .= " AND v.subledger_account = ".((int) $search_accountancy_subledger); } -if ($typeid > 0) { - $sql .= " AND v.fk_typepayment=".((int) $typeid); +if ($search_type_id > 0) { + $sql .= " AND v.fk_typepayment=".((int) $search_type_id); } if ($search_all) { $sql .= natural_search(array_keys($fieldstosearchall), $search_all); @@ -324,8 +314,8 @@ if ($resql) { if ($search_datev_end) { $param .= '&search_datev_end='.urlencode($search_datev_end); } - if ($typeid > 0) { - $param .= '&typeid='.urlencode($typeid); + if ($search_type_id > 0) { + $param .= '&search_type_id='.urlencode($search_type_id); } if ($search_amount_deb) { $param .= '&search_amount_deb='.urlencode($search_amount_deb); @@ -375,6 +365,7 @@ if ($resql) { $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $moreforfilter= ''; print '
    '; print '
    '.$langs->trans("DraftFichinter").'
    '; - print "rowid."\">".img_object($langs->trans("ShowFichinter"), "intervention").' '.$obj->ref."'.img_object($langs->trans("ShowCompany"), "company").' '.dol_trunc($obj->name, 24).'
    '; + print $fichinterstatic->getNomUrl(1); + print "'; + print $companystatic->getNomUrl(1, 'customer'); + print '
    '.$objectlink->getNomUrl(1).''.$objectlink->ref_client.''.dol_print_date($objectlink->date, 'day').''.dol_print_date($objectlink->date, 'day').''; if ($user->rights->commande->lire) { $total = $total + $objectlink->total_ht; diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index 31a918b1a27..29341b0fb99 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -986,7 +986,7 @@ if ($action == 'create') { print ''; // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('account_comment', (GETPOST("account_comment") ?GETPOST("account_comment") : $object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '95%'); + $doleditor = new DolEditor('account_comment', (GETPOST("account_comment") ?GETPOST("account_comment") : $object->comment), '', 90, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_4, '95%'); $doleditor->Create(); print '
    '; @@ -427,7 +418,7 @@ if ($resql) { // Payment type if ($arrayfields['type']['checked']) { print ''; } @@ -544,6 +535,8 @@ if ($resql) { $totalarray = array(); + $totalarray['nbfield'] = 0; + $totalarray['val']['total_cred'] = 0; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -656,7 +649,7 @@ if ($resql) { if ($arrayfields['account']['checked']) { $accountingaccount->fetch('', $obj->accountancy_code, 1); - print ''; + print ''; if (!$i) { $totalarray['nbfield']++; } diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index c16b6523d1f..169666477f4 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -1,12 +1,12 @@ - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005-2010 Regis Houssin - * Copyright (C) 2011-2016 Alexandre Spangaro - * Copyright (C) 2011-2014 Juanjo Menent - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2019 Nicolas ZABOURI - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2001-2003 Rodolphe Quiedeville + * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2005-2010 Regis Houssin + * Copyright (C) 2011-2022 Alexandre Spangaro + * Copyright (C) 2011-2014 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -58,6 +58,7 @@ $filtre = GETPOST("filtre", 'alpha'); if (!$year) { $year = date("Y", time()); } +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') $search_account = GETPOST('search_account', 'int'); @@ -184,7 +185,6 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { $num = $db->num_rows($resql); $i = 0; $total = 0; - $totalnb = 0; $totalpaid = 0; while ($i < min($num, $limit)) { @@ -204,7 +204,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { print $socialcontrib->getNomUrl(1, '20'); print ''; // Type - print ''; + print ''; // Expected to pay print ''; // Ref payment @@ -246,7 +246,6 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { print ''; $total = $total + $obj->total; - $totalnb = $totalnb + $obj->nb; $totalpaid = $totalpaid + $obj->totalpaid; $i++; } @@ -274,7 +273,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { print load_fiche_titre($langs->trans("VATDeclarations").($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); - $sql = "SELECT ptva.rowid, pv.rowid as id_tva, pv.amount as amount_tva, ptva.amount, pv.label, pv.datev as dm, ptva.datep as date_payment, ptva.fk_bank,"; + $sql = "SELECT ptva.rowid, pv.rowid as id_tva, pv.amount as amount_tva, ptva.amount, pv.label, pv.datev as dm, ptva.datep as date_payment, ptva.fk_bank, ptva.num_paiement as num_payment,"; $sql .= " pct.code as payment_code,"; $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; $sql .= " FROM ".MAIN_DB_PREFIX."tva as pv"; diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 166f38040c2..e963057f7ef 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -256,7 +256,7 @@ $arrayfields = array( 'f.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), ); -if (getDolGlobalString("INVOICE_USE_SITUATION") && $conf->global->INVOICE_USE_RETAINED_WARRANTY) { +if (getDolGlobalString("INVOICE_USE_SITUATION") && !empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) { $arrayfields['f.retained_warranty'] = array('label'=>$langs->trans("RetainedWarranty"), 'checked'=>0, 'position'=>86); } // Overwrite $arrayfields from columns into ->fields (transition before removal of $arrayoffields) diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index db48b2767f2..ba62c36b0fa 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -1,6 +1,7 @@ * Copyright (C) 2016-2018 Frédéric France + * Copyright (C) 2022 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -254,6 +255,7 @@ if ($action == 'create') { print "\n"; $total = 0; + $total_ttc = 0; $totalrecu = 0; while ($i < $num) { diff --git a/htdocs/compta/payment_sc/card.php b/htdocs/compta/payment_sc/card.php index b1ec9800aa5..f5ff5a101f2 100644 --- a/htdocs/compta/payment_sc/card.php +++ b/htdocs/compta/payment_sc/card.php @@ -1,8 +1,9 @@ - * Copyright (C) 2004-2014 Laurent Destailleur - * Copyright (C) 2005 Marc Barilley / Ocebo - * Copyright (C) 2005-2009 Regis Houssin +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2022 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -134,7 +135,7 @@ print ''; // Amount -print ''; +print ''; // Note print ''; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index fed5a42c04e..6cc3496ced0 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -1,9 +1,9 @@ - * Copyright (C) 2005-2013 Regis Houssin - * Copyright (C) 2016-2018 Frédéric France - * Copyright (C) 2017 Alexandre Spangaro - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2004-2020 Laurent Destailleur + * Copyright (C) 2005-2013 Regis Houssin + * Copyright (C) 2016-2018 Frédéric France + * Copyright (C) 2017-2022 Alexandre Spangaro + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -53,6 +53,7 @@ $cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); +$lineid = GETPOST('lineid', 'int'); $fk_project = (GETPOST('fk_project') ? GETPOST('fk_project', 'int') : 0); diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 1b83915714d..318e7fcd96b 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -1,6 +1,7 @@ - * Copyright (C) 2004-2007 Laurent Destailleur +/* Copyright (C) 2002 Rodolphe Quiedeville + * Copyright (C) 2004-2007 Laurent Destailleur + * Copyright (C) 2022 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -544,7 +545,7 @@ class PaymentSocialContribution extends CommonObject */ public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) { - global $conf; + global $conf, $langs; // Clean data $this->num_payment = trim($this->num_payment); diff --git a/htdocs/compta/sociales/list.php b/htdocs/compta/sociales/list.php index 93c8dea0a3e..14b8bfa043f 100644 --- a/htdocs/compta/sociales/list.php +++ b/htdocs/compta/sociales/list.php @@ -1,12 +1,12 @@ - * Copyright (C) 2004-2017 Laurent Destailleur - * Copyright (C) 2005-2009 Regis Houssin - * Copyright (C) 2016 Frédéric France - * Copyright (C) 2020 Pierre Ardoin - * Copyright (C) 2020 Tobias Sekan - * Copyright (C) 2021 Gauthier VERDOL - * Copyright (C) 2021 Alexandre Spangaro +/* Copyright (C) 2001-2003 Rodolphe Quiedeville + * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2016 Frédéric France + * Copyright (C) 2020 Pierre Ardoin + * Copyright (C) 2020 Tobias Sekan + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) 2021-2022 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -41,16 +41,17 @@ if (!empty($conf->project->enabled)) { // Load translation files required by the page $langs->loadLangs(array('compta', 'banks', 'bills', 'hrm', 'projects')); -$action = GETPOST('action', 'aZ09'); -$massaction = GETPOST('massaction', 'alpha'); -$confirm = GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); -$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'sclist'; +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'sclist'; -$search_ref = GETPOST('search_ref', 'int'); +$search_ref = GETPOST('search_ref', 'int'); $search_label = GETPOST('search_label', 'alpha'); -$search_amount = GETPOST('search_amount', 'alpha'); -$search_status = GETPOST('search_status', 'int'); +$search_typeid = GETPOST('search_typeid', 'int'); +$search_amount = GETPOST('search_amount', 'alpha'); +$search_status = GETPOST('search_status', 'int'); $search_date_startday = GETPOST('search_date_startday', 'int'); $search_date_startmonth = GETPOST('search_date_startmonth', 'int'); $search_date_startyear = GETPOST('search_date_startyear', 'int'); @@ -70,11 +71,11 @@ $search_date_limit_end = dol_mktime(23, 59, 59, $search_date_limit_endmonth, $se $search_project_ref = GETPOST('search_project_ref', 'alpha'); $search_users = GETPOST('search_users'); $search_type = GETPOST('search_type', 'int'); -$search_account = GETPOST('search_account', 'int'); +$search_account = GETPOST('search_account', 'int'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; -$sortfield = GETPOST('sortfield', 'aZ09comma'); -$sortorder = GETPOST("sortorder", 'aZ09comma'); +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST("sortorder", 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { @@ -93,19 +94,6 @@ if (!$sortorder) { $filtre = GETPOST("filtre", 'int'); -if (!GETPOSTISSET('search_typeid')) { - $newfiltre = str_replace('filtre=', '', $filtre); - $filterarray = explode('-', $newfiltre); - foreach ($filterarray as $val) { - $part = explode(':', $val); - if ($part[0] == 'cs.fk_type') { - $search_typeid = $part[1]; - } - } -} else { - $search_typeid = GETPOST('search_typeid', 'int'); -} - $arrayfields = array( 'cs.rowid' =>array('label'=>"Ref", 'checked'=>1, 'position'=>10), 'cs.libelle' =>array('label'=>"Label", 'checked'=>1, 'position'=>20), @@ -388,6 +376,9 @@ if (empty($mysoc->country_id) && empty($mysoc->country_code)) { $db->close(); } +$moreforfilter = ''; +$massactionbutton = ''; + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields if ($massactionbutton) { @@ -551,7 +542,9 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', '', $ print ''; $i = 0; - $totalarray = $TLoadedUsers = array(); +$totalarray = $TLoadedUsers = array(); +$totalarray['nbfield'] = 0; +$totalarray['val']['totalttcfield'] = 0; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); diff --git a/htdocs/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index d2646d241ea..843dbd58a50 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -1,12 +1,12 @@ - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005-2010 Regis Houssin - * Copyright (C) 2011-2016 Alexandre Spangaro - * Copyright (C) 2011-2014 Juanjo Menent - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2019 Nicolas ZABOURI - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2001-2003 Rodolphe Quiedeville + * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2005-2010 Regis Houssin + * Copyright (C) 2011-2022 Alexandre Spangaro + * Copyright (C) 2011-2014 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -37,6 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; +if (!empty($conf->accounting->enabled)) { + include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} $hookmanager = new HookManager($db); @@ -48,6 +51,7 @@ $langs->loadLangs(array('compta', 'bills', 'hrm')); $year = GETPOST("year", 'int'); $search_sc_type = GETPOST('search_sc_type', 'int'); +$optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); @@ -123,6 +127,9 @@ if ($year) { if ($search_sc_type) { $param .= '&search_sc_type='.urlencode($search_sc_type); } +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} $num = 0; print ''; @@ -139,14 +146,16 @@ $sql = "SELECT c.id, c.libelle as type_label,"; $sql .= " cs.rowid, cs.libelle as label_sc, cs.fk_type as type, cs.periode, cs.date_ech, cs.amount as total, cs.paye,"; $sql .= " pc.rowid as pid, pc.datep, pc.amount as totalpaid, pc.num_paiement as num_payment, pc.fk_bank,"; $sql .= " pct.code as payment_code,"; -$sql .= " u.rowid uid, u.lastname, u.firstname, u.email, u.login, u.admin,"; -$sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel, ba.iban_prefix as iban, ba.bic, ba.currency_code, ba.clos"; +$sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.login, u.admin, u.statut,"; +$sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel, ba.iban_prefix as iban, ba.bic, ba.currency_code, ba.clos,"; +$sql .= " aj.label as account_journal"; $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql .= " ".MAIN_DB_PREFIX."chargesociales as cs"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_journal as aj ON ba.fk_accountancy_journal = aj.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = cs.fk_user"; $sql .= " WHERE cs.fk_type = c.id"; $sql .= " AND cs.entity IN (".getEntity("tax").")"; @@ -278,7 +287,7 @@ while ($i < min($num, $limit)) { print $socialcontrib->getNomUrl(1, ''); print ''; // Type - print ''; + print ''; // Date $date = $obj->periode; if (empty($date)) { @@ -297,8 +306,7 @@ while ($i < min($num, $limit)) { $userstatic->admin = $obj->admin; $userstatic->login = $obj->login; $userstatic->email = $obj->email; - $userstatic->socid = $obj->fk_soc; - $userstatic->statut = $obj->status; + $userstatic->statut = $obj->statut; print $userstatic->getNomUrl(1); print "\n"; } @@ -327,13 +335,16 @@ while ($i < min($num, $limit)) { $accountstatic->id = $obj->bid; $accountstatic->ref = $obj->bref; $accountstatic->number = $obj->bnumber; - $accountstatic->accountancy_number = $obj->account_number; - $accountstatic->accountancy_journal = $obj->accountancy_journal; $accountstatic->label = $obj->blabel; $accountstatic->iban = $obj->iban; $accountstatic->bic = $obj->bic; $accountstatic->currency_code = $langs->trans("Currency".$obj->currency_code); $accountstatic->clos = $obj->clos; + + if (!empty($conf->accounting->enabled)) { + $accountstatic->account_number = $obj->account_number; + $accountstatic->accountancy_journal = $obj->account_journal; + } print $accountstatic->getNomUrl(1); } else { print ' '; @@ -356,7 +367,6 @@ while ($i < min($num, $limit)) { print ''; $total = $total + $obj->total; - $totalnb = $totalnb + $obj->nb; $totalpaid = $totalpaid + $obj->totalpaid; $i++; } diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index ecc8ec22660..0f61ecada43 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -1415,7 +1415,7 @@ if ($action == 'create') { } - $arrayothercontracts = $object->getListOfContracts('others'); + $arrayothercontracts = $object->getListOfContracts('others'); // array or -1 if technical error /* * Lines of contracts @@ -1544,9 +1544,9 @@ if ($action == 'create') { print ''; } - // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) + // Icon move, update et delete (status contract 0=draft,1=validated,2=closed) print ''; $formconfirm .= ''; $formconfirm .= ''; $formconfirm .= ''."\n"; @@ -8844,9 +8847,11 @@ class Form * @param int $useempty 1=Add empty line * @param int $addjscombo 1=Add js beautifier on combo box * @param string $morecss More CSS - * @return string See option + * @param string $labelyes Label for Yes + * @param string $labelno Label for No + * @return string See option */ - public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '') + public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No') { global $langs; @@ -8857,6 +8862,7 @@ class Form $no = "0"; } + $disabled = ($disabled ? ' disabled' : ''); $resultyesno = ''."\n"; diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index 4e0d3da467e..5bee2f31dd4 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -700,11 +700,14 @@ class FormOther print ' selected'; } - $labeltoshow = $langs->trans("Project").' '.$lines[$i]->projectref; + $labeltoshow = $lines[$i]->projectref; + //$labeltoshow .= ' '.$lines[$i]->projectlabel; if (empty($lines[$i]->public)) { - $labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')'; + //$labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')'; + $labeltoshow = img_picto($lines[$i]->projectlabel, 'project', 'class="pictofixedwidth"').$labeltoshow; } else { - $labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')'; + //$labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')'; + $labeltoshow = img_picto($lines[$i]->projectlabel, 'projectpub', 'class="pictofixedwidth"').$labeltoshow; } print ' data-html="'.dol_escape_htmltag($labeltoshow).'"'; @@ -738,12 +741,14 @@ class FormOther print ' disabled'; } - $labeltoshow = $langs->trans("Project").' '.$lines[$i]->projectref; - $labeltoshow .= ' '.$lines[$i]->projectlabel; + $labeltoshow = $lines[$i]->projectref; + //$labeltoshow .= ' '.$lines[$i]->projectlabel; if (empty($lines[$i]->public)) { - $labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')'; + //$labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')'; + $labeltoshow = img_picto($lines[$i]->projectlabel, 'project', 'class="pictofixedwidth"').$labeltoshow; } else { - $labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')'; + //$labeltoshow .= ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')'; + $labeltoshow = img_picto($lines[$i]->projectlabel, 'projectpub', 'class="pictofixedwidth"').$labeltoshow; } if ($lines[$i]->id) { $labeltoshow .= ' > '; diff --git a/htdocs/core/class/html.formticket.class.php b/htdocs/core/class/html.formticket.class.php index d837cf06030..e13aaba4685 100644 --- a/htdocs/core/class/html.formticket.class.php +++ b/htdocs/core/class/html.formticket.class.php @@ -418,7 +418,7 @@ class FormTicket } include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $uselocalbrowser = true; - $doleditor = new DolEditor('message', $msg, '100%', 230, $toolbarname, 'In', true, $uselocalbrowser, $conf->global->FCKEDITOR_ENABLE_TICKET, ROWS_8, '90%'); + $doleditor = new DolEditor('message', $msg, '100%', 230, $toolbarname, 'In', true, $uselocalbrowser, getDolGlobalInt('FCKEDITOR_ENABLE_TICKET'), ROWS_8, '90%'); $doleditor->Create(); print ''; @@ -1475,7 +1475,7 @@ class FormTicket print ''; @@ -1512,7 +1512,7 @@ class FormTicket //$toolbarname = 'dolibarr_details'; $toolbarname = 'dolibarr_notes'; include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('message', $defaultmessage, '100%', 200, $toolbarname, '', false, $uselocalbrowser, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, 70); + $doleditor = new DolEditor('message', $defaultmessage, '100%', 200, $toolbarname, '', false, $uselocalbrowser, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, 70); $doleditor->Create(); print ''; @@ -1524,7 +1524,7 @@ class FormTicket print $form->textwithpicto('', $langs->trans("TicketMessageMailSignatureHelp"), 1, 'help'); print ''; } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index bf41b5a624a..13ccde98bf2 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -745,7 +745,7 @@ function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null // - posted value not empty, or // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). - if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep + if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out; } } @@ -3917,7 +3917,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring', 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice', 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda', - 'uncheck', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'world', 'private', + 'uncheck', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private', 'conferenceorbooth', 'eventorganization' ))) { $fakey = $pictowithouttext; @@ -3968,7 +3968,7 @@ function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $ 'title_agenda'=>'calendar-alt', 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card', 'jabber'=>'comment-o', - 'website'=>'globe-americas', 'workstation'=>'pallet', 'world'=>'globe', 'private'=>'user-lock', + 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock', 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram' ); if ($pictowithouttext == 'off') { diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index d53870128fc..273922ff615 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -650,7 +650,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if ($showproject) { // Project ref - print "\n"; } // Date start if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) { - print ''; } // Date end if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) { - print ''; diff --git a/htdocs/core/modules/expedition/mod_expedition_ribera.php b/htdocs/core/modules/expedition/mod_expedition_ribera.php index 736ddc3ab3f..aae32f0f459 100644 --- a/htdocs/core/modules/expedition/mod_expedition_ribera.php +++ b/htdocs/core/modules/expedition/mod_expedition_ribera.php @@ -80,7 +80,7 @@ class mod_expedition_ribera extends ModelNumRefExpedition $tooltip .= $langs->trans("GenericMaskCodes5"); $texte .= ''; - $texte .= ''; + $texte .= ''; $texte .= ''; $texte .= ''; $texte .= '
    '; - $form->select_types_paiements($typeid, 'typeid', '', 0, 1, 1, 16, 1, 'maxwidth100'); + $form->select_types_paiements($search_type_id, 'search_type_id', '', 0, 1, 1, 16, 1, 'maxwidth100'); print ''.$accountingaccount->getNomUrl(0, 1, 1, '', 1).''.$accountingaccount->getNomUrl(0, 1, 1, '', 1).''.$obj->label.''.$obj->label.''.price($obj->total).'
    '.$langs->trans('Mode').''.$langs->trans("Pa print '
    '.$langs->trans('Numero').''.$object->num_payment.'
    '.$langs->trans('Amount').''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
    '.$langs->trans('Amount').''.price($object->amount, 0, $langs, 1, -1, -1, $conf->currency).'
    '.$langs->trans('Note').''.nl2br($object->note).'
    '.$obj->label.''.$obj->label_sc.'
    '.price($objp->pa_ht).''; - if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) { + if ($user->rights->contrat->creer && is_array($arrayothercontracts) && count($arrayothercontracts) && ($object->statut >= 0)) { print ''; print ''; print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow'); diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index ca52dcc6c91..ee59a5465dc 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -2126,7 +2126,7 @@ class Contrat extends CommonObject } /** - * Return list of other contracts for same company than current contract + * Return list of other contracts for the same company than current contract * * @param string $option 'all' or 'others' * @param array $status sort contracts having these status @@ -2138,7 +2138,7 @@ class Contrat extends CommonObject { $tab = array(); - $sql = "SELECT c.rowid, c.ref"; + $sql = "SELECT c.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; if (!empty($product_categories)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON cd.fk_contrat = c.rowid"; @@ -2159,12 +2159,12 @@ class Contrat extends CommonObject $obj = $this->db->fetch_object($resql); $contrat = new Contrat($this->db); $contrat->fetch($obj->rowid); - $tab[] = $contrat; + $tab[$contrat->id] = $contrat; $i++; } return $tab; } else { - $this->error = $this->db->error(); + $this->error = $this->db->lasterror(); return -1; } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 9ec4db2bd11..dfc9cdc7223 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -1055,6 +1055,8 @@ if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == ' if (in_array($objecttmp->element, array('societe', 'member'))) { $result = $objecttmp->delete($objecttmp->id, $user, 1); + } elseif (in_array($objecttmp->element, array('action'))) { + $result = $objecttmp->delete(); } else { $result = $objecttmp->delete($user); } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 2330ad56705..88f7f7aaa9a 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4749,7 +4749,7 @@ class Form print img_picto('', 'bank_account', 'class="pictofixedwidth"'); $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty); if ($nbaccountfound > 0) { - print ''; + print ''; } print ''; } else { @@ -4901,9 +4901,11 @@ class Form * @param int|string $height Force height of box (0 = auto) * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a
    section. + * @param string $labelbuttonyes Label for Yes + * @param string $labelbuttonno Label for No * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form */ - public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0) + public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No') { global $langs, $conf; @@ -5012,7 +5014,7 @@ class Form $more .= ' checked="checked"'; } $more .= ' /> '; - $more .= ''; + $more .= ''; $more .= ''."\n"; $i++; } @@ -5118,6 +5120,7 @@ class Form $(this).parent().find("button.ui-button:eq(2)").focus(); },'; } + $formconfirm .= ' resizable: false, height: "'.$height.'", @@ -5125,7 +5128,7 @@ class Form modal: true, closeOnEscape: false, buttons: { - "'.dol_escape_js($langs->transnoentities("Yes")).'": function() { + "'.dol_escape_js($langs->transnoentities($labelbuttonyes)).'": function() { var options = "&token='.urlencode(newToken()).'"; var inputok = '.json_encode($inputok).'; /* List of fields into form */ var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'"; @@ -5148,7 +5151,7 @@ class Form if (pageyes.length > 0) { location.href = urljump; } $(this).dialog("close"); }, - "'.dol_escape_js($langs->transnoentities("No")).'": function() { + "'.dol_escape_js($langs->transnoentities($labelbuttonno)).'": function() { var options = "&token='.urlencode(newToken()).'"; var inputko = '.json_encode($inputko).'; /* List of fields into form */ var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'"; @@ -5213,7 +5216,7 @@ class Form $formconfirm .= '
    '.$question.''; - $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly'); + $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno); $formconfirm .= ''; $formconfirm .= '
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('mail_intro', $mail_intro, '100%', 90, 'dolibarr_details', '', false, $uselocalbrowser, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); + $doleditor = new DolEditor('mail_intro', $mail_intro, '100%', 90, 'dolibarr_details', '', false, $uselocalbrowser, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_2, 70); $doleditor->Create(); print '
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('mail_signature', $mail_signature, '100%', 150, 'dolibarr_details', '', false, $uselocalbrowser, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70); + $doleditor = new DolEditor('mail_signature', $mail_signature, '100%', 150, 'dolibarr_details', '', false, $uselocalbrowser, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_2, 70); $doleditor->Create(); print '
    "; + print ''; //if ($showlineingray) print ''; if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) { print $projectstatic->getNomUrl(1); @@ -701,21 +701,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } if (count($arrayfields) > 0 && !empty($arrayfields['t.description']['checked'])) { - print ""; + print ''; print $lines[$i]->description; print "'; + print ''; print dol_print_date($lines[$i]->date_start, 'dayhour'); print ''; + print ''; print dol_print_date($lines[$i]->date_end, 'dayhour'); if ($taskstatic->hasDelay()) { print img_warning($langs->trans("Late")); @@ -2549,8 +2549,8 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $projectstatic->ref = $objp->ref; $projectstatic->status = $objp->status; $projectstatic->title = $objp->title; - $projectstatic->datee = $db->jdate($objp->datee); - $projectstatic->dateo = $db->jdate($objp->dateo); + $projectstatic->date_end = $db->jdate($objp->datee); + $projectstatic->date_start = $db->jdate($objp->dateo); print '
    '.$langs->trans("Mask").':'.$form->textwithpicto('', $tooltip, 1, 1).''.$form->textwithpicto('', $tooltip, 1, 1).' 
    '; @@ -125,9 +125,9 @@ class mod_expedition_ribera extends ModelNumRefExpedition require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $mask = $conf->global->EXPEDITION_RIBERA_MASK; + $mask = getDolGlobalString('EXPEDITION_RIBERA_MASK'); - if (!$mask) { + if (empty($mask)) { $this->error = 'NotConfigured'; return 0; } diff --git a/htdocs/core/modules/modWebhook.class.php b/htdocs/core/modules/modWebhook.class.php new file mode 100644 index 00000000000..fbcb5f81003 --- /dev/null +++ b/htdocs/core/modules/modWebhook.class.php @@ -0,0 +1,542 @@ + + * Copyright (C) 2018-2019 Nicolas ZABOURI + * Copyright (C) 2019-2020 Frédéric France + * Copyright (C) 2022 SuperAdmin + * + * 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 . + */ + +/** + * \defgroup webhook Module Webhook + * \brief Webhook module descriptor. + * + * \file htdocs/webhook/core/modules/modWebhook.class.php + * \ingroup webhook + * \brief Description and activation file for module Webhook + */ +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; + +/** + * Description and activation class for module Webhook + */ +class modWebhook extends DolibarrModules +{ + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $langs, $conf; + $this->db = $db; + + // Id for module (must be unique). + // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). + $this->numero = 68305; // TODO Go on page https://wiki.dolibarr.org/index.php/List_of_modules_id to reserve an id number for your module + + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'webhook'; + + // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...' + // It is used to group modules by family in module setup page + $this->family = "interface"; + + // Module position in the family on 2 digits ('01', '10', '20', ...) + $this->module_position = '90'; + + // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) + //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); + // Module label (no space allowed), used if translation string 'ModuleWebhookName' not found (Webhook is name of module). + $this->name = preg_replace('/^mod/i', '', get_class($this)); + + // Module description, used if translation string 'ModuleWebhookDesc' not found (Webhook is name of module). + $this->description = "WebhookDescription"; + // Used only if file README.md and README-LL.md not found. + $this->descriptionlong = "WebhookDescription"; + + // Author + $this->editor_name = 'Editor name'; + $this->editor_url = 'https://www.example.com'; + + // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z' + $this->version = 'development'; + // Url to the file with your last numberversion of this module + //$this->url_last_version = 'http://www.example.com/versionmodule.txt'; + + // Key used in llx_const table to save module status enabled/disabled (where WEBHOOK is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + + // Name of image file used for this module. + // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' + // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' + // To use a supported fa-xxx css style of font awesome, use this->picto='xxx' + $this->picto = 'webhook'; + + // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) + $this->module_parts = array( + // Set this to 1 if module has its own trigger directory (core/triggers) + 'triggers' => 1, + // Set this to 1 if module has its own login method file (core/login) + 'login' => 0, + // Set this to 1 if module has its own substitution function file (core/substitutions) + 'substitutions' => 0, + // Set this to 1 if module has its own menus handler directory (core/menus) + 'menus' => 0, + // Set this to 1 if module overwrite template dir (core/tpl) + 'tpl' => 0, + // Set this to 1 if module has its own barcode directory (core/modules/barcode) + 'barcode' => 0, + // Set this to 1 if module has its own models directory (core/modules/xxx) + 'models' => 1, + // Set this to 1 if module has its own printing directory (core/modules/printing) + 'printing' => 0, + // Set this to 1 if module has its own theme directory (theme) + 'theme' => 0, + // Set this to relative path of css file if module has its own css file + 'css' => array( + // '/webhook/css/webhook.css.php', + ), + // Set this to relative path of js file if module must load a js on all pages + 'js' => array( + // '/webhook/js/webhook.js.php', + ), + // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all' + 'hooks' => array( + // 'data' => array( + // 'hookcontext1', + // 'hookcontext2', + // ), + // 'entity' => '0', + ), + // Set this to 1 if features of module are opened to external users + 'moduleforexternal' => 0, + ); + + // Data directories to create when module is enabled. + // Example: this->dirs = array("/webhook/temp","/webhook/subdir"); + $this->dirs = array("/webhook/temp"); + + // Config pages. Put here list of php page, stored into webhook/admin directory, to use to setup module. + $this->config_page_url = array("webhook.php"); + + // Dependencies + // A condition to hide module + $this->hidden = false; + // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) + $this->depends = array(); + $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) + + // The language file dedicated to your module + $this->langfiles = array("webhook"); + + // Prerequisites + $this->phpmin = array(5, 6); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(11, -3); // Minimum version of Dolibarr required by module + + // Messages at activation + $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','MX'='textmx'...) + $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','MX'='textmx'...) + //$this->automatic_activation = array('FR'=>'WebhookWasAutomaticallyActivatedBecauseOfYourCountryChoice'); + //$this->always_enabled = true; // If true, can't be disabled + + // Constants + // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) + // Example: $this->const=array(1 => array('WEBHOOK_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1), + // 2 => array('WEBHOOK_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1) + // ); + $this->const = array(); + + // Some keys to add into the overwriting translation tables + /*$this->overwrite_translation = array( + 'en_US:ParentCompany'=>'Parent company or reseller', + 'fr_FR:ParentCompany'=>'Maison mère ou revendeur' + )*/ + + if (!isset($conf->webhook) || !isset($conf->webhook->enabled)) { + $conf->webhook = new stdClass(); + $conf->webhook->enabled = 0; + } + + // Array to add new pages in new tabs + $this->tabs = array(); + // Example: + // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@webhook:$user->rights->webhook->read:/webhook/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1 + // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@webhook:$user->rights->othermodule->read:/webhook/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. + // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname + // + // Where objecttype can be + // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) + // 'contact' to add a tab in contact view + // 'contract' to add a tab in contract view + // 'group' to add a tab in group view + // 'intervention' to add a tab in intervention view + // 'invoice' to add a tab in customer invoice view + // 'invoice_supplier' to add a tab in supplier invoice view + // 'member' to add a tab in fundation member view + // 'opensurveypoll' to add a tab in opensurvey poll view + // 'order' to add a tab in customer order view + // 'order_supplier' to add a tab in supplier order view + // 'payment' to add a tab in payment view + // 'payment_supplier' to add a tab in supplier payment view + // 'product' to add a tab in product view + // 'propal' to add a tab in propal view + // 'project' to add a tab in project view + // 'stock' to add a tab in stock view + // 'thirdparty' to add a tab in third party view + // 'user' to add a tab in user view + + // Dictionaries + $this->dictionaries = array(); + /* Example: + $this->dictionaries=array( + 'langs'=>'webhook@webhook', + // List of tables we want to see into dictonnary editor + 'tabname'=>array(MAIN_DB_PREFIX."table1", MAIN_DB_PREFIX."table2", MAIN_DB_PREFIX."table3"), + // Label of tables + 'tablib'=>array("Table1", "Table2", "Table3"), + // Request to select fields + 'tabsql'=>array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'), + // Sort order + 'tabsqlsort'=>array("label ASC", "label ASC", "label ASC"), + // List of fields (result of select to show dictionary) + 'tabfield'=>array("code,label", "code,label", "code,label"), + // List of fields (list of fields to edit a record) + 'tabfieldvalue'=>array("code,label", "code,label", "code,label"), + // List of fields (list of fields for insert) + 'tabfieldinsert'=>array("code,label", "code,label", "code,label"), + // Name of columns with primary key (try to always name it 'rowid') + 'tabrowid'=>array("rowid", "rowid", "rowid"), + // Condition to show each dictionary + 'tabcond'=>array($conf->webhook->enabled, $conf->webhook->enabled, $conf->webhook->enabled) + ); + */ + + // Boxes/Widgets + // Add here list of php file(s) stored in webhook/core/boxes that contains a class to show a widget. + $this->boxes = array( + // 0 => array( + // 'file' => 'webhookwidget1.php@webhook', + // 'note' => 'Widget provided by Webhook', + // 'enabledbydefaulton' => 'Home', + // ), + // ... + ); + + // Cronjobs (List of cron jobs entries to add when module is enabled) + // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week + $this->cronjobs = array( + // 0 => array( + // 'label' => 'MyJob label', + // 'jobtype' => 'method', + // 'class' => '/webhook/class/webhook_target.class.php', + // 'objectname' => 'Webhook_target', + // 'method' => 'doScheduledJob', + // 'parameters' => '', + // 'comment' => 'Comment', + // 'frequency' => 2, + // 'unitfrequency' => 3600, + // 'status' => 0, + // 'test' => '$conf->webhook->enabled', + // 'priority' => 50, + // ), + ); + // Example: $this->cronjobs=array( + // 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->webhook->enabled', 'priority'=>50), + // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->webhook->enabled', 'priority'=>50) + // ); + + // Permissions provided by this module + $this->rights = array(); + $r = 0; + // Add here entries to declare new permissions + /* BEGIN MODULEBUILDER PERMISSIONS */ + $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = 'Read objects of Webhook'; // Permission label + $this->rights[$r][4] = 'webhook_target'; + $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->webhook->webhook_target->read) + $r++; + $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = 'Create/Update objects of Webhook'; // Permission label + $this->rights[$r][4] = 'webhook_target'; + $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->webhook->webhook_target->write) + $r++; + $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = 'Delete objects of Webhook'; // Permission label + $this->rights[$r][4] = 'webhook_target'; + $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->webhook->webhook_target->delete) + $r++; + /* END MODULEBUILDER PERMISSIONS */ + + // Main menu entries to add + $this->menu = array(); + $r = 0; + // Add here entries to declare new menus + /* BEGIN MODULEBUILDER TOPMENU */ + /*$this->menu[$r++] = array( + 'fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'top', // This is a Top menu entry + 'titre'=>'ModuleWebhookName', + 'prefix' => img_picto('', $this->picto, 'class="paddingright pictofixedwidth valignmiddle"'), + 'mainmenu'=>'webhook', + 'leftmenu'=>'', + 'url'=>'/webhook/webhookindex.php', + 'langs'=>'webhook@webhook', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000 + $r, + 'enabled'=>'$conf->webhook->enabled', // Define condition to show or hide menu entry. Use '$conf->webhook->enabled' if entry must be visible if module is enabled. + 'perms'=>'1', // Use 'perms'=>'$user->rights->webhook->webhook_target->read' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + );*/ + /* END MODULEBUILDER TOPMENU */ + /* BEGIN MODULEBUILDER LEFTMENU WEBHOOK_TARGET + $this->menu[$r++]=array( + 'fk_menu'=>'fk_mainmenu=webhook', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'left', // This is a Left menu entry + 'titre'=>'Webhook_target', + 'prefix' => img_picto('', $this->picto, 'class="paddingright pictofixedwidth valignmiddle"'), + 'mainmenu'=>'webhook', + 'leftmenu'=>'webhook_target', + 'url'=>'/webhook/webhookindex.php', + 'langs'=>'webhook@webhook', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000+$r, + 'enabled'=>'$conf->webhook->enabled', // Define condition to show or hide menu entry. Use '$conf->webhook->enabled' if entry must be visible if module is enabled. + 'perms'=>'$user->rights->webhook->webhook_target->read', // Use 'perms'=>'$user->rights->webhook->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + ); + $this->menu[$r++]=array( + 'fk_menu'=>'fk_mainmenu=webhook,fk_leftmenu=webhook_target', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'left', // This is a Left menu entry + 'titre'=>'List_Webhook_target', + 'mainmenu'=>'webhook', + 'leftmenu'=>'webhook_webhook_target_list', + 'url'=>'/webhook/webhook_target_list.php', + 'langs'=>'webhook@webhook', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000+$r, + 'enabled'=>'$conf->webhook->enabled', // Define condition to show or hide menu entry. Use '$conf->webhook->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms'=>'$user->rights->webhook->webhook_target->read', // Use 'perms'=>'$user->rights->webhook->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + ); + $this->menu[$r++]=array( + 'fk_menu'=>'fk_mainmenu=webhook,fk_leftmenu=webhook_target', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'left', // This is a Left menu entry + 'titre'=>'New_Webhook_target', + 'mainmenu'=>'webhook', + 'leftmenu'=>'webhook_webhook_target_new', + 'url'=>'/webhook/webhook_target_card.php?action=create', + 'langs'=>'webhook@webhook', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000+$r, + 'enabled'=>'$conf->webhook->enabled', // Define condition to show or hide menu entry. Use '$conf->webhook->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms'=>'$user->rights->webhook->webhook_target->write', // Use 'perms'=>'$user->rights->webhook->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + ); + */ + + /*$this->menu[$r++]=array( + // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'fk_menu'=>'fk_mainmenu=webhook', + // This is a Left menu entry + 'type'=>'left', + 'titre'=>'List Webhook_target', + 'mainmenu'=>'webhook', + 'leftmenu'=>'webhook_webhook_target', + 'url'=>'/webhook/webhook_target_list.php', + // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs'=>'webhook@webhook', + 'position'=>1100+$r, + // Define condition to show or hide menu entry. Use '$conf->webhook->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'enabled'=>'$conf->webhook->enabled', + // Use 'perms'=>'$user->rights->webhook->level1->level2' if you want your menu with a permission rules + 'perms'=>'1', + 'target'=>'', + // 0=Menu for internal users, 1=external users, 2=both + 'user'=>2, + ); + $this->menu[$r++]=array( + // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'fk_menu'=>'fk_mainmenu=webhook,fk_leftmenu=webhook_webhook_target', + // This is a Left menu entry + 'type'=>'left', + 'titre'=>'New Webhook_target', + 'mainmenu'=>'webhook', + 'leftmenu'=>'webhook_webhook_target', + 'url'=>'/webhook/webhook_target_card.php?action=create', + // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs'=>'webhook@webhook', + 'position'=>1100+$r, + // Define condition to show or hide menu entry. Use '$conf->webhook->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'enabled'=>'$conf->webhook->enabled', + // Use 'perms'=>'$user->rights->webhook->level1->level2' if you want your menu with a permission rules + 'perms'=>'1', + 'target'=>'', + // 0=Menu for internal users, 1=external users, 2=both + 'user'=>2 + );*/ + + /* END MODULEBUILDER LEFTMENU WEBHOOK_TARGET */ + // Exports profiles provided by this module + $r = 1; + /* BEGIN MODULEBUILDER EXPORT WEBHOOK_TARGET */ + /* + $langs->load("webhook@webhook"); + $this->export_code[$r]=$this->rights_class.'_'.$r; + $this->export_label[$r]='Webhook_targetLines'; // Translation key (used only if key ExportDataset_xxx_z not found) + $this->export_icon[$r]='webhook_target@webhook'; + // Define $this->export_fields_array, $this->export_TypeFields_array and $this->export_entities_array + $keyforclass = 'Webhook_target'; $keyforclassfile='/webhook/class/webhook_target.class.php'; $keyforelement='webhook_target@webhook'; + include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; + //$this->export_fields_array[$r]['t.fieldtoadd']='FieldToAdd'; $this->export_TypeFields_array[$r]['t.fieldtoadd']='Text'; + //unset($this->export_fields_array[$r]['t.fieldtoremove']); + //$keyforclass = 'Webhook_targetLine'; $keyforclassfile='/webhook/class/webhook_target.class.php'; $keyforelement='webhook_targetline@webhook'; $keyforalias='tl'; + //include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; + $keyforselect='webhook_target'; $keyforaliasextra='extra'; $keyforelement='webhook_target@webhook'; + include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; + //$keyforselect='webhook_targetline'; $keyforaliasextra='extraline'; $keyforelement='webhook_targetline@webhook'; + //include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; + //$this->export_dependencies_array[$r] = array('webhook_targetline'=>array('tl.rowid','tl.ref')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields) + //$this->export_special_array[$r] = array('t.field'=>'...'); + //$this->export_examplevalues_array[$r] = array('t.field'=>'Example'); + //$this->export_help_array[$r] = array('t.field'=>'FieldDescHelp'); + $this->export_sql_start[$r]='SELECT DISTINCT '; + $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'webhook_target as t'; + //$this->export_sql_end[$r] =' LEFT JOIN '.MAIN_DB_PREFIX.'webhook_target_line as tl ON tl.fk_webhook_target = t.rowid'; + $this->export_sql_end[$r] .=' WHERE 1 = 1'; + $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('webhook_target').')'; + $r++; */ + /* END MODULEBUILDER EXPORT WEBHOOK_TARGET */ + + // Imports profiles provided by this module + $r = 1; + /* BEGIN MODULEBUILDER IMPORT WEBHOOK_TARGET */ + /* + $langs->load("webhook@webhook"); + $this->import_code[$r]=$this->rights_class.'_'.$r; + $this->import_label[$r]='Webhook_targetLines'; // Translation key (used only if key ExportDataset_xxx_z not found) + $this->import_icon[$r]='webhook_target@webhook'; + $this->import_tables_array[$r] = array('t' => MAIN_DB_PREFIX.'webhook_webhook_target', 'extra' => MAIN_DB_PREFIX.'webhook_webhook_target_extrafields'); + $this->import_tables_creator_array[$r] = array('t' => 'fk_user_author'); // Fields to store import user id + $import_sample = array(); + $keyforclass = 'Webhook_target'; $keyforclassfile='/webhook/class/webhook_target.class.php'; $keyforelement='webhook_target@webhook'; + include DOL_DOCUMENT_ROOT.'/core/commonfieldsinimport.inc.php'; + $import_extrafield_sample = array(); + $keyforselect='webhook_target'; $keyforaliasextra='extra'; $keyforelement='webhook_target@webhook'; + include DOL_DOCUMENT_ROOT.'/core/extrafieldsinimport.inc.php'; + $this->import_fieldshidden_array[$r] = array('extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'webhook_webhook_target'); + $this->import_regex_array[$r] = array(); + $this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample); + $this->import_updatekeys_array[$r] = array('t.ref' => 'Ref'); + $this->import_convertvalue_array[$r] = array( + 't.ref' => array( + 'rule'=>'getrefifauto', + 'class'=>(empty($conf->global->WEBHOOK_WEBHOOK_TARGET_ADDON) ? 'mod_webhook_target_standard' : $conf->global->WEBHOOK_WEBHOOK_TARGET_ADDON), + 'path'=>"/core/modules/commande/".(empty($conf->global->WEBHOOK_WEBHOOK_TARGET_ADDON) ? 'mod_webhook_target_standard' : $conf->global->WEBHOOK_WEBHOOK_TARGET_ADDON).'.php' + 'classobject'=>'Webhook_target', + 'pathobject'=>'/webhook/class/webhook_target.class.php', + ), + 't.fk_soc' => array('rule' => 'fetchidfromref', 'file' => '/societe/class/societe.class.php', 'class' => 'Societe', 'method' => 'fetch', 'element' => 'ThirdParty'), + 't.fk_user_valid' => array('rule' => 'fetchidfromref', 'file' => '/user/class/user.class.php', 'class' => 'User', 'method' => 'fetch', 'element' => 'user'), + 't.fk_mode_reglement' => array('rule' => 'fetchidfromcodeorlabel', 'file' => '/compta/paiement/class/cpaiement.class.php', 'class' => 'Cpaiement', 'method' => 'fetch', 'element' => 'cpayment'), + ); + $r++; */ + /* END MODULEBUILDER IMPORT WEBHOOK_TARGET */ + } + + /** + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. + * It also creates data directories + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function init($options = '') + { + global $conf, $langs; + + $result = $this->_load_tables('/install/mysql/tables/', 'webhook'); + //$result = $this->_load_tables('/webhook/sql/'); + if ($result < 0) { + return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') + } + + // Create extrafields during init + //include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + //$extrafields = new ExtraFields($this->db); + //$result1=$extrafields->addExtraField('webhook_myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', 0, 0, '', '', 'webhook@webhook', '$conf->webhook->enabled'); + //$result2=$extrafields->addExtraField('webhook_myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', 0, 0, '', '', 'webhook@webhook', '$conf->webhook->enabled'); + //$result3=$extrafields->addExtraField('webhook_myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'webhook@webhook', '$conf->webhook->enabled'); + //$result4=$extrafields->addExtraField('webhook_myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'webhook@webhook', '$conf->webhook->enabled'); + //$result5=$extrafields->addExtraField('webhook_myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', 0, 0, '', '', 'webhook@webhook', '$conf->webhook->enabled'); + + // Permissions + $this->remove($options); + + $sql = array(); + + // Document templates + $moduledir = dol_sanitizeFileName('webhook'); + $myTmpObjects = array(); + $myTmpObjects['Webhook_target'] = array('includerefgeneration'=>0, 'includedocgeneration'=>0); + + foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { + if ($myTmpObjectKey == 'Webhook_target') { + continue; + } + if ($myTmpObjectArray['includerefgeneration']) { + $src = DOL_DOCUMENT_ROOT.'/install/doctemplates/'.$moduledir.'/template_webhook_targets.odt'; + $dirodt = DOL_DATA_ROOT.'/doctemplates/'.$moduledir; + $dest = $dirodt.'/template_webhook_targets.odt'; + + if (file_exists($src) && !file_exists($dest)) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + dol_mkdir($dirodt); + $result = dol_copy($src, $dest, 0, 0); + if ($result < 0) { + $langs->load("errors"); + $this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest); + return 0; + } + } + + $sql = array_merge($sql, array( + "DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = 'standard_".strtolower($myTmpObjectKey)."' AND type = '".$this->db->escape(strtolower($myTmpObjectKey))."' AND entity = ".((int) $conf->entity), + "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('standard_".strtolower($myTmpObjectKey)."', '".$this->db->escape(strtolower($myTmpObjectKey))."', ".((int) $conf->entity).")", + "DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = 'generic_".strtolower($myTmpObjectKey)."_odt' AND type = '".$this->db->escape(strtolower($myTmpObjectKey))."' AND entity = ".((int) $conf->entity), + "INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('generic_".strtolower($myTmpObjectKey)."_odt', '".$this->db->escape(strtolower($myTmpObjectKey))."', ".((int) $conf->entity).")" + )); + } + } + + return $this->_init($sql, $options); + } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function remove($options = '') + { + $sql = array(); + return $this->_remove($sql, $options); + } +} diff --git a/htdocs/core/tpl/objectline_create.tpl.php b/htdocs/core/tpl/objectline_create.tpl.php index a3a8e964ee1..2956e71178f 100644 --- a/htdocs/core/tpl/objectline_create.tpl.php +++ b/htdocs/core/tpl/objectline_create.tpl.php @@ -358,6 +358,10 @@ if ($nolinesbefore) { if (!empty($conf->service->enabled) && ($object->element == 'facturerec' || $object->element == 'invoice_supplier_rec')) { echo '

    '; echo $langs->trans('AutoFillDateFrom').' '; + if (!empty($conf->global->INVOICE_REC_DATE_TO_YES)) { + $line->date_start_fill = 1; + $line->date_end_fill = 1; + } echo $form->selectyesno('date_start_fill', $line->date_start_fill, 1); echo ' - '; echo $langs->trans('AutoFillDateTo').' '; diff --git a/htdocs/core/triggers/interface_99_modWebhook_WebhookTriggers.class.php b/htdocs/core/triggers/interface_99_modWebhook_WebhookTriggers.class.php new file mode 100644 index 00000000000..335024554fc --- /dev/null +++ b/htdocs/core/triggers/interface_99_modWebhook_WebhookTriggers.class.php @@ -0,0 +1,121 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file core/triggers/interface_99_modWebhook_WebhookTriggers.class.php + * \ingroup webhook + * \brief Example trigger. + * + * Put detailed description here. + * + * \remarks You can create other triggers by copying this one. + * - File name should be either: + * - interface_99_modWebhook_MyTrigger.class.php + * - interface_99_all_MyTrigger.class.php + * - The file must stay in core/triggers + * - The class name must be InterfaceMytrigger + */ + +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; +require_once DOL_DOCUMENT_ROOT.'/webhook/class/target.class.php'; + +/** + * Class of triggers for Webhook module + */ +class InterfaceWebhookTriggers extends DolibarrTriggers +{ + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + + $this->name = preg_replace('/^Interface/i', '', get_class($this)); + $this->family = "demo"; + $this->description = "Webhook triggers."; + // 'development', 'experimental', 'dolibarr' or version + $this->version = 'development'; + $this->picto = 'webhook@webhook'; + } + + /** + * Trigger name + * + * @return string Name of trigger file + */ + public function getName() + { + return $this->name; + } + + /** + * Trigger description + * + * @return string Description of trigger file + */ + public function getDesc() + { + return $this->description; + } + + + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file + * is inside directory core/triggers + * + * @param string $action Event action code + * @param CommonObject $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param Conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) + { + if (empty($conf->webhook) || empty($conf->webhook->enabled)) { + return 0; // If module is not enabled, we do nothing + } + require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + // Or you can execute some code here + $nbPosts = 0; + $errors = 0; + $static_object = new Target($this->db); + $target_url = $static_object->fetchAll(); + foreach ($target_url as $key => $tmpobject) { + $actionarray = explode(",", $tmpobject->trigger_codes); + if (is_array($actionarray) && in_array($action, $actionarray)) { + $jsonstr = '{"triggercode":'.json_encode($action).',"object":'.json_encode($object).'}'; + $response = getURLContent($tmpobject->url, 'POST', $jsonstr); + if (empty($response['curl_error_no']) && $response['http_code'] >= 200 && $response['http_code'] < 300) { + $nbPosts ++; + } else { + $errors ++; + dol_syslog("Failed to get url with httpcode=".(!empty($response['http_code']) ? $response['http_code'] : "")." curl_error_no=".(!empty($response['curl_error_no']) ? $response['curl_error_no'] : ""), LOG_DEBUG); + } + } + } + if (!empty($errors)) { + return $errors * -1; + } + return $nbPosts; + } +} diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index 5b033fc11f7..a3ce1738fac 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -1244,7 +1244,7 @@ class Expedition extends CommonObject $mouvS->origin = null; // get lot/serial $lotArray = null; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { $lotArray = $shipmentlinebatch->fetchAll($obj->expeditiondet_id); if (!is_array($lotArray)) { $error++; @@ -2781,7 +2781,7 @@ class ExpeditionLigne extends CommonObjectLine $this->db->begin(); // delete batch expedition line - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch"; $sql .= " WHERE fk_expeditiondet = ".((int) $this->id); diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index 1a2718e7d9a..a877b659141 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -2,7 +2,7 @@ /* Copyright (C) 2003 Rodolphe Quiedeville * Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin - * Copyright (C) 2015-2021 Alexandre Spangaro + * Copyright (C) 2015-2022 Alexandre Spangaro * Copyright (C) 2017 Ferran Marcet * Copyright (C) 2018 Frédéric France * @@ -138,7 +138,7 @@ $candelete = 0; if (!empty($user->rights->expensereport->supprimer)) { $candelete = 1; } -if ($object->statut == ExpenseReport::STATUS_DRAFT && $user->rights->expensereport->write && in_array($object->fk_user_author, $childids)) { +if ($object->statut == ExpenseReport::STATUS_DRAFT && !empty($user->rights->expensereport->write) && in_array($object->fk_user_author, $childids)) { $candelete = 1; } @@ -1467,6 +1467,8 @@ if ($action == 'create') { } // Public note + $note_public = GETPOSTISSET('note_public') ? GETPOST('note_public', 'restricthtml') : ''; + print ''; print ''.$langs->trans('NotePublic').''; print ''; @@ -1476,6 +1478,8 @@ if ($action == 'create') { print ''; // Private note + $note_private = GETPOSTISSET('note_private') ? GETPOST('note_private', 'restricthtml') : ''; + if (empty($user->socid)) { print ''; print ''.$langs->trans('NotePrivate').''; @@ -1624,6 +1628,8 @@ if ($action == 'create') { print dol_get_fiche_head($head, 'card', $langs->trans("ExpenseReport"), -1, 'trip'); + $formconfirm = ''; + // Clone confirmation if ($action == 'clone') { // Create an array for form @@ -1923,6 +1929,7 @@ if ($action == 'create') { // List of payments already done $nbcols = 3; + $nbrows = 0; if (!empty($conf->banque->enabled)) { $nbrows++; $nbcols++; diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index fd07a30f648..d03cb11a7e0 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -1433,7 +1433,7 @@ if ($action == 'create') { // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('np_desc', $objp->description, '', 164, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); + $doleditor = new DolEditor('np_desc', $objp->description, '', 164, 'dolibarr_details', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_DETAILS'), ROWS_2, '90%'); $doleditor->Create(); $objectline = new FichinterLigne($db); diff --git a/htdocs/fichinter/index.php b/htdocs/fichinter/index.php index 0f0fc0acc99..5e62cc5b0e4 100644 --- a/htdocs/fichinter/index.php +++ b/htdocs/fichinter/index.php @@ -89,7 +89,6 @@ $sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $i = 0; $total = 0; $totalinprocess = 0; @@ -97,38 +96,28 @@ if ($resql) { $vals = array(); $bool = false; // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not) - while ($i < $num) { - $row = $db->fetch_row($resql); - if ($row) { - //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) - { - $bool = (!empty($row[2]) ?true:false); - if (!isset($vals[$row[1].$bool])) { - $vals[$row[1].$bool] = 0; - } - $vals[$row[1].$bool] += $row[0]; - $totalinprocess += $row[0]; + if ($num>0) { + while ($row = $db->fetch_row($resql)) { + if (!isset($vals[$row[1]])) { + $vals[$row[1]] = 0; } + $vals[$row[1]] += $row[0]; + $totalinprocess += $row[0]; + $total += $row[0]; } - $i++; } $db->free($resql); - include DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; print '
    '; print ''; print ''."\n"; - $listofstatus = array(0, 1, 3); - $bool = false; + $listofstatus = array(Fichinter::STATUS_DRAFT, Fichinter::STATUS_VALIDATED); + if (!empty($conf->global->FICHINTER_CLASSIFY_BILLED)) $listofstatus[] = Fichinter::STATUS_BILLED; + foreach ($listofstatus as $status) { - $dataseries[] = array($fichinterstatic->LibStatut($status, $bool, 1), (isset($vals[$status.$bool]) ? (int) $vals[$status.$bool] : 0)); - if ($status == 3 && !$bool) { - $bool = true; - } else { - $bool = false; - } + $dataseries[] = array($fichinterstatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); if ($status == Fichinter::STATUS_DRAFT) { $colorseries[$status] = '-'.$badgeStatus0; @@ -139,10 +128,8 @@ if ($resql) { if ($status == Fichinter::STATUS_BILLED) { $colorseries[$status] = $badgeStatus4; } - if ($status == Fichinter::STATUS_CLOSED) { - $colorseries[$status] = $badgeStatus6; - } } + if ($conf->use_javascript_ajax) { print ''; } - $bool = false; foreach ($listofstatus as $status) { if (!$conf->use_javascript_ajax) { print ''; print ''; - print ''; print "\n"; - if ($status == 3 && !$bool) { - $bool = true; - } else { - $bool = false; - } } } //if ($totalinprocess != $total) diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index d113eadd8a7..690558fc9ad 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/productfournisseurprice.class.php'; /** @@ -256,9 +257,10 @@ class ProductFournisseur extends Product * @param string $desc_fourn Custom description for product_fourn_price * @param string $barcode Barcode * @param int $fk_barcode_type Barcode type + * @param array $options Extrafields of product fourn price * @return int <0 if KO, >=0 if OK */ - public function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = '') + public function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = '', $options = array()) { // phpcs:enable global $conf, $langs; @@ -407,7 +409,21 @@ class ProductFournisseur extends Product $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging); } $sql .= " WHERE rowid = ".((int) $this->product_fourn_price_id); - //print $sql;exit; + + if (!$error) { + if (!empty($options) && is_array($options)) { + $productfournisseurprice = new ProductFournisseurPrice($this->db); + $res = $productfournisseurprice->fetch($this->product_fourn_price_id); + if ($res > 0) { + foreach ($options as $key=>$value) { + $productfournisseurprice->array_options[$key] = $value; + } + $res = $productfournisseurprice->update($user); + if ($res < 0) $error++; + } + } + } + // TODO Add price_base_type and price_ttc dol_syslog(get_class($this).'::update_buyprice update knowing id of line = product_fourn_price_id = '.$this->product_fourn_price_id, LOG_DEBUG); @@ -493,6 +509,20 @@ class ProductFournisseur extends Product $error++; } + if (!$error) { + if (!empty($options) && is_array($options)) { + $productfournisseurprice = new ProductFournisseurPrice($this->db); + $res = $productfournisseurprice->fetch($this->product_fourn_price_id); + if ($res > 0) { + foreach ($options as $key=>$value) { + $productfournisseurprice->array_options[$key] = $value; + } + $res = $productfournisseurprice->update($user); + if ($res < 0) $error++; + } + } + } + if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) { // Add record into log table // $this->product_fourn_price_id must be set diff --git a/htdocs/holiday/document.php b/htdocs/holiday/document.php index 25646e78046..a4b9bcfcfdb 100644 --- a/htdocs/holiday/document.php +++ b/htdocs/holiday/document.php @@ -6,7 +6,7 @@ * Copyright (C) 2005 Simon TOSSER * Copyright (C) 2011-2012 Juanjo Menent * Copyright (C) 2013 Cédric Salvador - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2022 Frédéric France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -124,8 +124,6 @@ $title = $langs->trans("Leave").' - '.$langs->trans("Files"); llxHeader('', $title); -$edit = false; - if ($object->id) { $valideur = new User($db); $valideur->fetch($object->fk_validator); @@ -176,51 +174,25 @@ if ($object->id) { $starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning'; $endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon'; - if (!$edit) { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; - if (!$edit) { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; // Nb days consumed print ''; @@ -247,17 +219,10 @@ if ($object->id) { } // Description - if (!$edit) { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; print ''; print ''; @@ -274,8 +239,7 @@ if ($object->id) { print '
    '.$langs->trans("Statistics").' - '.$langs->trans("Interventions").'
    '; @@ -159,21 +146,15 @@ if ($resql) { print '
    '.$fichinterstatic->LibStatut($status, $bool, 0).''.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' '; - print $fichinterstatic->LibStatut($status, $bool, 3); + print ''.(isset($vals[$status]) ? $vals[$status] : 0).' '; + print $fichinterstatic->LibStatut($status, 3); print ''; print '
    '; - print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); - print ''.dol_print_date($object->date_debut, 'day'); - print '     '; - print ''.$langs->trans($listhalfday[$starthalfday]).''; - print '
    '; - print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); - print ''; - print $form->selectDate($object->date_debut, 'date_debut_'); - print '     '; - print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday') ?GETPOST('starthalfday') : $starthalfday)); - print '
    '; + print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday")); + print ''.dol_print_date($object->date_debut, 'day'); + print '     '; + print ''.$langs->trans($listhalfday[$starthalfday]).''; + print '
    '; - print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); - print ''.dol_print_date($object->date_fin, 'day'); - print '     '; - print ''.$langs->trans($listhalfday[$endhalfday]).''; - print '
    '; - print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); - print ''; - print $form->selectDate($object->date_fin, 'date_fin_'); - print '     '; - print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday') ?GETPOST('endhalfday') : $endhalfday)); - print '
    '; + print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday")); + print ''.dol_print_date($object->date_fin, 'day'); + print '     '; + print ''.$langs->trans($listhalfday[$endhalfday]).''; + print '
    '.$langs->trans('DescCP').''.nl2br($object->description).'
    '.$langs->trans('DescCP').'
    '.$langs->trans('DescCP').''.nl2br($object->description).'
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize, 1, 1).'
    '."\n"; print ''; - if (! empty($object->fk_user_create)) - { + if (! empty($object->fk_user_create)) { $userCreate=new User($db); $userCreate->fetch($object->fk_user_create); print ''; @@ -284,19 +248,10 @@ if ($object->id) { print ''; } - if (!$edit) { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; print ''; print ''; diff --git a/htdocs/hrm/admin/admin_hrm.php b/htdocs/hrm/admin/admin_hrm.php index 810c0da870d..6763fb43f8e 100644 --- a/htdocs/hrm/admin/admin_hrm.php +++ b/htdocs/hrm/admin/admin_hrm.php @@ -109,7 +109,7 @@ foreach ($list as $key) { // Value print ''; } diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index 52784558b45..38a540ca042 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -167,6 +167,7 @@ if (empty($array_match_file_to_database)) { } } + /* * Actions */ @@ -742,8 +743,8 @@ if ($step == 3 && $datatoimport) { if ($step == 4 && $datatoimport) { //var_dump($_SESSION["dol_array_match_file_to_database_select"]); $serialized_array_match_file_to_database = isset($_SESSION["dol_array_match_file_to_database_select"]) ? $_SESSION["dol_array_match_file_to_database_select"] : ''; - $array_match_file_to_database = array(); $fieldsarray = explode(',', $serialized_array_match_file_to_database); + $array_match_file_to_database = array(); // Same than $fieldsarray but with mapped value only (col1 => 's.fielda', col2 => 's.fieldb'...) foreach ($fieldsarray as $elem) { $tabelem = explode('=', $elem, 2); $key = $tabelem[0]; @@ -752,6 +753,11 @@ if ($step == 4 && $datatoimport) { $array_match_file_to_database[$key] = $val; } } + + //var_dump($serialized_array_match_file_to_database); + //var_dump($fieldsarray); + //var_dump($array_match_file_to_database); + $model = $format; $list = $objmodelimport->liste_modeles($db); @@ -853,20 +859,15 @@ if ($step == 4 && $datatoimport) { } // We found the key of targets that is at position pos $array_match_file_to_database[$pos] = $key; - if ($serialized_array_match_file_to_database) { - $serialized_array_match_file_to_database .= ','; - } - $serialized_array_match_file_to_database .= ($pos.'='.$key); break; } } $pos++; } - // Save the match array in session. We now will use the array in session. - $_SESSION["dol_array_match_file_to_database_select"] = $serialized_array_match_file_to_database; } $array_match_database_to_file = array_flip($array_match_file_to_database); - + //var_dump($array_match_database_to_file); + //var_dump($_SESSION["dol_array_match_file_to_database_select"]); $fieldstarget_tmp = array(); $arraykeysfieldtarget = array_keys($fieldstarget); @@ -1088,8 +1089,8 @@ if ($step == 4 && $datatoimport) { $optionsall = array(); foreach ($fieldstarget as $code => $line) { //var_dump($line); - $labeltoshow = $langs->trans($line["label"]); - $optionsall[$code] = array('label'=>$labeltoshow, 'required'=>(empty($line["required"]) ? 0 : 1), 'position'=>!empty($line['position']) ? $line['position'] : 0); + $labeltoshow = $langs->transnoentities($line["label"]); + $optionsall[$code] = array('labelkey'=>$line['label'], 'label'=>$labeltoshow, 'required'=>(empty($line["required"]) ? 0 : 1), 'position'=>!empty($line['position']) ? $line['position'] : 0); // TODO Get type from an new array into module descriptor. //$picto = 'email'; $picto = ''; @@ -1106,13 +1107,19 @@ if ($step == 4 && $datatoimport) { //var_dump($fieldstarget); //var_dump($optionsall); //exit; - /* - var_dump($_SESSION['dol_array_match_file_to_database']); - var_dump($_SESSION['dol_array_match_file_to_database_select']); - var_dump($optionsall); - var_dump($fieldssource); - var_dump($fieldstarget); - */ + + //var_dump($_SESSION['dol_array_match_file_to_database']); + //var_dump($_SESSION['dol_array_match_file_to_database_select']); + //exit; + //var_dump($optionsall); + //var_dump($fieldssource); + //var_dump($fieldstarget); + + $modetoautofillmapping = 'session'; // Use setup in session + if ($initialloadofstep4) { + $modetoautofillmapping = 'guess'; + } + //var_dump($modetoautofillmapping); print '
    '.$langs->trans('ReviewedByCP').''.$valideur->getNomUrl(-1).'
    '.$langs->trans('ReviewedByCP').''; - print $form->select_dolusers($object->fk_user, "valideur", 1, ($user->admin ? '' : array($user->id))); // By default, hierarchical parent - print '
    '.$langs->trans('ReviewedByCP').''.$valideur->getNomUrl(-1).'
    '.$langs->trans('DateCreation').''; - print ''; + print ''; print '
    '; foreach ($fieldssource as $code => $line) { // $fieldssource is an array code=column num, line=content on first line for column in source file. @@ -1132,23 +1139,19 @@ if ($step == 4 && $datatoimport) { print ''; print '"; + $selectforline .= ''; + $selectforline .= ajax_combobox('selectorderimport_'.($i+1)); + + print $selectforline; + + print ''; print ''; // Value print ''; print ''; @@ -181,7 +181,7 @@ foreach ($list_DES as $key) { print ''; // Value print ''; print ''; diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 26c2a959a13..95ed076f347 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -2252,13 +2252,21 @@ TemplateforBusinessCards=Template for a business card in different size InventorySetup= Inventory Setup ExportUseLowMemoryMode=Use a low memory mode ExportUseLowMemoryModeHelp=Use the low memory mode to execute the exec of the dump (compression is done through a pipe instead of into the PHP memory). This method does not allow to check that file is completed and error message can't be reported if it fails. -ShowQuickAddLink=Show a button to quickly add an object, in top right menu + +ModuleWebhookName = Webhook +ModuleWebhookDesc = Interface to catch dolibarr triggers and send it to an URL +WebhookSetup = Webhook setup +Settings = Settings +WebhookSetupPage = Webhook setup page +ShowQuickAddLink=Show a button to quickly add an element in top right menu + HashForPing=Hash used for ping ReadOnlyMode=Is instance in "Read Only" mode DEBUGBAR_USE_LOG_FILE=Use the dolibarr.log file to trap Logs UsingLogFileShowAllRecordOfSubrequestButIsSlower=Use the dolibarr.log file to trap Logs instead of live memory catching. It allows to catch all logs instead of only log of current process (so including the one of ajax subrequests pages) but will make your instance very very slow. Not recommended. FixedOrPercent=Fixed (use keyword 'fixed') or percent (use keyword 'percent') DefaultOpportunityStatus=Default opportunity status (first status when lead is created) + IconAndText=Icon and text TextOnly=Text only IconOnlyAllTextsOnHover=Icon only - All texts appears under icon on mouse hover menu bar @@ -2268,4 +2276,4 @@ INVOICE_ADD_ZATCA_QR_CODE=Show the ZATCA QR code on invoices INVOICE_ADD_ZATCA_QR_CODEMore=Some Arabic countries need this QR Code on their invoices INVOICE_ADD_SWISS_QR_CODE=Show the swiss QR-Bill code on invoices UrlSocialNetworksDesc=Url link of social network. Use {socialid} for the variable part that contains the social network ID. -IfThisCategoryIsChildOfAnother=If this category is a child of another one \ No newline at end of file +IfThisCategoryIsChildOfAnother=If this category is a child of another one diff --git a/htdocs/langs/en_US/categories.lang b/htdocs/langs/en_US/categories.lang index a2d05767cae..62c2752ff9f 100644 --- a/htdocs/langs/en_US/categories.lang +++ b/htdocs/langs/en_US/categories.lang @@ -95,6 +95,7 @@ ShowCategory=Show tag/category ByDefaultInList=By default in list ChooseCategory=Choose category StocksCategoriesArea=Warehouse Categories +TicketsCategoriesArea=Tickets Categories ActionCommCategoriesArea=Event Categories WebsitePagesCategoriesArea=Page-Container Categories KnowledgemanagementsCategoriesArea=KM article Categories diff --git a/htdocs/langs/en_US/exports.lang b/htdocs/langs/en_US/exports.lang index f06acd49f41..c4c629c9a87 100644 --- a/htdocs/langs/en_US/exports.lang +++ b/htdocs/langs/en_US/exports.lang @@ -141,4 +141,5 @@ WarningFirstImportedLine=The first line(s) will not be imported with the current NotUsedFields=Fields of database not used SelectImportFieldsSource = Choose the source file fields you want to import and their target field in database by choosing the fields in each select boxes, or select a predefined import profile: MandatoryTargetFieldsNotMapped=Some mandatory target fields are not mapped -AllTargetMandatoryFieldsAreMapped=All target fields that need a mandatory value are mapped \ No newline at end of file +AllTargetMandatoryFieldsAreMapped=All target fields that need a mandatory value are mapped +ResultOfSimulationNoError=Result of simulation: No error \ No newline at end of file diff --git a/htdocs/mrp/mo_production.php b/htdocs/mrp/mo_production.php index 16249087403..f6aba7f2597 100644 --- a/htdocs/mrp/mo_production.php +++ b/htdocs/mrp/mo_production.php @@ -747,7 +747,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } print ''; - if ($conf->stock->enabled) { + if (isModEnabled('stock')) { // Available print ''; } // Lot - serial - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; - if ($conf->stock->enabled) { + if (isModEnabled('stock')) { print ''; } // Lot - serial - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; } // Action @@ -909,7 +909,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; // Stock - if ($conf->stock->enabled) { + if (isModEnabled('stock')) { print ''; } // Lot - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; } // Action delete line @@ -965,12 +965,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; // Stock - if ($conf->stock->enabled) { + if (isModEnabled('stock')) { print ''; } // Lot Batch - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; // Stock - if ($conf->stock->enabled) { + if (isModEnabled('stock')) { print ''; } // Lot / Batch - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; // Lot - serial - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; } // Action @@ -1236,7 +1236,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; // Lot } @@ -1277,7 +1277,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } print ''; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; // Batch number managment - if (!empty($conf->productbatch->enabled)) { + if (isModEnabled('productbatch')) { if ($object->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) { print '"; @@ -2146,7 +2146,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { print '"; diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index 96ce57c5bbe..6e7db72c393 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -285,34 +285,8 @@ if (empty($reshook)) { if (GETPOSTISSET('ref_fourn_price_id')) { $object->fetch_product_fournisseur_price(GETPOST('ref_fourn_price_id', 'int')); } - $extralabels = $extrafields->fetch_name_optionals_label("product_fournisseur_price"); $extrafield_values = $extrafields->getOptionalsFromPost("product_fournisseur_price"); - if (!empty($extrafield_values)) { - $resql = $db->query("SELECT fk_object FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields WHERE fk_object = ".((int) $object->product_fourn_price_id)); - // Insert a new extrafields row, if none exists - if ($db->num_rows($resql) != 1) { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields (fk_object, "; - foreach ($extrafield_values as $key => $value) { - $sql .= str_replace('options_', '', $key).', '; - } - $sql = substr($sql, 0, strlen($sql) - 2).") VALUES (".((int) $object->product_fourn_price_id).", "; - foreach ($extrafield_values as $key => $value) { - $sql .= "'".$db->escape($value)."', "; - } - $sql = substr($sql, 0, strlen($sql) - 2).')'; - } else { - // update the existing one - $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields SET "; - foreach ($extrafield_values as $key => $value) { - $sql .= str_replace('options_', '', $key)." = '".$db->escape($value)."', "; - } - $sql = substr($sql, 0, strlen($sql) - 2).' WHERE fk_object = '.((int) $object->product_fourn_price_id); - } - - // Execute the sql command from above - $db->query($sql); - } $newprice = price2num(GETPOST("price", "alpha")); @@ -330,9 +304,9 @@ if (empty($reshook)) { $multicurrency_price = price2num(GETPOST("multicurrency_price", 'alpha')); $multicurrency_code = GETPOST("multicurrency_code", 'alpha'); - $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', $multicurrency_price, GETPOST("multicurrency_price_base_type"), $multicurrency_tx, $multicurrency_code, $supplier_description, $barcode, $fk_barcode_type); + $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', $multicurrency_price, GETPOST("multicurrency_price_base_type"), $multicurrency_tx, $multicurrency_code, $supplier_description, $barcode, $fk_barcode_type, $extrafield_values); } else { - $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type); + $ret = $object->update_buyprice($quantity, $newprice, $user, GETPOST("price_base_type"), $supplier, GETPOST("oselDispo"), $ref_fourn, $tva_tx, GETPOST("charges"), $remise_percent, 0, $npr, $delivery_time_days, $supplier_reputation, array(), '', 0, 'HT', 1, '', $supplier_description, $barcode, $fk_barcode_type, $extrafield_values); } if ($ret < 0) { $error++; @@ -806,7 +780,7 @@ END; print ''; print ''; diff --git a/htdocs/product/inventory/class/inventory.class.php b/htdocs/product/inventory/class/inventory.class.php index 80823c7ba5a..e0e2f9c59da 100644 --- a/htdocs/product/inventory/class/inventory.class.php +++ b/htdocs/product/inventory/class/inventory.class.php @@ -308,7 +308,7 @@ class Inventory extends CommonObject $inventoryline->batch = $obj->batch; $inventoryline->datec = dol_now(); - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { $inventoryline->qty_stock = ($obj->batch ? $obj->qty : $obj->reel); // If there is batch detail, we take qty for batch, else global qty } else { $inventoryline->qty_stock = $obj->reel; diff --git a/htdocs/product/stock/massstockmove.php b/htdocs/product/stock/massstockmove.php index e0e191fc5d1..85848942fbe 100644 --- a/htdocs/product/stock/massstockmove.php +++ b/htdocs/product/stock/massstockmove.php @@ -569,7 +569,7 @@ print ''; print getTitleFieldOfList($langs->trans('WarehouseSource'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); print getTitleFieldOfList($langs->trans('WarehouseTarget'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); print getTitleFieldOfList($langs->trans('ProductRef'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); -if ($conf->productbatch->enabled) { +if (isModEnabled('productbatch')) { print getTitleFieldOfList($langs->trans('Batch'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); } print getTitleFieldOfList($langs->trans('Qty'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'center tagtd maxwidthonsmartphone '); @@ -601,7 +601,7 @@ print img_picto($langs->trans("Product"), 'product', 'class="paddingright"'); print $form->select_produits($id_product, 'productid', $filtertype, $limit, 0, -1, 2, '', 1, array(), 0, '1', 0, 'minwidth200imp maxwidth300', 1, '', null, 1); print ''; // Batch number -if ($conf->productbatch->enabled) { +if (isModEnabled('productbatch')) { print ''; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index 3054e6785bd..6af0e105b47 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -631,7 +631,7 @@ if ($id > 0 || $ref) { print ''; } - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_card.php b/htdocs/product/stock/stocktransfer/stocktransfer_card.php index b88df4e1da1..b009ace7275 100644 --- a/htdocs/product/stock/stocktransfer/stocktransfer_card.php +++ b/htdocs/product/stock/stocktransfer/stocktransfer_card.php @@ -749,7 +749,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print getTitleFieldOfList($langs->trans('ProductRef'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print getTitleFieldOfList($langs->trans('Batch'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); } print getTitleFieldOfList($langs->trans('WarehouseSource'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); @@ -789,7 +789,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action === 'editline' && $line->id == $lineid) $form->select_produits($line->fk_product, 'fk_product', $filtertype, $limit, 0, -1, 2, '', 0, array(), 0, 0, 0, 'minwidth200imp maxwidth300', 1); else print $productstatic->getNomUrl(1).' - '.$productstatic->label; print ''; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; // Batch number - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { print ''; diff --git a/htdocs/product/traduction.php b/htdocs/product/traduction.php index 65906a0cc0f..7f91e9c73a8 100644 --- a/htdocs/product/traduction.php +++ b/htdocs/product/traduction.php @@ -264,12 +264,12 @@ if ($action == 'edit') { print '
    => '; - $modetoautofillmapping = 'session'; // Use setup in session - if ($initialloadofstep4) { - $modetoautofillmapping = 'guess'; - } //var_dump($_SESSION['dol_array_match_file_to_database_select']); - //var_dump($modetoautofillmapping); //var_dump($_SESSION['dol_array_match_file_to_database']); - //var_dump($modetoautofillmapping); - print ''; if (!empty($line["imported"])) { - print ''; + $selectforline .= ''; } else { - print ''; + $selectforline .= ''; } $j = 0; + $codeselectedarray = array(); foreach ($optionsall as $tmpcode => $tmpval) { // Loop on each entry to add into each combo list. $label = ''; if (!empty($tmpval['picto'])) { @@ -1158,16 +1161,11 @@ if ($step == 4 && $datatoimport) { $label .= $tmpval['label']; $label .= $tmpval['required'] ? '*' : ''; - // If we must guess how to fill the preselected value, and we can't because input value are not string - if ($modetoautofillmapping == 'guess' && $j == 0 && is_numeric($tmpval)) { - $modetoautofillmapping = 'orderoftargets'; - } - - print ''; $filecolumn = ($i + 1); @@ -1317,18 +1325,21 @@ if ($step == 4 && $datatoimport) { print ' console.log("Remove the disabled flag everywhere");'."\n"; print ' $("select.targetselectchange").not($( this )).find(\'option\').prop("disabled", false);'."\n"; // Enable all options print ' arrayofselectedvalues = [];'."\n"; + print ' $("select.targetselectchange").each(function(){'."\n"; print ' id = $(this).attr(\'id\')'."\n"; print ' value = $(this).val()'."\n"; - //print ' console.log("a selected value has been found for component "+id+" = "+value);'."\n"; + print ' console.log("a selected value has been found for component "+id+" = "+value);'."\n"; print ' arrayofselectedvalues.push(value);'."\n"; print ' });'."\n"; - print ' console.log("List of all selected values");'."\n"; + + print ' console.log("List of all selected values arrayofselectedvalues");'."\n"; print ' console.log(arrayofselectedvalues);'."\n"; print ' console.log("Set the option to disabled for every entry that is currently selected somewhere else (so into arrayofselectedvalues)");'."\n"; - print ' $.each( arrayofselectedvalues, function( key, value ) {'."\n"; // Loop on each selected value + + print ' $.each(arrayofselectedvalues, function(key, value) {'."\n"; // Loop on each selected value print ' if (value != -1) {'."\n"; - //print ' console.log("Process key="+key+" value="+value+" to disable.");'."\n"; + print ' console.log("Process key="+key+" value="+value+" to disable.");'."\n"; print ' $("select.targetselectchange").find(\'option[value="\'+value+\'"]:not(:selected)\').prop("disabled", true);'."\n"; // Set to disabled except if currently selected print ' }'."\n"; print ' });'."\n"; @@ -1338,12 +1349,13 @@ if ($step == 4 && $datatoimport) { print 'function saveSelection() {'."\n"; //print ' console.log(arrayofselectedvalues);'."\n"; print ' arrayselectedfields = [];'."\n"; - print ' arrayselectedfields.push("0");'."\n"; + print ' arrayselectedfields.push(0);'."\n"; + print ' $.each( arrayofselectedvalues, function( key, value ) {'."\n"; print ' if (value != -1) {'."\n"; - print ' arrayselectedfields.push(value);'."\n"; + print ' arrayselectedfields.push(value);'."\n"; print ' } else {'."\n"; - print ' arrayselectedfields.push(0);'."\n"; + print ' arrayselectedfields.push(0);'."\n"; print ' }'."\n"; print ' });'."\n"; @@ -1353,12 +1365,14 @@ if ($step == 4 && $datatoimport) { print " url: '".dol_escape_js($_SERVER["PHP_SELF"])."?action=saveselectorder&token=".newToken()."',\n"; print " data: 'selectorder='+arrayselectedfields.toString(),\n"; print " success: function(){\n"; - print " console.log('Select order saved');\n"; + print " console.log('The selected fields have been saved into '+arrayselectedfields.toString());\n"; print " },\n"; print ' });'."\n"; // Now we loop on all target fields that are mandatory to show if they are not mapped yet. + print ' console.log("arrayselectedfields");'; print ' console.log(arrayselectedfields);'; + print ' console.log("arrayoftargetmandatoryfields");'; print ' console.log(arrayoftargetmandatoryfields);'; print " listtoshow = '';"; print " nbelement = arrayoftargetmandatoryfields.length @@ -1886,16 +1900,17 @@ if ($step == 5 && $datatoimport) { // Show OK if (!count($arrayoferrors) && !count($arrayofwarnings)) { - print '
    '.img_picto($langs->trans("OK"), 'tick').' '.$langs->trans("NoError").'


    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '.$langs->trans("ResultOfSimulationNoError").'
    '; print $langs->trans("NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'
    '; print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'
    '; print '
    '; print '
    '; } else { print '
    '; - print '
    '; - print $langs->trans("NbOfLinesOK", $nbok).'
    '; + print '
    '; + print $langs->trans("NbOfLinesOK", $nbok).'...
    '; print '
    '; print '
    '; } @@ -2281,10 +2296,10 @@ if ($step == 6 && $datatoimport) { // Show result print '
    '; - print '
    '; + print '
    '; print $langs->trans("NbOfLinesImported", $nbok).'
    '; print $langs->trans("NbInsert", empty($obj->nbinsert) ? 0 : $obj->nbinsert).'
    '; - print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'

    '; + print $langs->trans("NbUpdate", empty($obj->nbupdate) ? 0 : $obj->nbupdate).'
    '; print '
    '; print '
    '; print $langs->trans("FileWasImported", $importid).'
    '; diff --git a/htdocs/install/mysql/migration/15.0.0-16.0.0.sql b/htdocs/install/mysql/migration/15.0.0-16.0.0.sql index 2d8b0a8cc17..b57cab5b4eb 100644 --- a/htdocs/install/mysql/migration/15.0.0-16.0.0.sql +++ b/htdocs/install/mysql/migration/15.0.0-16.0.0.sql @@ -181,48 +181,48 @@ ALTER TABLE llx_stock_mouvement_extrafields ADD INDEX idx_stock_mouvement_extraf CREATE TABLE llx_facture_fourn_rec ( rowid integer AUTO_INCREMENT PRIMARY KEY, - titre varchar(200) NOT NULL, - ref_supplier varchar(180) NOT NULL, - entity integer DEFAULT 1 NOT NULL, - fk_soc integer NOT NULL, + titre varchar(200) NOT NULL, + ref_supplier varchar(180) NOT NULL, + entity integer DEFAULT 1 NOT NULL, + fk_soc integer NOT NULL, datec datetime, - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - suspended integer DEFAULT 0, - libelle varchar(255), - amount double(24, 8) DEFAULT 0 NOT NULL, - remise real DEFAULT 0, - vat_src_code varchar(10) DEFAULT '', - localtax1 double(24,8) DEFAULT 0, - localtax2 double(24,8) DEFAULT 0, - total_ht double(24,8) DEFAULT 0, - total_tva double(24,8) DEFAULT 0, - total_ttc double(24,8) DEFAULT 0, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + suspended integer DEFAULT 0, + libelle varchar(255), + amount double(24,8) DEFAULT 0 NOT NULL, + remise real DEFAULT 0, + vat_src_code varchar(10) DEFAULT '', + localtax1 double(24,8) DEFAULT 0, + localtax2 double(24,8) DEFAULT 0, + total_ht double(24,8) DEFAULT 0, + total_tva double(24,8) DEFAULT 0, + total_ttc double(24,8) DEFAULT 0, fk_user_author integer, fk_user_modif integer, fk_projet integer, fk_account integer, - fk_cond_reglement integer, - fk_mode_reglement integer, + fk_cond_reglement integer, + fk_mode_reglement integer, date_lim_reglement date, note_private text, note_public text, modelpdf varchar(255), fk_multicurrency integer, multicurrency_code varchar(3), - multicurrency_tx double(24,8) DEFAULT 1, - multicurrency_total_ht double(24,8) DEFAULT 0, - multicurrency_total_tva double(24,8) DEFAULT 0, - multicurrency_total_ttc double(24,8) DEFAULT 0, - usenewprice integer DEFAULT 0, + multicurrency_tx double(24,8) DEFAULT 1, + multicurrency_total_ht double(24,8) DEFAULT 0, + multicurrency_total_tva double(24,8) DEFAULT 0, + multicurrency_total_ttc double(24,8) DEFAULT 0, + usenewprice integer DEFAULT 0, frequency integer, - unit_frequency varchar(2) DEFAULT 'm', - date_when datetime DEFAULT NULL, - date_last_gen datetime DEFAULT NULL, - nb_gen_done integer DEFAULT NULL, - nb_gen_max integer DEFAULT NULL, - auto_validate integer DEFAULT 0, - generate_pdf integer DEFAULT 1 -)ENGINE=innodb; + unit_frequency varchar(2) DEFAULT 'm', + date_when datetime DEFAULT NULL, + date_last_gen datetime DEFAULT NULL, + nb_gen_done integer DEFAULT NULL, + nb_gen_max integer DEFAULT NULL, + auto_validate integer DEFAULT 0, + generate_pdf integer DEFAULT 1 +) ENGINE=innodb; ALTER TABLE llx_facture_fourn_rec ADD UNIQUE INDEX uk_facture_fourn_rec_ref (titre, entity); ALTER TABLE llx_facture_fourn_rec ADD UNIQUE INDEX uk_facture_fourn_rec_ref_supplier (ref_supplier, fk_soc, entity); @@ -251,23 +251,23 @@ CREATE TABLE llx_facture_fourn_det_rec fk_parent_line integer NULL, fk_product integer NULL, ref varchar(50), - label varchar(255) DEFAULT NULL, + label varchar(255) DEFAULT NULL, description text, pu_ht double(24,8), pu_ttc double(24,8), qty real, - remise_percent real DEFAULT 0, - fk_remise_except integer NULL, - vat_src_code varchar(10) DEFAULT '', + remise_percent real DEFAULT 0, + fk_remise_except integer NULL, + vat_src_code varchar(10) DEFAULT '', tva_tx double(7,4), - localtax1_tx double(7,4) DEFAULT 0, - localtax1_type varchar(10) NULL, - localtax2_tx double(7,4) DEFAULT 0, - localtax2_type varchar(10) NULL, + localtax1_tx double(7,4) DEFAULT 0, + localtax1_type varchar(10) NULL, + localtax2_tx double(7,4) DEFAULT 0, + localtax2_type varchar(10) NULL, total_ht double(24,8), total_tva double(24,8), - total_localtax1 double(24,8) DEFAULT 0, - total_localtax2 double(24,8) DEFAULT 0, + total_localtax1 double(24,8) DEFAULT 0, + total_localtax2 double(24,8) DEFAULT 0, total_ttc double(24,8), product_type integer DEFAULT 0, date_start integer DEFAULT NULL, @@ -285,17 +285,20 @@ CREATE TABLE llx_facture_fourn_det_rec multicurrency_total_ht double(24,8) DEFAULT 0, multicurrency_total_tva double(24,8) DEFAULT 0, multicurrency_total_ttc double(24,8) DEFAULT 0 -)ENGINE=innodb; +) ENGINE=innodb; + ALTER TABLE llx_facture_fourn_det_rec ADD CONSTRAINT fk_facture_fourn_det_rec_fk_unit FOREIGN KEY (fk_unit) REFERENCES llx_c_units (rowid); + CREATE TABLE llx_facture_fourn_det_rec_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, -- object id - import_key varchar(14) -- import key -)ENGINE=innodb; + import_key varchar(14) -- import key +) ENGINE=innodb; + ALTER TABLE llx_facture_fourn_det_rec_extrafields ADD INDEX idx_facture_fourn_det_rec_extrafields (fk_object); @@ -314,7 +317,8 @@ ALTER TABLE llx_emailcollector_emailcollector ADD COLUMN position INTEGER NOT NU ALTER TABLE llx_advtargetemailing RENAME TO llx_mailing_advtarget; -ALTER TABLE llx_mailing ADD UNIQUE INDEX uk_mailing(titre, entity); +ALTER TABLE llx_mailing ADD UNIQUE INDEX uk_mailing (titre, entity); + create table llx_inventory_extrafields ( @@ -324,6 +328,7 @@ create table llx_inventory_extrafields import_key varchar(14) -- import key ) ENGINE=innodb; + ALTER TABLE llx_inventory_extrafields ADD INDEX idx_inventory_extrafields (fk_object); ALTER TABLE llx_reception MODIFY COLUMN ref_supplier varchar(128); @@ -364,136 +369,149 @@ ALTER TABLE llx_asset ADD COLUMN model_pdf varchar(255) AFTER import_key; DROP TABLE llx_asset_type; + CREATE TABLE llx_c_asset_disposal_type ( - rowid integer AUTO_INCREMENT PRIMARY KEY, - entity integer NOT NULL DEFAULT 1, - code varchar(16) NOT NULL, - label varchar(50) NOT NULL, - active integer DEFAULT 1 NOT NULL -)ENGINE=innodb; + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer NOT NULL DEFAULT 1, + code varchar(16) NOT NULL, + label varchar(50) NOT NULL, + active integer NOT NULL DEFAULT 1 +) ENGINE=innodb; -CREATE TABLE llx_asset_accountancy_codes_economic( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + +CREATE TABLE llx_asset_accountancy_codes_economic +( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_asset integer, + fk_asset_model integer, + + asset varchar(32), + depreciation_asset varchar(32), + depreciation_expense varchar(32), + value_asset_sold varchar(32), + receivable_on_assignment varchar(32), + proceeds_from_sales varchar(32), + vat_collected varchar(32), + vat_deductible varchar(32), + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user_modif integer +) ENGINE=innodb; + + +CREATE TABLE llx_asset_accountancy_codes_fiscal +( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, fk_asset integer, fk_asset_model integer, - asset varchar(32), - depreciation_asset varchar(32), - depreciation_expense varchar(32), - value_asset_sold varchar(32), - receivable_on_assignment varchar(32), - proceeds_from_sales varchar(32), - vat_collected varchar(32), - vat_deductible varchar(32), - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - fk_user_modif integer -) ENGINE=innodb; - -CREATE TABLE llx_asset_accountancy_codes_fiscal( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - fk_asset integer, - fk_asset_model integer, - - accelerated_depreciation varchar(32), + accelerated_depreciation varchar(32), endowment_accelerated_depreciation varchar(32), provision_accelerated_depreciation varchar(32), - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - fk_user_modif integer + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user_modif integer ) ENGINE=innodb; -CREATE TABLE llx_asset_depreciation_options_economic( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - fk_asset integer, - fk_asset_model integer, - depreciation_type smallint DEFAULT 0 NOT NULL, -- 0:linear, 1:degressive, 2:exceptional - accelerated_depreciation_option integer, -- activate accelerated depreciation mode (fiscal) +CREATE TABLE llx_asset_depreciation_options_economic +( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_asset integer, + fk_asset_model integer, - degressive_coefficient double(24,8), - duration smallint NOT NULL, - duration_type smallint DEFAULT 0 NOT NULL, -- 0:annual, 1:monthly, 2:daily + depreciation_type smallint DEFAULT 0 NOT NULL, -- 0:linear, 1:degressive, 2:exceptional + accelerated_depreciation_option integer, -- activate accelerated depreciation mode (fiscal) - amount_base_depreciation_ht double(24,8), - amount_base_deductible_ht double(24,8), - total_amount_last_depreciation_ht double(24,8), + degressive_coefficient double(24,8), + duration smallint NOT NULL, + duration_type smallint DEFAULT 0 NOT NULL, -- 0:annual, 1:monthly, 2:daily - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - fk_user_modif integer + amount_base_depreciation_ht double(24,8), + amount_base_deductible_ht double(24,8), + total_amount_last_depreciation_ht double(24,8), + + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user_modif integer ) ENGINE=innodb; -CREATE TABLE llx_asset_depreciation_options_fiscal( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - fk_asset integer, - fk_asset_model integer, - depreciation_type smallint DEFAULT 0 NOT NULL, -- 0:linear, 1:degressive, 2:exceptional +CREATE TABLE llx_asset_depreciation_options_fiscal +( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + fk_asset integer, + fk_asset_model integer, - degressive_coefficient double(24,8), - duration smallint NOT NULL, - duration_type smallint DEFAULT 0 NOT NULL, -- 0:annual, 1:monthly, 2:daily + depreciation_type smallint DEFAULT 0 NOT NULL, -- 0:linear, 1:degressive, 2:exceptional - amount_base_depreciation_ht double(24,8), - amount_base_deductible_ht double(24,8), - total_amount_last_depreciation_ht double(24,8), + degressive_coefficient double(24,8), + duration smallint NOT NULL, + duration_type smallint DEFAULT 0 NOT NULL, -- 0:annual, 1:monthly, 2:daily - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - fk_user_modif integer + amount_base_depreciation_ht double(24,8), + amount_base_deductible_ht double(24,8), + total_amount_last_depreciation_ht double(24,8), + + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user_modif integer ) ENGINE=innodb; -CREATE TABLE llx_asset_depreciation( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - fk_asset integer NOT NULL, - depreciation_mode varchar(255) NOT NULL, -- (economic, fiscal or other) +CREATE TABLE llx_asset_depreciation +( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - ref varchar(255) NOT NULL, - depreciation_date datetime NOT NULL, - depreciation_ht double(24,8) NOT NULL, - cumulative_depreciation_ht double(24,8) NOT NULL, + fk_asset integer NOT NULL, + depreciation_mode varchar(255) NOT NULL, -- (economic, fiscal or other) - accountancy_code_debit varchar(32), - accountancy_code_credit varchar(32), + ref varchar(255) NOT NULL, + depreciation_date datetime NOT NULL, + depreciation_ht double(24,8) NOT NULL, + cumulative_depreciation_ht double(24,8) NOT NULL, - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - fk_user_modif integer + accountancy_code_debit varchar(32), + accountancy_code_credit varchar(32), + + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_user_modif integer ) ENGINE=innodb; + CREATE TABLE llx_asset_model( - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - entity integer DEFAULT 1 NOT NULL, -- multi company id + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + entity integer DEFAULT 1 NOT NULL, -- multi company id ref varchar(128) NOT NULL, label varchar(255) NOT NULL, - asset_type smallint NOT NULL, - fk_pays integer DEFAULT 0, + asset_type smallint NOT NULL, + fk_pays integer DEFAULT 0, - note_public text, - note_private text, - date_creation datetime 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), - status smallint NOT NULL + note_public text, + note_private text, + date_creation datetime 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), + status smallint NOT NULL ) ENGINE=innodb; CREATE TABLE llx_asset_model_extrafields ( - rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, fk_object integer NOT NULL, import_key varchar(14) -- import key ) ENGINE=innodb; + ALTER TABLE llx_c_asset_disposal_type ADD UNIQUE INDEX uk_c_asset_disposal_type(code, entity); ALTER TABLE llx_asset ADD INDEX idx_asset_fk_asset_model (fk_asset_model); ALTER TABLE llx_asset ADD INDEX idx_asset_fk_disposal_type (fk_disposal_type); -ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); -ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_disposal_type FOREIGN KEY (fk_disposal_type) REFERENCES llx_c_asset_disposal_type (rowid); +ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); +ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_disposal_type FOREIGN KEY (fk_disposal_type) REFERENCES llx_c_asset_disposal_type (rowid); ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_user_creat FOREIGN KEY (fk_user_creat) REFERENCES llx_user (rowid); ALTER TABLE llx_asset ADD CONSTRAINT fk_asset_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); @@ -501,33 +519,33 @@ ALTER TABLE llx_asset_accountancy_codes_economic ADD INDEX idx_asset_ace_rowid ( ALTER TABLE llx_asset_accountancy_codes_economic ADD UNIQUE uk_asset_ace_fk_asset (fk_asset); ALTER TABLE llx_asset_accountancy_codes_economic ADD UNIQUE uk_asset_ace_fk_asset_model (fk_asset_model); -ALTER TABLE llx_asset_accountancy_codes_economic ADD CONSTRAINT fk_asset_ace_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); +ALTER TABLE llx_asset_accountancy_codes_economic ADD CONSTRAINT fk_asset_ace_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); ALTER TABLE llx_asset_accountancy_codes_economic ADD CONSTRAINT fk_asset_ace_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); -ALTER TABLE llx_asset_accountancy_codes_economic ADD CONSTRAINT fk_asset_ace_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_accountancy_codes_economic ADD CONSTRAINT fk_asset_ace_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); ALTER TABLE llx_asset_accountancy_codes_fiscal ADD INDEX idx_asset_acf_rowid (rowid); ALTER TABLE llx_asset_accountancy_codes_fiscal ADD UNIQUE uk_asset_acf_fk_asset (fk_asset); ALTER TABLE llx_asset_accountancy_codes_fiscal ADD UNIQUE uk_asset_acf_fk_asset_model (fk_asset_model); -ALTER TABLE llx_asset_accountancy_codes_fiscal ADD CONSTRAINT fk_asset_acf_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); -ALTER TABLE llx_asset_accountancy_codes_fiscal ADD CONSTRAINT fk_asset_acf_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); -ALTER TABLE llx_asset_accountancy_codes_fiscal ADD CONSTRAINT fk_asset_acf_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_accountancy_codes_fiscal ADD CONSTRAINT fk_asset_acf_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); +ALTER TABLE llx_asset_accountancy_codes_fiscal ADD CONSTRAINT fk_asset_acf_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); +ALTER TABLE llx_asset_accountancy_codes_fiscal ADD CONSTRAINT fk_asset_acf_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); ALTER TABLE llx_asset_depreciation_options_economic ADD INDEX idx_asset_doe_rowid (rowid); ALTER TABLE llx_asset_depreciation_options_economic ADD UNIQUE uk_asset_doe_fk_asset (fk_asset); ALTER TABLE llx_asset_depreciation_options_economic ADD UNIQUE uk_asset_doe_fk_asset_model (fk_asset_model); -ALTER TABLE llx_asset_depreciation_options_economic ADD CONSTRAINT fk_asset_doe_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); +ALTER TABLE llx_asset_depreciation_options_economic ADD CONSTRAINT fk_asset_doe_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); ALTER TABLE llx_asset_depreciation_options_economic ADD CONSTRAINT fk_asset_doe_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); -ALTER TABLE llx_asset_depreciation_options_economic ADD CONSTRAINT fk_asset_doe_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_depreciation_options_economic ADD CONSTRAINT fk_asset_doe_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); ALTER TABLE llx_asset_depreciation_options_fiscal ADD INDEX idx_asset_dof_rowid (rowid); ALTER TABLE llx_asset_depreciation_options_fiscal ADD UNIQUE uk_asset_dof_fk_asset (fk_asset); ALTER TABLE llx_asset_depreciation_options_fiscal ADD UNIQUE uk_asset_dof_fk_asset_model (fk_asset_model); -ALTER TABLE llx_asset_depreciation_options_fiscal ADD CONSTRAINT fk_asset_dof_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); +ALTER TABLE llx_asset_depreciation_options_fiscal ADD CONSTRAINT fk_asset_dof_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); ALTER TABLE llx_asset_depreciation_options_fiscal ADD CONSTRAINT fk_asset_dof_asset_model FOREIGN KEY (fk_asset_model) REFERENCES llx_asset_model (rowid); -ALTER TABLE llx_asset_depreciation_options_fiscal ADD CONSTRAINT fk_asset_dof_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_depreciation_options_fiscal ADD CONSTRAINT fk_asset_dof_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); ALTER TABLE llx_asset_depreciation ADD INDEX idx_asset_depreciation_rowid (rowid); ALTER TABLE llx_asset_depreciation ADD INDEX idx_asset_depreciation_fk_asset (fk_asset); @@ -535,8 +553,8 @@ ALTER TABLE llx_asset_depreciation ADD INDEX idx_asset_depreciation_depreciation ALTER TABLE llx_asset_depreciation ADD INDEX idx_asset_depreciation_ref (ref); ALTER TABLE llx_asset_depreciation ADD UNIQUE uk_asset_depreciation_fk_asset (fk_asset, depreciation_mode, ref); -ALTER TABLE llx_asset_depreciation ADD CONSTRAINT fk_asset_depreciation_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); -ALTER TABLE llx_asset_depreciation ADD CONSTRAINT fk_asset_depreciation_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_depreciation ADD CONSTRAINT fk_asset_depreciation_asset FOREIGN KEY (fk_asset) REFERENCES llx_asset (rowid); +ALTER TABLE llx_asset_depreciation ADD CONSTRAINT fk_asset_depreciation_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); ALTER TABLE llx_asset_model ADD INDEX idx_asset_model_rowid (rowid); ALTER TABLE llx_asset_model ADD INDEX idx_asset_model_ref (ref); @@ -544,8 +562,8 @@ ALTER TABLE llx_asset_model ADD INDEX idx_asset_model_pays (fk_pays); ALTER TABLE llx_asset_model ADD INDEX idx_asset_model_entity (entity); ALTER TABLE llx_asset_model ADD UNIQUE INDEX uk_asset_model (entity, ref); -ALTER TABLE llx_asset_model ADD CONSTRAINT fk_asset_model_user_creat FOREIGN KEY (fk_user_creat) REFERENCES llx_user (rowid); -ALTER TABLE llx_asset_model ADD CONSTRAINT fk_asset_model_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_model ADD CONSTRAINT fk_asset_model_user_creat FOREIGN KEY (fk_user_creat) REFERENCES llx_user (rowid); +ALTER TABLE llx_asset_model ADD CONSTRAINT fk_asset_model_user_modif FOREIGN KEY (fk_user_modif) REFERENCES llx_user (rowid); ALTER TABLE llx_asset_model_extrafields ADD INDEX idx_asset_model_extrafields (fk_object); @@ -581,10 +599,11 @@ UPDATE llx_c_availability SET type_duration = 'w', qty = 4 WHERE code = 'AV_4W'; -- Deposit generation helper with specific payment terms -ALTER TABLE llx_c_payment_term ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER decalage; -ALTER TABLE llx_societe ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER cond_reglement; -ALTER TABLE llx_propal ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER fk_cond_reglement; -ALTER TABLE llx_commande ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER fk_cond_reglement; +ALTER TABLE llx_c_payment_term ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER decalage; +ALTER TABLE llx_societe ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER cond_reglement; +ALTER TABLE llx_propal ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER fk_cond_reglement; +ALTER TABLE llx_commande ADD COLUMN deposit_percent VARCHAR(63) DEFAULT NULL AFTER fk_cond_reglement; + INSERT INTO llx_c_payment_term(code, sortorder, active, libelle, libelle_facture, type_cdr, nbjour, deposit_percent) values ('DEP30PCTDEL', 13, 0, '__DEPOSIT_PERCENT__% deposit', '__DEPOSIT_PERCENT__% deposit, remainder on delivery', 0, 1, '30'); @@ -599,13 +618,13 @@ DELETE FROM llx_boxes_def WHERE file IN ('box_bom.php@bom', 'box_bom.php', 'box_ ALTER TABLE llx_takepos_floor_tables ADD UNIQUE(entity,label); -ALTER TABLE llx_partnership ADD COLUMN url_to_check varchar(255); -ALTER TABLE llx_c_partnership_type ADD COLUMN keyword varchar(128); +ALTER TABLE llx_partnership ADD COLUMN url_to_check varchar(255); +ALTER TABLE llx_c_partnership_type ADD COLUMN keyword varchar(128); -ALTER TABLE llx_eventorganization_conferenceorboothattendee ADD COLUMN firstname varchar(100); -ALTER TABLE llx_eventorganization_conferenceorboothattendee ADD COLUMN lastname varchar(100); -ALTER TABLE llx_eventorganization_conferenceorboothattendee ADD COLUMN email_company varchar(128) after email; +ALTER TABLE llx_eventorganization_conferenceorboothattendee ADD COLUMN firstname varchar(100); +ALTER TABLE llx_eventorganization_conferenceorboothattendee ADD COLUMN lastname varchar(100); +ALTER TABLE llx_eventorganization_conferenceorboothattendee ADD COLUMN email_company varchar(128) after email; ALTER TABLE llx_c_email_template ADD COLUMN email_from varchar(255); diff --git a/htdocs/install/mysql/tables/llx_adherent_type.sql b/htdocs/install/mysql/tables/llx_adherent_type.sql index 243372c0452..4144d9b32b7 100644 --- a/htdocs/install/mysql/tables/llx_adherent_type.sql +++ b/htdocs/install/mysql/tables/llx_adherent_type.sql @@ -18,22 +18,23 @@ -- -- =================================================================== -- --- statut --- 0 : actif --- 1 : inactif +-- state / statut +-- 0 : active / actif +-- 1 : inactive / inactif +-- create table llx_adherent_type ( rowid integer AUTO_INCREMENT PRIMARY KEY, - entity integer DEFAULT 1 NOT NULL, + entity integer DEFAULT 1 NOT NULL, -- multi company id 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, - duration varchar(6) DEFAULT NULL, - subscription varchar(3) NOT NULL DEFAULT '1', - amount double(24,8) DEFAULT NULL, - vote varchar(3) NOT NULL DEFAULT '1', - note text, - mail_valid text + statut smallint NOT NULL DEFAULT 0, -- state 0 = active , 1 = inactive + libelle varchar(50) NOT NULL, -- label + morphy varchar(3) NOT NULL, -- moral and/or physical entity + duration varchar(6) DEFAULT NULL, -- (minimal) duration of membership + subscription varchar(3) NOT NULL DEFAULT '1', -- subscription with costs / fee or without / for free + amount double(24,8) DEFAULT NULL, -- membership fee + vote varchar(3) NOT NULL DEFAULT '1', -- entitled to vote + note text, -- description / comment + mail_valid text -- text for welcome email )ENGINE=innodb; diff --git a/htdocs/intracommreport/admin/intracommreport.php b/htdocs/intracommreport/admin/intracommreport.php index 13231c43af2..3185e8a030e 100644 --- a/htdocs/intracommreport/admin/intracommreport.php +++ b/htdocs/intracommreport/admin/intracommreport.php @@ -117,7 +117,7 @@ foreach ($list_DEB as $key) { print '
    '.$label.''; - print ''; + print ''; print '
    '.$label.''; - print ''; + print ''; print '
    '; if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { @@ -756,7 +756,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { print $langs->trans("Batch"); @@ -787,11 +787,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; print ''; print ''; if ($tmpproduct->stock_reel < ($line->qty - $alreadyconsumed)) { print img_warning($langs->trans('StockTooLow')).' '; @@ -918,7 +918,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; if ($line2['batch'] != '') { $tmpbatch->fetch(0, $line2['fk_product'], $line2['batch']); @@ -1033,12 +1033,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; if ($tmpproduct->status_batch) { $preselected = (GETPOSTISSET('batch-'.$line->id.'-'.$i) ? GETPOST('batch-'.$line->id.'-'.$i) : ''); @@ -1121,7 +1121,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print $langs->trans("Warehouse"); } print ''; if ($collapse || in_array($action, array('consumeorproduce', 'consumeandproduceall'))) { print $langs->trans("Batch"); @@ -1149,7 +1149,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''; print ''; // Warehouse print ''; if ($line2['batch'] != '') { $tmpbatch->fetch(0, $line2['fk_product'], $line2['batch']); @@ -1324,7 +1324,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''.$langs->trans("NoStockChangeOnServices").''; } print ''; if ($tmpproduct->status_batch) { $preselected = (GETPOSTISSET('batchtoproduce-'.$line->id.'-'.$i) ? GETPOST('batchtoproduce-'.$line->id.'-'.$i) : ''); diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 9aade4fa62d..d0b7e4ece73 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -1860,7 +1860,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print '
    '.$langs->trans("ManageLotSerial").''; $statutarray = array('0' => $langs->trans("ProductStatusNotOnBatch"), '1' => $langs->trans("ProductStatusOnBatch"), '2' => $langs->trans("ProductStatusOnSerial")); @@ -1964,7 +1964,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print '
    '.$langs->trans("Description").''; // We use dolibarr_details as type of DolEditor here, because we must not accept images as description is included into PDF and not accepted by TCPDF. - $doleditor = new DolEditor('desc', $object->description, '', 160, 'dolibarr_details', '', false, true, !empty($conf->global->FCKEDITOR_ENABLE_PRODUCTDESC)?$conf->global->FCKEDITOR_ENABLE_PRODUCTDESC:0, ROWS_4, '90%'); + $doleditor = new DolEditor('desc', $object->description, '', 160, 'dolibarr_details', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_4, '90%'); $doleditor->Create(); print "
    '.$langs->trans("NoteNotVisibleOnBill").''; - $doleditor = new DolEditor('note_private', $object->note_private, '', 140, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%'); + $doleditor = new DolEditor('note_private', $object->note_private, '', 140, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_4, '90%'); $doleditor->Create(); print "
    '.$langs->trans('ProductSupplierDescription').''; - $doleditor = new DolEditor('supplier_description', $object->desc_supplier, '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%'); + $doleditor = new DolEditor('supplier_description', $object->desc_supplier, '', 160, 'dolibarr_details', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_4, '90%'); $doleditor->Create(); print '
    '; print img_picto($langs->trans("LotSerial"), 'lot', 'class="paddingright"'); print ''; @@ -643,7 +643,7 @@ foreach ($listofdata as $key => $val) { print ''; print $productstatic->getNomUrl(1).' - '.$productstatic->label; print ''; print $val['batch']; print '
    '.$langs->trans("ManageLotSerial").''; print $object->getLibStatut(0, 2); print '
    '; if ($action === 'editline' && $line->id == $lineid) print ''; else { @@ -883,7 +883,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $form->select_produits($fk_product, 'fk_product', $filtertype, $limit, 0, -1, 2, '', 0, array(), 0, 0, 0, 'minwidth200imp maxwidth300', 1); print ''; print ''; print '
    '; print ''; print ''; if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print ''; @@ -335,13 +335,13 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print ''; print ''; print ''; // Other field (not used) if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) { print ''; } diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 0cfe126d69b..2ad89326e6a 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -996,7 +996,7 @@ if ($action == 'create' && $user->rights->projet->creer) { // Description print ''; print ''; diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index 0c56ecf0677..4d851b86270 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -86,8 +86,33 @@ class Project extends CommonObject */ public $title; + /** + * @var int Date start + * @deprecated + * @see $date_start + */ + public $dateo; + + /** + * @var int Date start + */ public $date_start; + + /** + * @var int Date end + * @deprecated + * @see $date_end + */ + public $datee; + + /** + * @var int Date end + */ public $date_end; + + /** + * @var int Date close + */ public $date_close; public $socid; // To store id of thirdparty @@ -694,12 +719,12 @@ class Project extends CommonObject * @param string $type 'propal','order','invoice','order_supplier','invoice_supplier',... * @param string $tablename name of table associated of the type * @param string $datefieldname name of date field for filter - * @param int $dates Start date - * @param int $datee End date + * @param int $date_start Start date + * @param int $date_end End date * @param string $projectkey Equivalent key to fk_projet for actual type * @return mixed Array list of object ids linked to project, < 0 or string if error */ - public function get_element_list($type, $tablename, $datefieldname = '', $dates = '', $datee = '', $projectkey = 'fk_projet') + public function get_element_list($type, $tablename, $datefieldname = '', $date_start = '', $date_end = '', $projectkey = 'fk_projet') { // phpcs:enable @@ -729,28 +754,28 @@ class Project extends CommonObject $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." IN (".$this->db->sanitize($ids).") AND entity IN (".getEntity($type).")"; } - if ($dates > 0 && $type == 'loan') { - $sql .= " AND (dateend > '".$this->db->idate($dates)."' OR dateend IS NULL)"; - } elseif ($dates > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table + if ($date_start > 0 && $type == 'loan') { + $sql .= " AND (dateend > '".$this->db->idate($date_start)."' OR dateend IS NULL)"; + } elseif ($date_start > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table if (empty($datefieldname) && !empty($this->table_element_date)) { $datefieldname = $this->table_element_date; } if (empty($datefieldname)) { return 'Error this object has no date field defined'; } - $sql .= " AND (".$datefieldname." >= '".$this->db->idate($dates)."' OR ".$datefieldname." IS NULL)"; + $sql .= " AND (".$datefieldname." >= '".$this->db->idate($date_start)."' OR ".$datefieldname." IS NULL)"; } - if ($datee > 0 && $type == 'loan') { - $sql .= " AND (datestart < '".$this->db->idate($datee)."' OR datestart IS NULL)"; - } elseif ($datee > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table + if ($date_end > 0 && $type == 'loan') { + $sql .= " AND (datestart < '".$this->db->idate($date_end)."' OR datestart IS NULL)"; + } elseif ($date_end > 0 && ($type != 'project_task')) { // For table project_taks, we want the filter on date apply on project_time_spent table if (empty($datefieldname) && !empty($this->table_element_date)) { $datefieldname = $this->table_element_date; } if (empty($datefieldname)) { return 'Error this object has no date field defined'; } - $sql .= " AND (".$datefieldname." <= '".$this->db->idate($datee)."' OR ".$datefieldname." IS NULL)"; + $sql .= " AND (".$datefieldname." <= '".$this->db->idate($date_end)."' OR ".$datefieldname." IS NULL)"; } $parameters = array( @@ -758,8 +783,8 @@ class Project extends CommonObject 'type' => $type, 'tablename' => $tablename, 'datefieldname' => $datefieldname, - 'dates' => $dates, - 'datee' => $datee, + 'dates' => $date_start, + 'datee' => $date_end, 'fk_projet' => $projectkey, 'ids' => $ids, ); diff --git a/htdocs/projet/tasks.php b/htdocs/projet/tasks.php index f2e514afe56..612aa0e6fe7 100644 --- a/htdocs/projet/tasks.php +++ b/htdocs/projet/tasks.php @@ -729,16 +729,21 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third // Project print ''; + $contactsofproject = (empty($object->id) ? '' : $object->getListContactId('internal')); + // Assigned to print ''; diff --git a/htdocs/reception/card.php b/htdocs/reception/card.php index 9c0d3b01136..ed4586a7376 100644 --- a/htdocs/reception/card.php +++ b/htdocs/reception/card.php @@ -1244,7 +1244,7 @@ if ($action == 'create') { if (!empty($extrafields)) { //var_dump($line); $colspan = 5; - if ($conf->productbatch->enabled) { + if (isModEnabled('productbatch')) { $colspan += 3; } $recLine = new CommandeFournisseurDispatch($db); diff --git a/htdocs/reception/class/reception.class.php b/htdocs/reception/class/reception.class.php index 958528e2fe7..f7d695abaad 100644 --- a/htdocs/reception/class/reception.class.php +++ b/htdocs/reception/class/reception.class.php @@ -600,7 +600,7 @@ class Reception extends CommonObject $inventorycode = ''; $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode); - if ($result < 0) { + if (intval($result) < 0) { $error++; $this->errors[] = $mouvS->error; $this->errors = array_merge($this->errors, $mouvS->errors); @@ -614,7 +614,7 @@ class Reception extends CommonObject $inventorycode = ''; $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode); - if ($result < 0) { + if (intval($result) < 0) { $error++; $this->errors[] = $mouvS->error; $this->errors = array_merge($this->errors, $mouvS->errors); diff --git a/htdocs/recruitment/admin/setup.php b/htdocs/recruitment/admin/setup.php index 1ef8fa544ad..c2cd40f6b6d 100644 --- a/htdocs/recruitment/admin/setup.php +++ b/htdocs/recruitment/admin/setup.php @@ -229,7 +229,7 @@ if ($action == 'edit') { print ''; + print ''; } print '
    '.$langs->trans('Label').'
    '.$langs->trans('Description').''; - $doleditor = new DolEditor("desc-$key", $object->multilangs[$key]["description"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor("desc-$key", $object->multilangs[$key]["description"], '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print '
    '.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'; - $doleditor = new DolEditor("other-$key", $object->multilangs[$key]["other"], '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor("other-$key", $object->multilangs[$key]["other"], '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); } print '
    '.$langs->trans('Label').'
    '.$langs->trans('Description').''; - $doleditor = new DolEditor('desc', '', '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor('desc', '', '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print '
    '.$langs->trans('Other').' ('.$langs->trans("NotUsed").''; - $doleditor = new DolEditor('other', '', '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); + $doleditor = new DolEditor('other', '', '', 160, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_PRODUCTDESC'), ROWS_3, '90%'); $doleditor->Create(); print '
    '.$langs->trans("Description").''; - $doleditor = new DolEditor('description', $object->description, '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); + $doleditor = new DolEditor('description', $object->description, '', 90, 'dolibarr_notes', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_3, '90%'); $doleditor->Create(); print '
    '.$langs->trans("ChildOfProjectTask").''; print img_picto('', 'project'); - $formother->selectProjectTasks(GETPOST('task_parent'), !empty($projectid) ? $projectid : $object->id, 'task_parent', 0, 0, 1, 1, 0, '0,1', 'maxwidth500'); + $formother->selectProjectTasks(GETPOST('task_parent'), empty($projectid) ? $object->id : $projectid, 'task_parent', 0, 0, 1, 1, 0, '0,1', 'maxwidth500 widthcentpercentminusxx'); print '
    '.$langs->trans("AffectedTo").''; - $contactsofproject = (!empty($object->id) ? $object->getListContactId('internal') : ''); if (is_array($contactsofproject) && count($contactsofproject)) { print $form->select_dolusers($user->id, 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 0, '', 'maxwidth300'); } else { - print ''.$langs->trans("NoUserAssignedToTheProject").''; + if ($projectid > 0 || $object->id > 0) { + print ''.$langs->trans("NoUserAssignedToTheProject").''; + } else { + print $form->select_dolusers($user->id, 'userid', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + } } print '
    '; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print '
    '; @@ -250,7 +250,7 @@ if ($action == 'edit') { print ''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''.$conf->global->$key.''; + print ''.getDolGlobalString($key).''; } print ''; diff --git a/htdocs/recruitment/admin/setup_candidatures.php b/htdocs/recruitment/admin/setup_candidatures.php index 58172c2e767..1ab24288401 100644 --- a/htdocs/recruitment/admin/setup_candidatures.php +++ b/htdocs/recruitment/admin/setup_candidatures.php @@ -226,7 +226,7 @@ if ($action == 'edit') { print ''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''; + print ''; } print ''; @@ -247,7 +247,7 @@ if ($action == 'edit') { print ''; $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); print $form->textwithpicto($langs->trans($key), $tooltiphelp); - print ''.$conf->global->$key.''; + print ''.getDolGlobalString($key).''; } print ''; diff --git a/htdocs/recruitment/class/recruitmentcandidature.class.php b/htdocs/recruitment/class/recruitmentcandidature.class.php index 1561d0a72ab..db8a8d08186 100644 --- a/htdocs/recruitment/class/recruitmentcandidature.class.php +++ b/htdocs/recruitment/class/recruitmentcandidature.class.php @@ -110,11 +110,11 @@ class RecruitmentCandidature extends CommonObject public $fields = array( 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'comment'=>"Id"), 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1), - 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of candidature"), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of candidature", 'csslist'=>'nowraponall'), 'fk_recruitmentjobposition' => array('type'=>'integer:RecruitmentJobPosition:recruitment/class/recruitmentjobposition.class.php', 'label'=>'Job', 'enabled'=>'1', 'position'=>15, 'notnull'=>0, 'visible'=>1, 'index'=>1, 'picto'=>'recruitmentjobposition', 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'csslist'=>'minwidth125 tdoverflowmax200'), 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0,), 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0,), - 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>1,), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,), 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',), 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,), diff --git a/htdocs/recruitment/recruitmentcandidature_list.php b/htdocs/recruitment/recruitmentcandidature_list.php index 8e3ea982193..e8a52730b74 100644 --- a/htdocs/recruitment/recruitmentcandidature_list.php +++ b/htdocs/recruitment/recruitmentcandidature_list.php @@ -97,7 +97,7 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Default sort order (if not yet defined by previous GETPOST) if (!$sortfield) { - $sortfield = "t.ref"; // Set here default search field. By default 1st field in definition. + $sortfield = "t.date_creation"; // Set here default search field. By default 1st field in definition. } if (!$sortorder) { $sortorder = "DESC"; diff --git a/htdocs/recruitment/recruitmentjobposition_list.php b/htdocs/recruitment/recruitmentjobposition_list.php index 4f63434f9cf..ef9a882bd8e 100644 --- a/htdocs/recruitment/recruitmentjobposition_list.php +++ b/htdocs/recruitment/recruitmentjobposition_list.php @@ -558,7 +558,7 @@ $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$ $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (!empty($arrayfields['nbapplications']['checked'])) { - print ''.$langs->trans("Applications").''; + print ''.$langs->trans("RecruitmentCandidatures").''; $totalarray['nbfield']++; } // Action column diff --git a/htdocs/salaries/admin/salaries.php b/htdocs/salaries/admin/salaries.php index 1c9eeec6464..f69e17336c6 100644 --- a/htdocs/salaries/admin/salaries.php +++ b/htdocs/salaries/admin/salaries.php @@ -122,7 +122,7 @@ foreach ($list as $key) { if (!empty($conf->accounting->enabled)) { print $formaccounting->select_account(getDolGlobalString($key), $key, 1, '', 1, 1); } else { - print ''; + print ''; } print ''; } diff --git a/htdocs/salaries/class/paymentsalary.class.php b/htdocs/salaries/class/paymentsalary.class.php index 08e850c259a..3a6ade39c6a 100644 --- a/htdocs/salaries/class/paymentsalary.class.php +++ b/htdocs/salaries/class/paymentsalary.class.php @@ -1,7 +1,7 @@ - * Copyright (C) 2014 Juanjo Menent - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2011-2022 Alexandre Spangaro + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -486,7 +486,7 @@ class PaymentSalary extends CommonObject */ public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) { - global $conf; + global $conf, $langs; // Clean data $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); diff --git a/htdocs/salaries/class/salary.class.php b/htdocs/salaries/class/salary.class.php index a7e96741862..668bd1de299 100644 --- a/htdocs/salaries/class/salary.class.php +++ b/htdocs/salaries/class/salary.class.php @@ -1,7 +1,7 @@ - * Copyright (C) 2014 Juanjo Menent - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2011-2022 Alexandre Spangaro + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -94,6 +94,10 @@ class Salary extends CommonObject */ public $user; + /** + * 1 if salary paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code) + */ + public $paye; const STATUS_UNPAID = 0; const STATUS_PAID = 1; @@ -218,8 +222,6 @@ class Salary extends CommonObject $sql .= " s.fk_user_author,"; $sql .= " s.fk_user_modif,"; $sql .= " s.fk_account"; - /*$sql .= " b.fk_type,"; - $sql .= " b.rappro";*/ $sql .= " FROM ".MAIN_DB_PREFIX."salary as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; @@ -231,28 +233,26 @@ class Salary extends CommonObject if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; $this->ref = $obj->rowid; $this->tms = $this->db->jdate($obj->tms); - $this->fk_user = $obj->fk_user; + $this->fk_user = $obj->fk_user; $this->datep = $this->db->jdate($obj->datep); $this->datev = $this->db->jdate($obj->datev); - $this->amount = $obj->amount; - $this->fk_project = $obj->fk_project; - $this->type_payment = $obj->fk_typepayment; + $this->amount = $obj->amount; + $this->fk_project = $obj->fk_project; + $this->type_payment = $obj->fk_typepayment; $this->label = $obj->label; $this->datesp = $this->db->jdate($obj->datesp); $this->dateep = $this->db->jdate($obj->dateep); $this->note = $obj->note; $this->paye = $obj->paye; - $this->fk_bank = $obj->fk_bank; - $this->fk_user_author = $obj->fk_user_author; - $this->fk_user_modif = $obj->fk_user_modif; - $this->fk_account = $this->accountid = $obj->fk_account; - $this->fk_type = $obj->fk_type; - $this->rappro = $obj->rappro; + $this->fk_bank = $obj->fk_bank; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_modif = $obj->fk_user_modif; + $this->fk_account = $this->accountid = $obj->fk_account; - // Retreive all extrafield + // Retrieve all extrafield // fetch optionals attributes and labels $this->fetch_optionals(); } diff --git a/htdocs/salaries/list.php b/htdocs/salaries/list.php index 957e76ac440..e578e8e0d02 100644 --- a/htdocs/salaries/list.php +++ b/htdocs/salaries/list.php @@ -1,8 +1,8 @@ - * Copyright (C) 2015-2016 Laurent Destailleur - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2011-2022 Alexandre Spangaro + * Copyright (C) 2015-2016 Laurent Destailleur + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -90,22 +90,10 @@ $search_date_end_to = dol_mktime(23, 59, 59, GETPOST('search_date_end_tomonth', $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'int'); $search_status = GETPOST('search_status', 'int'); +$search_type_id = GETPOST('search_type_id', 'int'); $filtre = GETPOST("filtre", 'restricthtml'); -if (!GETPOST('search_type_id', 'int')) { - $newfiltre = str_replace('filtre=', '', $filtre); - $filterarray = explode('-', $newfiltre); - foreach ($filterarray as $val) { - $part = explode(':', $val); - if ($part[0] == 's.fk_typepayment') { - $search_type_id = $part[1]; - } - } -} else { - $search_type_id = GETPOST('search_type_id', 'int'); -} - $childids = $user->getAllChildIds(1); // Initialize array of search criterias @@ -519,6 +507,9 @@ if (isset($extrafields->attributes[$object->table_element]['computed']) && is_ar $i = 0; $total = 0; $totalarray = array(); +$totalarray['nbfield'] = 0; +$totalarray['val'] = array(); +$totalarray['val']['totalttcfield'] = 0; while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); if (empty($obj)) { diff --git a/htdocs/salaries/payments.php b/htdocs/salaries/payments.php index 00d3463357c..54a8589677d 100644 --- a/htdocs/salaries/payments.php +++ b/htdocs/salaries/payments.php @@ -1,8 +1,8 @@ - * Copyright (C) 2015-2016 Laurent Destailleur - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2021 Gauthier VERDOL +/* Copyright (C) 2011-2022 Alexandre Spangaro + * Copyright (C) 2015-2016 Laurent Destailleur + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -391,7 +391,9 @@ if (!empty($socid)) { } $newcardbutton = dolGetButtonTitle($langs->trans('NewSalaryPayment'), '', 'fa fa-plus-circle', $url, '', $user->rights->salaries->write); -print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'object_payment', 0, $newcardbutton, '', $limit, 0, 0, 1); +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_payment', 0, $newcardbutton, '', $limit, 0, 0, 1); + +$moreforfilter = ''; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; //$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields diff --git a/htdocs/takepos/admin/receipt.php b/htdocs/takepos/admin/receipt.php index 8ba37a69ab3..bf5f5e8b931 100644 --- a/htdocs/takepos/admin/receipt.php +++ b/htdocs/takepos/admin/receipt.php @@ -192,10 +192,10 @@ if ($conf->global->TAKEPOS_PRINT_METHOD == "browser" || $conf->global->TAKEPOS_P print ''; $variablename = 'TAKEPOS_HEADER'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print "\n"; @@ -205,10 +205,10 @@ if ($conf->global->TAKEPOS_PRINT_METHOD == "browser" || $conf->global->TAKEPOS_P print ''; $variablename = 'TAKEPOS_FOOTER'; if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { - print ''; + print ''; } else { include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes'); + $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } print "\n"; diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php index 433a7d26cfd..2f82eefffeb 100644 --- a/htdocs/theme/eldy/global.inc.php +++ b/htdocs/theme/eldy/global.inc.php @@ -1045,6 +1045,7 @@ div.divsearchfield { overflow: auto; padding-bottom: 5px; opacity: 0.6; + font-size: small; } .divadvancedsearchfield:first-child { margin-top: 3px; @@ -4817,7 +4818,7 @@ div#card-errors { color: #fa755a; text-align: center; padding-top: 3px; - max-width: 320px; + /* max-width: 320px; */ } @@ -7615,6 +7616,14 @@ div.clipboardCPValue.hidewithsize { /* border-bottom: 2px solid var(--colorbackhmenu1) !important; */ border-bottom: 1px solid var(--colortopbordertitle1) !important; } + + div#card-errors { + max-width: unset; + } + + #dolpaymenttable { + padding: 5px; + } } @media only screen and (max-width: 320px) diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index c99482d6415..bcd2598740a 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -530,6 +530,7 @@ input.buttonpayment, button.buttonpayment, div.buttonpayment { background-color: #eee; white-space: normal; color: #888 !important; + height: 60px; } .nofocusvisible:focus-visible { outline: none; @@ -1163,6 +1164,7 @@ div.divsearchfield { white-space: nowrap; padding-bottom: 5px; opacity: 0.6; + font-size: small; } .divadvancedsearchfield:first-child { margin-top: 3px; @@ -4669,11 +4671,10 @@ div#card-errors { color: #fa755a; text-align: center; padding-top: 3px; - max-width: 320px; + /* max-width: 320px; */ } - /* * Effect Postit */ @@ -7299,6 +7300,14 @@ div.clipboardCPValue.hidewithsize { div.divButAction { margin-bottom: 0.5em; } + + div#card-errors { + max-width: unset; + } + + #dolpaymenttable { + padding: 5px; + } } diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index c073937b048..b47781a9db4 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -700,14 +700,13 @@ class User extends CommonObject public function hasRight($module, $permlevel1, $permlevel2 = '') { global $conf; - // For compatibility with bad naming permissions on module $moduletomoduletouse = array( 'contract' => 'contrat', 'member' => 'adherent', // We must check $user->rights->adherent... 'mo' => 'mrp', 'order' => 'commande', - 'product' => 'produit', // We must check $user->rights->produit... + //'product' => 'produit', // We must check $user->rights->produit... 'project' => 'projet', 'shipping' => 'expedition', 'task' => 'task@projet', @@ -721,14 +720,24 @@ class User extends CommonObject 'position@hrm' => 'all@hrm', // skill / job / position objects rights are for the moment grouped into right level "all" 'facturerec' => 'facture' ); + if (!empty($moduletomoduletouse[$module])) { $module = $moduletomoduletouse[$module]; } + $moduleRightsMapping = array( + 'product' => 'produit', // We must check $user->rights->produit... + ); + + $rightsPath = $module; + if (!empty($moduleRightsMapping[$rightsPath])) { + $rightsPath = $moduleRightsMapping[$rightsPath]; + } + // If module is abc@module, we check permission user->rights->module->abc->permlevel1 - $tmp = explode('@', $module, 2); + $tmp = explode('@', $rightsPath, 2); if (! empty($tmp[1])) { - $module = $tmp[1]; + $rightsPath = $tmp[1]; $permlevel2 = $permlevel1; $permlevel1 = $tmp[0]; } @@ -749,49 +758,49 @@ class User extends CommonObject if ($permlevel1 == 'recruitmentcandidature') { $permlevel1 = 'recruitmentjobposition'; } - - //var_dump($module.' '.$permlevel1.' '.$permlevel2); - if (empty($module) || empty($this->rights) || empty($this->rights->$module) || empty($permlevel1)) { + //var_dump($module.' '.$permlevel1.' '.$permlevel2. ' '. $rightsPath); + //var_dump($this->rights); + if (empty($rightsPath) || empty($this->rights) || empty($this->rights->$rightsPath) || empty($permlevel1)) { return 0; } if ($permlevel2) { - if (!empty($this->rights->$module->$permlevel1)) { - if (!empty($this->rights->$module->$permlevel1->$permlevel2)) { - return $this->rights->$module->$permlevel1->$permlevel2; + if (!empty($this->rights->$rightsPath->$permlevel1)) { + if (!empty($this->rights->$rightsPath->$permlevel1->$permlevel2)) { + return $this->rights->$rightsPath->$permlevel1->$permlevel2; } // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer" // instead of "read", "write", "delete" - if ($permlevel2 == 'read' && !empty($this->rights->$module->$permlevel1->lire)) { - return $this->rights->$module->lire; + if ($permlevel2 == 'read' && !empty($this->rights->$rightsPath->$permlevel1->lire)) { + return $this->rights->$rightsPath->lire; } - if ($permlevel2 == 'write' && !empty($this->rights->$module->$permlevel1->creer)) { - return $this->rights->$module->create; + if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->creer)) { + return $this->rights->$rightsPath->create; } - if ($permlevel2 == 'write' && !empty($this->rights->$module->$permlevel1->create)) { - return $this->rights->$module->create; + if ($permlevel2 == 'write' && !empty($this->rights->$rightsPath->$permlevel1->create)) { + return $this->rights->$rightsPath->create; } - if ($permlevel2 == 'delete' && !empty($this->rights->$module->$permlevel1->supprimer)) { - return $this->rights->$module->supprimer; + if ($permlevel2 == 'delete' && !empty($this->rights->$rightsPath->$permlevel1->supprimer)) { + return $this->rights->$rightsPath->supprimer; } } } else { - if (!empty($this->rights->$module->$permlevel1)) { - return $this->rights->$module->$permlevel1; + if (!empty($this->rights->$rightsPath->$permlevel1)) { + return $this->rights->$rightsPath->$permlevel1; } // For backward compatibility with old permissions called "lire", "creer", "create", "supprimer" // instead of "read", "write", "delete" - if ($permlevel1 == 'read' && !empty($this->rights->$module->lire)) { - return $this->rights->$module->lire; + if ($permlevel1 == 'read' && !empty($this->rights->$rightsPath->lire)) { + return $this->rights->$rightsPath->lire; } - if ($permlevel1 == 'write' && !empty($this->rights->$module->creer)) { - return $this->rights->$module->create; + if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->creer)) { + return $this->rights->$rightsPath->create; } - if ($permlevel1 == 'write' && !empty($this->rights->$module->create)) { - return $this->rights->$module->create; + if ($permlevel1 == 'write' && !empty($this->rights->$rightsPath->create)) { + return $this->rights->$rightsPath->create; } - if ($permlevel1 == 'delete' && !empty($this->rights->$module->supprimer)) { - return $this->rights->$module->supprimer; + if ($permlevel1 == 'delete' && !empty($this->rights->$rightsPath->supprimer)) { + return $this->rights->$rightsPath->supprimer; } } diff --git a/htdocs/user/note.php b/htdocs/user/note.php index 1cf1f112df4..801cafbbd52 100644 --- a/htdocs/user/note.php +++ b/htdocs/user/note.php @@ -142,7 +142,7 @@ if ($id) { print "id."\">"; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('note_private', $object->note_private, '', 280, 'dolibarr_notes', 'In', true, false, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_8, '90%'); + $doleditor = new DolEditor('note_private', $object->note_private, '', 280, 'dolibarr_notes', 'In', true, false, getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_8, '90%'); $doleditor->Create(); } else { print dol_string_onlythesehtmltags(dol_htmlentitiesbr($object->note_private)); diff --git a/htdocs/webhook/README.md b/htdocs/webhook/README.md new file mode 100644 index 00000000000..74fe79e76fd --- /dev/null +++ b/htdocs/webhook/README.md @@ -0,0 +1,86 @@ +# WEBHOOK FOR [DOLIBARR ERP CRM](https://www.dolibarr.org) + +## Features + +Description of the module... + + + +Other external modules are available on [Dolistore.com](https://www.dolistore.com). + +## Translations + +Translations can be completed manually by editing files into directories *langs*. + + + + + +## Licenses + +### Main code + +GPLv3 or (at your option) any later version. See file COPYING for more information. + +### Documentation + +All texts and readmes are licensed under GFDL. diff --git a/htdocs/webhook/class/target.class.php b/htdocs/webhook/class/target.class.php new file mode 100644 index 00000000000..d768f7c5c36 --- /dev/null +++ b/htdocs/webhook/class/target.class.php @@ -0,0 +1,1088 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/target.class.php + * \ingroup webhook + * \brief This file is a CRUD class file for Target (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for Target + */ +class Target extends CommonObject +{ + /** + * @var string ID of module. + */ + public $module = 'webhook'; + + /** + * @var string ID to identify managed object. + */ + public $element = 'target'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'webhook_target'; + + /** + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table + */ + public $ismultientitymanaged = 0; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * @var string String with name of icon for target. Must be the part after the 'object_' into object_target.png + */ + public $picto = 'webhook'; + + + const STATUS_DRAFT = 0; + const STATUS_VALIDATED = 1; + const STATUS_CANCELED = 9; + + + /** + * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or '!empty($conf->multicurrency->enabled)' ...) + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage) + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200' + * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar' + * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1. + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'validate' is 1 if need to validate with $this->validateField() + * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value) + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'index'=>1, 'searchall'=>1, 'validate'=>'1', 'comment'=>"Reference of object"), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>"Help text", 'showoncombobox'=>'2', 'validate'=>'1',), + 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3, 'validate'=>'1',), + 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak', 'validate'=>'1',), + 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak', 'validate'=>'1',), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,), + 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',), + 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,), + 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>'1', 'position'=>2000, 'notnull'=>1, 'visible'=>3, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validé', '9'=>'Annulé'), 'validate'=>'1',), + 'url' => array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1,), + 'trigger_codes' => array('type'=>'text', 'label'=>'TriggerCodes', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1, 'help'=>"TriggerCodeInfo",), + ); + public $rowid; + public $ref; + public $label; + public $description; + public $note_public; + public $note_private; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $import_key; + public $status; + public $url; + public $trigger_codes; + // END MODULEBUILDER PROPERTIES + + + // If this object has a subtable with lines + + // /** + // * @var string Name of subtable line + // */ + // public $table_element_line = 'webhook_targetline'; + + // /** + // * @var string Field with ID of parent key if this object has a parent + // */ + // public $fk_element = 'fk_target'; + + // /** + // * @var string Name of subtable class that manage subtable lines + // */ + // public $class_element_line = 'Targetline'; + + // /** + // * @var array List of child tables. To test if we can delete object. + // */ + // protected $childtables = array(); + + // /** + // * @var array List of child tables. To know object to delete on cascade. + // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will + // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object + // */ + // protected $childtablesoncascade = array('webhook_targetdet'); + + // /** + // * @var TargetLine[] Array of subtable lines + // */ + // public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } + + // Example to show how to set values of fields definition dynamically + /*if ($user->rights->webhook->target->read) { + $this->fields['myfield']['visible'] = 1; + $this->fields['myfield']['noteditable'] = 0; + }*/ + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + $resultcreate = $this->createCommon($user, $notrigger); + $this->ref = $this->id; + + if ($resultcreate <= 0) { + return $resultcreate; + } + $resultvalidate = $this->validate($user, $notrigger); + + return $resultvalidate; + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } + + // get lines so they will be clone + //foreach($this->lines as $line) + // $line->fetch_optionals(); + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + if (property_exists($object, 'ref')) { + $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + } + if (property_exists($object, 'label')) { + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + } + if (property_exists($object, 'status')) { + $object->status = self::STATUS_DRAFT; + } + if (property_exists($object, 'date_creation')) { + $object->date_creation = dol_now(); + } + if (property_exists($object, 'date_modification')) { + $object->date_modification = null; + } + // ... + // Clear extrafields that are unique + if (is_array($object->array_options) && count($object->array_options) > 0) { + $extrafields->fetch_name_optionals_label($this->table_element); + foreach ($object->array_options as $key => $option) { + $shortkey = preg_replace('/options_/', '', $key); + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { + //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; + unset($object->array_options[$key]); + } + } + } + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + if (!$error) { + // copy internal contacts + if ($this->copy_linked_contact($object, 'internal') < 0) { + $error++; + } + } + + if (!$error) { + // copy external contacts if same company + if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { + $error++; + } + } + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines = array(); + + $result = $this->fetchLinesCommon(); + return $result; + } + + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return array|int int <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = "SELECT "; + $sql .= $this->getFieldList('t'); + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($this->table_element).")"; + } else { + $sql .= " WHERE 1 = 1"; + } + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid') { + $sqlwhere[] = $key." = ".((int) $value); + } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) { + $sqlwhere[] = $key." = '".$this->db->idate($value)."'"; + } elseif ($key == 'customsql') { + $sqlwhere[] = $value; + } elseif (strpos($value, '%') === false) { + $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")"; + } else { + $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'"; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")"; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= $this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + //return $this->deleteCommon($user, $notrigger, 1); + } + + /** + * Delete a line of object in database + * + * @param User $user User that delete + * @param int $idline Id of line to delete + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $idline, $notrigger = false) + { + if ($this->status < 0) { + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; + return -2; + } + + return $this->deleteLineCommon($user, $idline, $notrigger); + } + + + /** + * Validate object + * + * @param User $user User making status change + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <=0 if OK, 0=Nothing done, >0 if KO + */ + public function validate($user, $notrigger = 0) + { + global $conf, $langs; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $error = 0; + + // Protection + if ($this->status == self::STATUS_VALIDATED) { + dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->target->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->target->target_advance->validate)))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ + + $now = dol_now(); + + $this->db->begin(); + + // Define new ref + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life + $num = $this->getNextNumRef(); + } else { + $num = $this->ref; + } + $this->newref = $num; + + if (!empty($num)) { + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " status = ".self::STATUS_VALIDATED; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."'"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".((int) $user->id); + } + $sql .= " WHERE rowid = ".((int) $this->id); + + dol_syslog(get_class($this)."::validate()", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + dol_print_error($this->db); + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('TARGET_VALIDATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } + + if (!$error) { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) { + // Now we rename also files into index + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'target/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->webhook->dir_output.'/target/'.$oldref; + $dirdest = $conf->webhook->dir_output.'/target/'.$newref; + if (!$error && file_exists($dirsource)) { + dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); + + if (@rename($dirsource, $dirdest)) { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->webhook->dir_output.'/target/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } + + // Set new ref and current status + if (!$error) { + $this->ref = $num; + $this->status = self::STATUS_VALIDATED; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, >0 if OK + */ + public function setDraft($user, $notrigger = 0) + { + // Protection + if ($this->status <= self::STATUS_DRAFT) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->webhook_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'TARGET_UNVALIDATE'); + } + + /** + * Set cancel status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function cancel($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_VALIDATED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->webhook_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'TARGET_CANCEL'); + } + + /** + * Set back to validated status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function reopen($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_CANCELED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->webhook_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'TARGET_REOPEN'); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $conf, $langs, $hookmanager; + + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } + + $result = ''; + + $label = img_picto('', $this->picto).' '.$langs->trans("Target").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; + + $url = dol_buildpath('/webhook/target_card.php', 1).'?id='.$this->id; + + if ($option != 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($url && $add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } + } + + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowTarget"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } + + if ($option == 'nolink' || empty($url)) { + $linkstart = ''; + if ($option == 'nolink' || empty($url)) { + $linkend = ''; + } else { + $linkend = ''; + } + + $result .= $linkstart; + + if (empty($this->showphoto_on_popup)) { + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + } else { + if ($withpicto) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + list($class, $module) = explode('@', $this->picto); + $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref); + $filearray = dol_dir_list($upload_dir, "files"); + $filename = $filearray[0]['name']; + if (!empty($filename)) { + $pospoint = strpos($filearray[0]['name'], '.'); + + $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint); + if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) { + $result .= '
    No photo
    '; + } else { + $result .= '
    No photo
    '; + } + + $result .= '
    '; + } else { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + } + } + + if ($withpicto != 2) { + $result .= $this->ref; + } + + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + global $action, $hookmanager; + $hookmanager->initHooks(array('targetdao')); + $parameters = array('id'=>$this->id, 'getnomurl' => &$result); + $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } + + return $result; + } + + /** + * Return the label of the status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLabelStatus($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + /** + * Return the label of the status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("webhook@webhook"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled'); + } + + $statusType = 'status'.$status; + //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; + if ($status == self::STATUS_CANCELED) { + $statusType = 'status6'; + } + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } + + /** + * Load the info information in the object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + $sql = "SELECT rowid, date_creation as datec, tms as datem,"; + $sql .= " fk_user_creat, fk_user_modif"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " WHERE t.rowid = ".((int) $id); + + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if (!empty($obj->fk_user_author)) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if (!empty($obj->fk_user_valid)) { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if (!empty($obj->fk_user_cloture)) { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + // Set here init that are not commonf fields + // $this->property1 = ... + // $this->property2 = ... + + $this->initAsSpecimenCommon(); + } + + /** + * Create an array of lines + * + * @return array|int array of lines if OK, <0 if KO + */ + public function getLinesArray() + { + $this->lines = array(); + + $objectline = new TargetLine($this->db); + $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_target = '.((int) $this->id))); + + if (is_numeric($result)) { + $this->error = $this->error; + $this->errors = $this->errors; + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Returns the reference to the following non used object depending on the active numbering module. + * + * @return string Object free reference + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("webhook@webhook"); + + if (empty($conf->global->WEBHOOK_TARGET_ADDON)) { + $conf->global->WEBHOOK_TARGET_ADDON = 'mod_target_standard'; + } + + if (!empty($conf->global->WEBHOOK_TARGET_ADDON)) { + $mybool = false; + + $file = $conf->global->WEBHOOK_TARGET_ADDON.".php"; + $classname = $conf->global->WEBHOOK_TARGET_ADDON; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/webhook/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + if (class_exists($classname)) { + $obj = new $classname(); + $numref = $obj->getNextValue($this); + + if ($numref != '' && $numref != '-1') { + return $numref; + } else { + $this->error = $obj->error; + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return ""; + } + } else { + print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname; + return ""; + } + } else { + print $langs->trans("ErrorNumberingModuleNotSetup", $this->element); + return ""; + } + } + + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; + + $result = 0; + $includedocgeneration = 0; + + $langs->load("webhook@webhook"); + + if (!dol_strlen($modele)) { + $modele = 'standard_target'; + + if (!empty($this->model_pdf)) { + $modele = $this->model_pdf; + } elseif (!empty($conf->global->TARGET_ADDON_PDF)) { + $modele = $conf->global->TARGET_ADDON_PDF; + } + } + + $modelpath = "core/modules/webhook/doc/"; + + if ($includedocgeneration && !empty($modele)) { + $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } + + return $result; + } + + /** + * Action executed by scheduler + * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters' + * Use public function doScheduledJob($param1, $param2, ...) to get parameters + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; + + $error = 0; + $this->output = ''; + $this->error = ''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $now = dol_now(); + + $this->db->begin(); + + // ... + + $this->db->commit(); + + return $error; + } +} + + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; + +/** + * Class TargetLine. You can also remove this and generate a CRUD class for lines objects. + */ +class TargetLine extends CommonObjectLine +{ + // To complete with content of an object TargetLine + // We should have a field rowid, fk_target and position + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } +} diff --git a/htdocs/webhook/class/target.class.php.back b/htdocs/webhook/class/target.class.php.back new file mode 100644 index 00000000000..acb40530bc1 --- /dev/null +++ b/htdocs/webhook/class/target.class.php.back @@ -0,0 +1,1090 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/target.class.php + * \ingroup webhook + * \brief This file is a CRUD class file for Target (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for Target + */ +class Target extends CommonObject +{ + /** + * @var string ID of module. + */ + public $module = 'webhook'; + + /** + * @var string ID to identify managed object. + */ + public $element = 'target'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'webhook_target'; + + /** + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table + */ + public $ismultientitymanaged = 0; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * @var string String with name of icon for target. Must be the part after the 'object_' into object_target.png + */ + public $picto = 'webhook'; + + + const STATUS_DRAFT = 0; + const STATUS_VALIDATED = 1; + const STATUS_CANCELED = 9; + + + /** + * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or '!empty($conf->multicurrency->enabled)' ...) + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage) + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200' + * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar' + * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1. + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'validate' is 1 if need to validate with $this->validateField() + * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value) + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'index'=>1, 'searchall'=>1, 'validate'=>'1', 'comment'=>"Reference of object"), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'help'=>"Help text", 'showoncombobox'=>'2', 'validate'=>'1',), + 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3, 'validate'=>'1',), + 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak', 'validate'=>'1',), + 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak', 'validate'=>'1',), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,), + 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',), + 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,), + 'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>'1', 'position'=>600, 'notnull'=>0, 'visible'=>0,), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,), + 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>'1', 'position'=>2000, 'notnull'=>1, 'visible'=>3, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validé', '9'=>'Annulé'), 'validate'=>'1',), + 'url' => array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1,), + 'trigger_codes' => array('type'=>'text', 'label'=>'TriggerCodes', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1, 'help'=>"TriggerCodeInfo",), + ); + public $rowid; + public $ref; + public $label; + public $description; + public $note_public; + public $note_private; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $last_main_doc; + public $import_key; + public $status; + public $url; + public $trigger_codes; + // END MODULEBUILDER PROPERTIES + + + // If this object has a subtable with lines + + // /** + // * @var string Name of subtable line + // */ + // public $table_element_line = 'webhook_targetline'; + + // /** + // * @var string Field with ID of parent key if this object has a parent + // */ + // public $fk_element = 'fk_target'; + + // /** + // * @var string Name of subtable class that manage subtable lines + // */ + // public $class_element_line = 'Targetline'; + + // /** + // * @var array List of child tables. To test if we can delete object. + // */ + // protected $childtables = array(); + + // /** + // * @var array List of child tables. To know object to delete on cascade. + // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will + // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object + // */ + // protected $childtablesoncascade = array('webhook_targetdet'); + + // /** + // * @var TargetLine[] Array of subtable lines + // */ + // public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } + + // Example to show how to set values of fields definition dynamically + /*if ($user->rights->webhook->target->read) { + $this->fields['myfield']['visible'] = 1; + $this->fields['myfield']['noteditable'] = 0; + }*/ + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + $resultcreate = $this->createCommon($user, $notrigger); + $this->ref = $this->id; + + if ($resultcreate <= 0) { + return $resultcreate; + } + $resultvalidate = $this->validate($user, $notrigger); + + return $resultvalidate; + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } + + // get lines so they will be clone + //foreach($this->lines as $line) + // $line->fetch_optionals(); + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + if (property_exists($object, 'ref')) { + $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default']; + } + if (property_exists($object, 'label')) { + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + } + if (property_exists($object, 'status')) { + $object->status = self::STATUS_DRAFT; + } + if (property_exists($object, 'date_creation')) { + $object->date_creation = dol_now(); + } + if (property_exists($object, 'date_modification')) { + $object->date_modification = null; + } + // ... + // Clear extrafields that are unique + if (is_array($object->array_options) && count($object->array_options) > 0) { + $extrafields->fetch_name_optionals_label($this->table_element); + foreach ($object->array_options as $key => $option) { + $shortkey = preg_replace('/options_/', '', $key); + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { + //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; + unset($object->array_options[$key]); + } + } + } + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + if (!$error) { + // copy internal contacts + if ($this->copy_linked_contact($object, 'internal') < 0) { + $error++; + } + } + + if (!$error) { + // copy external contacts if same company + if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { + $error++; + } + } + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines = array(); + + $result = $this->fetchLinesCommon(); + return $result; + } + + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return array|int int <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = "SELECT "; + $sql .= $this->getFieldList('t'); + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($this->table_element).")"; + } else { + $sql .= " WHERE 1 = 1"; + } + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid') { + $sqlwhere[] = $key." = ".((int) $value); + } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) { + $sqlwhere[] = $key." = '".$this->db->idate($value)."'"; + } elseif ($key == 'customsql') { + $sqlwhere[] = $value; + } elseif (strpos($value, '%') === false) { + $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")"; + } else { + $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'"; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")"; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= $this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + //return $this->deleteCommon($user, $notrigger, 1); + } + + /** + * Delete a line of object in database + * + * @param User $user User that delete + * @param int $idline Id of line to delete + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $idline, $notrigger = false) + { + if ($this->status < 0) { + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; + return -2; + } + + return $this->deleteLineCommon($user, $idline, $notrigger); + } + + + /** + * Validate object + * + * @param User $user User making status change + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <=0 if OK, 0=Nothing done, >0 if KO + */ + public function validate($user, $notrigger = 0) + { + global $conf, $langs; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $error = 0; + + // Protection + if ($this->status == self::STATUS_VALIDATED) { + dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->target->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->target->target_advance->validate)))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ + + $now = dol_now(); + + $this->db->begin(); + + // Define new ref + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life + $num = $this->getNextNumRef(); + } else { + $num = $this->ref; + } + $this->newref = $num; + + if (!empty($num)) { + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " status = ".self::STATUS_VALIDATED; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation = '".$this->db->idate($now)."'"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid = ".((int) $user->id); + } + $sql .= " WHERE rowid = ".((int) $this->id); + + dol_syslog(get_class($this)."::validate()", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + dol_print_error($this->db); + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('TARGET_VALIDATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } + + if (!$error) { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) { + // Now we rename also files into index + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'target/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'target/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->webhook->dir_output.'/target/'.$oldref; + $dirdest = $conf->webhook->dir_output.'/target/'.$newref; + if (!$error && file_exists($dirsource)) { + dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); + + if (@rename($dirsource, $dirdest)) { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->webhook->dir_output.'/target/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } + + // Set new ref and current status + if (!$error) { + $this->ref = $num; + $this->status = self::STATUS_VALIDATED; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, >0 if OK + */ + public function setDraft($user, $notrigger = 0) + { + // Protection + if ($this->status <= self::STATUS_DRAFT) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->webhook_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'TARGET_UNVALIDATE'); + } + + /** + * Set cancel status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function cancel($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_VALIDATED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->webhook_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'TARGET_CANCEL'); + } + + /** + * Set back to validated status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function reopen($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_CANCELED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->webhook->webhook_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'TARGET_REOPEN'); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $conf, $langs, $hookmanager; + + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } + + $result = ''; + + $label = img_picto('', $this->picto).' '.$langs->trans("Target").''; + if (isset($this->status)) { + $label .= ' '.$this->getLibStatut(5); + } + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; + + $url = dol_buildpath('/webhook/target_card.php', 1).'?id='.$this->id; + + if ($option != 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($url && $add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } + } + + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowTarget"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } + + if ($option == 'nolink' || empty($url)) { + $linkstart = ''; + if ($option == 'nolink' || empty($url)) { + $linkend = ''; + } else { + $linkend = ''; + } + + $result .= $linkstart; + + if (empty($this->showphoto_on_popup)) { + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + } else { + if ($withpicto) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + list($class, $module) = explode('@', $this->picto); + $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref); + $filearray = dol_dir_list($upload_dir, "files"); + $filename = $filearray[0]['name']; + if (!empty($filename)) { + $pospoint = strpos($filearray[0]['name'], '.'); + + $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint); + if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) { + $result .= '
    No photo
    '; + } else { + $result .= '
    No photo
    '; + } + + $result .= '
    '; + } else { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + } + } + + if ($withpicto != 2) { + $result .= $this->ref; + } + + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + global $action, $hookmanager; + $hookmanager->initHooks(array('targetdao')); + $parameters = array('id'=>$this->id, 'getnomurl' => &$result); + $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } + + return $result; + } + + /** + * Return the label of the status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLabelStatus($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + /** + * Return the label of the status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("webhook@webhook"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled'); + } + + $statusType = 'status'.$status; + //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; + if ($status == self::STATUS_CANCELED) { + $statusType = 'status6'; + } + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } + + /** + * Load the info information in the object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + $sql = "SELECT rowid, date_creation as datec, tms as datem,"; + $sql .= " fk_user_creat, fk_user_modif"; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " WHERE t.rowid = ".((int) $id); + + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if (!empty($obj->fk_user_author)) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if (!empty($obj->fk_user_valid)) { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if (!empty($obj->fk_user_cloture)) { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + // Set here init that are not commonf fields + // $this->property1 = ... + // $this->property2 = ... + + $this->initAsSpecimenCommon(); + } + + /** + * Create an array of lines + * + * @return array|int array of lines if OK, <0 if KO + */ + public function getLinesArray() + { + $this->lines = array(); + + $objectline = new TargetLine($this->db); + $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_target = '.((int) $this->id))); + + if (is_numeric($result)) { + $this->error = $this->error; + $this->errors = $this->errors; + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Returns the reference to the following non used object depending on the active numbering module. + * + * @return string Object free reference + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("webhook@webhook"); + + if (empty($conf->global->WEBHOOK_TARGET_ADDON)) { + $conf->global->WEBHOOK_TARGET_ADDON = 'mod_target_standard'; + } + + if (!empty($conf->global->WEBHOOK_TARGET_ADDON)) { + $mybool = false; + + $file = $conf->global->WEBHOOK_TARGET_ADDON.".php"; + $classname = $conf->global->WEBHOOK_TARGET_ADDON; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/webhook/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + if (class_exists($classname)) { + $obj = new $classname(); + $numref = $obj->getNextValue($this); + + if ($numref != '' && $numref != '-1') { + return $numref; + } else { + $this->error = $obj->error; + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return ""; + } + } else { + print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname; + return ""; + } + } else { + print $langs->trans("ErrorNumberingModuleNotSetup", $this->element); + return ""; + } + } + + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; + + $result = 0; + $includedocgeneration = 0; + + $langs->load("webhook@webhook"); + + if (!dol_strlen($modele)) { + $modele = 'standard_target'; + + if (!empty($this->model_pdf)) { + $modele = $this->model_pdf; + } elseif (!empty($conf->global->TARGET_ADDON_PDF)) { + $modele = $conf->global->TARGET_ADDON_PDF; + } + } + + $modelpath = "core/modules/webhook/doc/"; + + if ($includedocgeneration && !empty($modele)) { + $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } + + return $result; + } + + /** + * Action executed by scheduler + * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters' + * Use public function doScheduledJob($param1, $param2, ...) to get parameters + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; + + $error = 0; + $this->output = ''; + $this->error = ''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $now = dol_now(); + + $this->db->begin(); + + // ... + + $this->db->commit(); + + return $error; + } +} + + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; + +/** + * Class TargetLine. You can also remove this and generate a CRUD class for lines objects. + */ +class TargetLine extends CommonObjectLine +{ + // To complete with content of an object TargetLine + // We should have a field rowid, fk_target and position + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } +} diff --git a/htdocs/webhook/lib/webhook.lib.php b/htdocs/webhook/lib/webhook.lib.php new file mode 100644 index 00000000000..6c511180b6e --- /dev/null +++ b/htdocs/webhook/lib/webhook.lib.php @@ -0,0 +1,70 @@ + + * + * 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 webhook/lib/webhook.lib.php + * \ingroup webhook + * \brief Library files with common functions for Webhook + */ + +/** + * Prepare admin pages header + * + * @return array + */ +function webhookAdminPrepareHead() +{ + global $langs, $conf; + + $langs->load("webhook@webhook"); + + $h = 0; + $head = array(); + $head[$h][0] = dol_buildpath("/admin/webhook.php", 1); + $head[$h][1] = $langs->trans("Miscellaneous"); + $head[$h][2] = 'settings'; + $h++; + + $head[$h][0] = dol_buildpath("/webhook/target_list.php?mode=modulesetup", 1); + $head[$h][1] = $langs->trans("Targets"); + $head[$h][2] = 'targets'; + $h++; + + + /* + $head[$h][0] = dol_buildpath("/webhook/admin/myobject_extrafields.php", 1); + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'myobject_extrafields'; + $h++; + */ + + + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@webhook:/webhook/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@webhook:/webhook/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'webhook@webhook'); + + complete_head_from_modules($conf, $langs, null, $head, $h, 'webhook@webhook', 'remove'); + + return $head; +} diff --git a/htdocs/webhook/lib/webhook_target.lib.php b/htdocs/webhook/lib/webhook_target.lib.php new file mode 100644 index 00000000000..fb01a8f95aa --- /dev/null +++ b/htdocs/webhook/lib/webhook_target.lib.php @@ -0,0 +1,91 @@ +. + */ + +/** + * \file lib/webhook_target.lib.php + * \ingroup webhook + * \brief Library files with common functions for Target + */ +/** + * Prepare array of tabs for Target + * + * @param Target $object Target + * @return array Array of tabs + */ +function targetPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("webhook@webhook"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/webhook/target_card.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { + $nbNote = 0; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } + $head[$h][0] = dol_buildpath('/webhook/target_note.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbNote.'' : ''); + } + $head[$h][2] = 'note'; + $h++; + } + + /*require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->webhook->dir_output."/target/".dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = dol_buildpath("/webhook/target_document.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } + $head[$h][2] = 'document'; + $h++;*/ + + /*$head[$h][0] = dol_buildpath("/webhook/target_agenda.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Events"); + $head[$h][2] = 'agenda'; + $h++;*/ + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@webhook:/webhook/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@webhook:/webhook/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'target@webhook'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'target@webhook', 'remove'); + + return $head; +} diff --git a/htdocs/webhook/modulebuilder.txt b/htdocs/webhook/modulebuilder.txt new file mode 100644 index 00000000000..670a1774929 --- /dev/null +++ b/htdocs/webhook/modulebuilder.txt @@ -0,0 +1,3 @@ +# DO NOT DELETE THIS FILE MANUALLY +# File to flag module built using official module template. +# When this file is present into a module directory, you can edit it with the module builder tool. \ No newline at end of file diff --git a/htdocs/webhook/target_agenda.php b/htdocs/webhook/target_agenda.php new file mode 100644 index 00000000000..12b6e67c57b --- /dev/null +++ b/htdocs/webhook/target_agenda.php @@ -0,0 +1,315 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file target_agenda.php + * \ingroup webhook + * \brief Tab of events on Target + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +dol_include_once('/webhook/class/target.class.php'); +dol_include_once('/webhook/lib/webhook_target.lib.php'); + + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "other")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +if (GETPOST('actioncode', 'array')) { + $actioncode = GETPOST('actioncode', 'array', 3); + if (!count($actioncode)) { + $actioncode = '0'; + } +} else { + $actioncode = GETPOST("actioncode", "alpha", 3) ? GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); +} +$search_agenda_label = GETPOST('search_agenda_label'); + +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} + +// Initialize technical objects +$object = new Target($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('targetagenda', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->webhook->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity]."/".$object->id; +} + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$enablepermissioncheck = 0; +if ($enablepermissioncheck) { + $permissiontoread = $user->rights->webhook->target->read; + $permissiontoadd = $user->rights->webhook->target->write; +} else { + $permissiontoread = 1; + $permissiontoadd = 1; +} + +// Security check (enable the most restrictive one) +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft); +if (empty($conf->webhook->enabled)) accessforbidden(); +if (!$permissiontoread) accessforbidden(); + + +/* + * Actions + */ + +$parameters = array('id'=>$id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + // Cancel + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { + header("Location: ".$backtopage); + exit; + } + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + $actioncode = ''; + $search_agenda_label = ''; + } +} + + + +/* + * View + */ + +$form = new Form($db); + +if ($object->id > 0) { + $title = $langs->trans("Agenda"); + //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; + $help_url = 'EN:Module_Agenda_En'; + llxHeader('', $title, $help_url); + + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } + $head = targetPrepareHead($object); + + + print dol_get_fiche_head($head, 'agenda', $langs->trans("Target"), -1, $object->picto); + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) { + if ($action != 'classify') { + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + } + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + + $object->info($object->id); + dol_print_object_info($object, 1); + + print '
    '; + + print dol_get_fiche_end(); + + + + // Actions buttons + + $objthirdparty = $object; + $objcon = new stdClass(); + + $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.=""; + } + + + print '
    '; + + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { + print ''.$langs->trans("AddAction").''; + } else { + print ''.$langs->trans("AddAction").''; + } + } + + print '
    '; + + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { + $param = '&id='.$object->id.'&socid='.$socid; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + + + //print load_fiche_titre($langs->trans("ActionsOnTarget"), '', ''); + + // List of all actions + $filters = array(); + $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, $object->module); + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/target_card.php b/htdocs/webhook/target_card.php new file mode 100644 index 00000000000..dd0d5e171e8 --- /dev/null +++ b/htdocs/webhook/target_card.php @@ -0,0 +1,618 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file target_card.php + * \ingroup webhook + * \brief Page to create/edit/view target + */ + +//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 (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +//if (! defined('NOSESSION')) define('NOSESSION', '1'); // Disable session + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +dol_include_once('/webhook/class/target.class.php'); +dol_include_once('/webhook/lib/webhook_target.lib.php'); + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "other")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'targetcard'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); +$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); +$lineid = GETPOST('lineid', 'int'); + +// Initialize technical objects +$object = new Target($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('targetcard', 'globalcard')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Initialize array of search criterias +$search_all = GETPOST("search_all", 'alpha'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } +} + +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$enablepermissioncheck = 0; +if ($enablepermissioncheck) { + $permissiontoread = $user->rights->webhook->target->read; + $permissiontoadd = $user->rights->webhook->target->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php + $permissiontodelete = $user->rights->webhook->target->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); + $permissionnote = $user->rights->webhook->target->write; // Used by the include of actions_setnotes.inc.php + $permissiondellink = $user->rights->webhook->target->write; // Used by the include of actions_dellink.inc.php +} else { + $permissiontoread = 1; + $permissiontoadd = 1; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php + $permissiontodelete = 1; + $permissionnote = 1; + $permissiondellink = 1; +} + +$upload_dir = $conf->webhook->multidir_output[isset($object->entity) ? $object->entity : 1].'/target'; + +// Security check (enable the most restrictive one) +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (isset($object->status) && ($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft); +if (empty($conf->webhook->enabled)) accessforbidden(); +if (!$permissiontoread) accessforbidden(); + + +/* + * Actions + */ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + $error = 0; + + $backurlforlist = dol_buildpath('/webhook/target_list.php?mode=modulesetup', 1); + + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/webhook/target_card.php', 1).'?id='.((!empty($id) && $id > 0) ? $id : '__ID__'); + } + } + } + + $triggermodname = 'WEBHOOK_TARGET_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 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'; + + // Action to move up and down lines of object + //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; + + // Action to build doc + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + if ($action == 'set_thirdparty' && $permissiontoadd) { + $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, $triggermodname); + } + if ($action == 'classin' && $permissiontoadd) { + $object->setProject(GETPOST('projectid', 'int')); + } + + // Actions to send emails + $triggersendname = 'WEBHOOK_TARGET_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_TARGET_TO'; + $trackid = 'target'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; +} + + + + +/* + * View + * + * Put here all code to build page + */ + +$form = new Form($db); +$formfile = new FormFile($db); +$formproject = new FormProjets($db); + +$title = $langs->trans("Target"); +$help_url = ''; +llxHeader('', $title, $help_url); + +// Example : Adding jquery code +// print ''; + + +// Part to create +if ($action == 'create') { + if (empty($permissiontoadd)) { + accessforbidden($langs->trans('NotEnoughPermissions'), 0, 1); + exit; + } + + print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Target")), '', 'object_'.$object->picto); + + print '
    '; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(array(), ''); + + // Set some default values + //if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue'; + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; + + print '
    '."\n"; + + print dol_get_fiche_end(); + + print $form->buttonsSaveCancel("Create"); + + print '
    '; + + //dol_set_focus('input[name="ref"]'); +} + +// Part to edit record +if (($id || $ref) && $action == 'edit') { + print load_fiche_titre($langs->trans("Target"), '', 'object_'.$object->picto); + + print '
    '; + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; + + print '
    '; + + print dol_get_fiche_end(); + + print $form->buttonsSaveCancel(); + + print '
    '; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $res = $object->fetch_optionals(); + + $head = targetPrepareHead($object); + print dol_get_fiche_head($head, 'card', $langs->trans("Target"), -1, $object->picto); + + $formconfirm = ''; + + // Confirmation to delete + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteTarget'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); + } + // Confirmation to delete line + if ($action == 'deleteline') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); + } + + // Clone confirmation + if ($action == 'clone') { + // Create an array for form + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } + + // Confirmation of action xxxx (You can use it for xxx = 'close', xxx = 'reopen', ...) + if ($action == 'xxx') { + $text = $langs->trans('ConfirmActionTarget', $object->ref); + /*if (! empty($conf->notification->enabled)) + { + require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + $notify = new Notify($db); + $text .= '
    '; + $text .= $notify->confirmMessage('TARGET_CLOSE', $object->socid, $object); + }*/ + + $formquestion = array(); + /* + $forcecombo=0; + if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $formquestion = array( + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + ); + */ + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + } + + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) { + //if ($action != 'classify') $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' '; + $morehtmlref .= ' : '; + if ($action == 'classify') { + //$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + print ''."\n"; + + // Common attributes + //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field + //unset($object->fields['fk_project']); // Hide field already shown in banner + //unset($object->fields['fk_soc']); // Hide field already shown in banner + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; + + // Other attributes. Fields from hook formObjectOptions and Extrafields. + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + + print dol_get_fiche_end(); + + + /* + * Lines + */ + + if (!empty($object->table_element_line)) { + // Show object lines + $result = $object->getLinesArray(); + + print '
    + + + + + + '; + + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; + } + + print '
    '; + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { + print ''; + } + + if (!empty($object->lines)) { + $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); + } + + // Form to add new line + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { + // Add products/services form + + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $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)) + $object->formAddObjectLine(1, $mysoc, $soc); + } + } + + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { + print '
    '; + } + print '
    '; + + print "
    \n"; + } + + + // Buttons for actions + + if ($action != 'presend' && $action != 'editline') { + print '
    '."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } + + if (empty($reshook)) { + // Send + if (empty($user->socid)) { + print dolGetButtonAction($langs->trans('SendMail'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init&token='.newToken().'#formmailbeforetitle'); + } + + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) { + print dolGetButtonAction($langs->trans('SetToDraft'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes&token='.newToken(), '', $permissiontoadd); + } + + print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&token='.newToken(), '', $permissiontoadd); + + // Validate + if ($object->status == $object::STATUS_DRAFT) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { + print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes&token='.newToken(), '', $permissiontoadd); + } else { + $langs->load("errors"); + print dolGetButtonAction($langs->trans("ErrorAddAtLeastOneLineFirst"), $langs->trans("Validate"), 'default', '#', '', 0); + } + } + + // Clone + print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.(!empty($object->socid)?'&socid='.$object->socid:'').'&action=clone&token='.newToken(), '', $permissiontoadd); + + /* + if ($permissiontoadd) { + if ($object->status == $object::STATUS_ENABLED) { + print dolGetButtonAction($langs->trans('Disable'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=disable&token='.newToken(), '', $permissiontoadd); + } else { + print dolGetButtonAction($langs->trans('Enable'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=enable&token='.newToken(), '', $permissiontoadd); + } + } + if ($permissiontoadd) { + if ($object->status == $object::STATUS_VALIDATED) { + print dolGetButtonAction($langs->trans('Cancel'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close&token='.newToken(), '', $permissiontoadd); + } else { + print dolGetButtonAction($langs->trans('Re-Open'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken(), '', $permissiontoadd); + } + } + */ + + // Delete (need delete permission, or if draft, just need create/modify permission) + print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete&token='.newToken(), '', $permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)); + } + print '
    '."\n"; + } + + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') { + print '
    '; + print ''; // ancre + + $includedocgeneration = 0; + + // Documents + if ($includedocgeneration) { + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->webhook->dir_output.'/'.$object->element.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $permissiontoread; // If you can read, you can build the PDF to read content + $delallowed = $permissiontoadd; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('webhook:Target', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); + } + + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('target')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + + + print '
    '; + + $MAXEVENT = 10; + + $morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-list-alt imgforviewmode', dol_buildpath('/webhook/target_agenda.php', 1).'?id='.$object->id); + + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, $object->element.'@'.$object->module, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlcenter); + + print '
    '; + } + + //Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + // Presend form + $modelmail = 'target'; + $defaulttopic = 'InformationMessage'; + $diroutput = $conf->webhook->dir_output; + $trackid = 'target'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/target_contact.php b/htdocs/webhook/target_contact.php new file mode 100644 index 00000000000..94c906969aa --- /dev/null +++ b/htdocs/webhook/target_contact.php @@ -0,0 +1,226 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file target_contact.php + * \ingroup webhook + * \brief Tab for contacts linked to Target + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +dol_include_once('/webhook/class/target.class.php'); +dol_include_once('/webhook/lib/webhook_target.lib.php'); + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "companies", "other", "mails")); + +$id = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility +$ref = GETPOST('ref', 'alpha'); +$lineid = GETPOST('lineid', 'int'); +$socid = GETPOST('socid', 'int'); +$action = GETPOST('action', 'aZ09'); + +// Initialize technical objects +$object = new Target($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('targetcontact', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$enablepermissioncheck = 0; +if ($enablepermissioncheck) { + $permissiontoread = $user->rights->webhook->target->read; + $permission = $user->rights->webhook->target->write; +} else { + $permissiontoread = 1; + $permission = 1; +} + +// Security check (enable the most restrictive one) +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft); +if (empty($conf->webhook->enabled)) accessforbidden(); +if (!$permissiontoread) accessforbidden(); + + +/* + * Add a new contact + */ + +if ($action == 'addcontact' && $permission) { + $contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } +} elseif ($action == 'swapstatut' && $permission) { + // Toggle the status of a contact + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); +} elseif ($action == 'deletecontact' && $permission) { + // Deletes a contact + $result = $object->delete_contact($lineid); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + dol_print_error($db); + } +} + + +/* + * View + */ + +$title = $langs->trans('Target')." - ".$langs->trans('ContactsAddresses'); +$help_url = ''; +//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +llxHeader('', $title, $help_url); + +$form = new Form($db); +$formcompany = new FormCompany($db); +$contactstatic = new Contact($db); +$userstatic = new User($db); + + +/* *************************************************************************** */ +/* */ +/* View and edit mode */ +/* */ +/* *************************************************************************** */ + +if ($object->id) { + /* + * Show tabs + */ + $head = targetPrepareHead($object); + + print dol_get_fiche_head($head, 'contact', $langs->trans("Target"), -1, $object->picto); + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + + print dol_get_fiche_end(); + + print '
    '; + + // Contacts lines (modules that overwrite templates must declare this into descriptor) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { + $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); + if ($res) { + break; + } + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/target_list.php b/htdocs/webhook/target_list.php new file mode 100644 index 00000000000..e62969e62ea --- /dev/null +++ b/htdocs/webhook/target_list.php @@ -0,0 +1,813 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file target_list.php + * \ingroup webhook + * \brief List page for target + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +//if (! defined('NOSESSION')) define('NOSESSION', '1'); // On CLI mode, no need to use web sessions + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + +// load webhook libraries +require_once __DIR__.'/class/target.class.php'; + +// for other modules +//dol_include_once('/othermodule/class/otherobject.class.php'); + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "other")); + +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'targetlist'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$mode = GETPOST('mode', 'aZ'); + +$id = GETPOST('id', 'int'); + +// Load variable for pagination +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + // If $page is not defined, or '' or -1 or if we click on clear filters + $page = 0; +} +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object = new Target($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('targetlist')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + reset($object->fields); // Reset is required to avoid key() to return null. + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} + +// Initialize array of search criterias +$search_all = GETPOST('search_all', 'alphanohtml'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int')); + } +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach ($object->fields as $key => $val) { + if (!empty($val['searchall'])) { + $fieldstosearchall['t.'.$key] = $val['label']; + } +} + +// Definition of array of fields for columns +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval($val['visible'], 1); + $arrayfields['t.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($visible < 0) ? 0 : 1), + 'enabled'=>(abs($visible) != 3 && dol_eval($val['enabled'], 1)), + 'position'=>$val['position'], + 'help'=> isset($val['help']) ? $val['help'] : '' + ); + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +$object->fields = dol_sort_array($object->fields, 'position'); +//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$enablepermissioncheck = 0; +if ($enablepermissioncheck) { + $permissiontoread = $user->rights->webhook->target->read; + $permissiontoadd = $user->rights->webhook->target->write; + $permissiontodelete = $user->rights->webhook->target->delete; +} else { + $permissiontoread = 1; + $permissiontoadd = 1; + $permissiontodelete = 1; +} + +// Security check (enable the most restrictive one) +if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) accessforbidden(); +//$socid = 0; if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->element, 0, $object->table_element, '', 'fk_soc', 'rowid', $isdraft); +if (empty($conf->webhook->enabled)) accessforbidden('Module not enabled'); +if (!$permissiontoread) accessforbidden(); + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + foreach ($object->fields as $key => $val) { + $search[$key] = ''; + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = ''; + $search[$key.'_dtend'] = ''; + } + } + $toselect = array(); + $search_array_options = array(); + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass = 'Target'; + $objectlabel = 'Target'; + $uploaddir = $conf->webhook->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + + +/* + * View + */ + +$form = new Form($db); + +$now = dol_now(); +//$help_url = "EN:Module_Target|FR:Module_Target_FR|ES:Módulo_Target"; +$help_url = ''; +$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Targets")); +$morejs = array(); +$morecss = array(); + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +$sql .= $object->getFieldList('t'); +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : ''); + } +} +// Add fields from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); +$sql = preg_replace('/,\s*$/', '', $sql); +//$sql .= ", COUNT(rc.rowid) as anotherfield"; +$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; +//$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."anothertable as rc ON rc.parent = t.rowid"; +if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +// Add table from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if (array_key_exists($key, $object->fields)) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) { + if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval'])))) { + $search[$key] = ''; + } + $mode_search = 2; + } + if ($search[$key] != '') { + $sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } else { + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key); + if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND t.".$db->escape($columnName)." >= '".$db->idate($search[$key])."'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND t.".$db->escape($columnName)." <= '".$db->idate($search[$key])."'"; + } + } + } + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + +/* If a group by is required +$sql .= " GROUP BY "; +foreach($object->fields as $key => $val) { + $sql .= "t.".$db->escape($key).", "; +} +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); + } +} +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/,\s*$/', '', $sql); +*/ + +// Add HAVING from hooks +/* +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint; +*/ + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + /* This old and fast method to get and count full list returns all record so use a high amount of memory. + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); + */ + /* The slow method does not consume memory on mysql (not tested on pgsql) */ + /*$resql = $db->query($sql, 0, 'auto', 1); + while ($db->fetch_object($resql)) { + if (empty($nbtotalofrecords)) { + $nbtotalofrecords = 1; // We can't make +1 because init value is '' + } else { + $nbtotalofrecords++; + } + }*/ + /* The fast and low memory method to get and count full list converts the sql into a sql count */ + $sqlforcount = preg_replace('/^SELECT[a-zA-Z0-9\._\s\(\),=<>\:\-\']+\sFROM/', 'SELECT COUNT(*) as nbtotalofrecords FROM', $sql); + $resql = $db->query($sqlforcount); + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + + if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 + $page = 0; + $offset = 0; + } + $db->free($resql); +} + +// Complete request and execute it with limit +$sql .= $db->order($sortfield, $sortorder); +if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); +} + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + + +// Direct jump if only one record found +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".dol_buildpath('/webhook/target_card.php', 1).'?id='.$id); + exit; +} + + +// Output page +// -------------------------------------------------------------------- +$title = $langs->trans("Targets"); +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', ''); + +if ($mode == 'modulesetup') { + require_once 'lib/webhook.lib.php'; + + $help_url = ''; + $page_name = "WebhookSetup"; + // Subheader + $linkback = ''.$langs->trans("BackToModuleList").''; + print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); + + $head = webhookAdminPrepareHead(); + print dol_get_fiche_head($head, 'targets', $langs->trans($page_name), -1, "webhook@webhook"); +} + +// Example : Adding jquery code +// print ''; + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$param = ''; +if (!empty($mode)) { + $param .= '&mode='.urlencode($mode); +} +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + if ($skey != '') { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } + } elseif ($search[$key] != '') { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +// Add $param from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook +$param .= $hookmanager->resPrint; + +// List of mass actions available +$arrayofmassactions = array( + //'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"), + //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"), + //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"), + //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"), +); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '
    '."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + + +$newcardbutton = ''; +//$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/^&mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); +//$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-list-alt imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/^&mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); +//$newcardbutton .= dolGetButtonTitleSeparator(); +$newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/webhook/target_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']).'?mode=modulesetup', '', $permissiontoadd); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, "", 0, $newcardbutton, '', $limit, 0, 0, 1); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail = "SendTargetRef"; +$modelmail = "target"; +$objecttmp = new Target($db); +$trackid = 'xxxx'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; +} + +$moreforfilter = ''; +/*$moreforfilter.='
    '; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
    ';*/ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} + +if (!empty($moreforfilter)) { + print '
    '; + print $moreforfilter; + print '
    '; +} + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; +}*/ +// Action column +print ''; +print ''."\n"; + +$totalarray = array(); +$totalarray['nbfield'] = 0; + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; + $totalarray['nbfield']++; + } +} +// 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, 'totalarray'=>&$totalarray); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; + $totalarray['nbfield']++; +}*/ +// Action column +print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +$totalarray['nbfield']++; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } + } +} + + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$savnbfield = $totalarray['nbfield']; +$totalarray['nbfield'] = 0; +$imaxinloop = ($limit ? min($num, $limit) : $num); +while ($i < $imaxinloop) { + $obj = $db->fetch_object($resql); + if (empty($obj)) { + break; // Should not happen + } + + // Store properties in $object + $object->setVarsFromFetchObj($obj); + + if ($mode == 'kanban') { + if ($i == 0) { + print ''; + } + } else { + // Show here line of result + $j = 0; + print ''; + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } + + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif ($key == 'rowid') { + print $object->showOutputField($val, $key, $object->id, ''); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure']) && $val['isameasure'] == 1) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } + if (!isset($totalarray['val'])) { + $totalarray['val'] = array(); + } + if (!isset($totalarray['val']['t.'.$key])) { + $totalarray['val']['t.'.$key] = 0; + } + $totalarray['val']['t.'.$key] += $object->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + /*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; + }*/ + // Action column + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + + print ''."\n"; + } + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +// If no record found +if ($num == 0) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''; +} + + +$db->free($resql); + +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
    '; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) { + print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', 'maxwidth125', 1); + } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print '
    '; + print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
    '; + print '
    '; + print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
    '; + } elseif ($key == 'lang') { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin = new FormAdmin($db); + print $formadmin->select_language($search[$key], 'search_lang', 0, null, 1, 0, 0, 'minwidth150 maxwidth200', 2); + } else { + print ''; + } + print '
    '; +$searchpicto = $form->showFilterButtons(); +print $searchpicto; +print '
    '.$langs->trans("AnotherField").'
    '; + print '
    '; + } + // Output Kanban + print $object->getKanbanView(''); + if ($i == ($imaxinloop - 1)) { + print '
    '; + print '
    '.$obj->anotherfield.''; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; +print '
    '."\n"; + +print '
    '."\n"; + +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); + + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; + + print $formfile->showdocuments('massfilesarea_webhook', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/target_note.php b/htdocs/webhook/target_note.php new file mode 100644 index 00000000000..bb12d0947e8 --- /dev/null +++ b/htdocs/webhook/target_note.php @@ -0,0 +1,221 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file target_note.php + * \ingroup webhook + * \brief Tab for notes on Target + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +dol_include_once('/webhook/class/target.class.php'); +dol_include_once('/webhook/lib/webhook_target.lib.php'); + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "companies")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object = new Target($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('targetnote', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->webhook->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity]."/".$object->id; +} + + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$enablepermissioncheck = 0; +if ($enablepermissioncheck) { + $permissiontoread = $user->rights->webhook->target->read; + $permissiontoadd = $user->rights->webhook->target->write; + $permissionnote = $user->rights->webhook->target->write; // Used by the include of actions_setnotes.inc.php +} else { + $permissiontoread = 1; + $permissiontoadd = 1; + $permissionnote = 1; +} + +// Security check (enable the most restrictive one) +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->element, $object->id, $object->table_element, '', 'fk_soc', 'rowid', $isdraft); +if (empty($conf->webhook->enabled)) accessforbidden(); +if (!$permissiontoread) accessforbidden(); + + +/* + * Actions + */ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once +} + + +/* + * View + */ + +$form = new Form($db); + +//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; +$help_url = ''; +$title = $langs->trans('Target').' - '.$langs->trans("Notes"); +llxHeader('', $title, $help_url); + +if ($id > 0 || !empty($ref)) { + $object->fetch_thirdparty(); + + $head = targetPrepareHead($object); + + print dol_get_fiche_head($head, 'note', $langs->trans("Target"), -1, $object->picto); + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + + + $cssclass = "titlefield"; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + + print '
    '; + + print dol_get_fiche_end(); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/webhookindex.php b/htdocs/webhook/webhookindex.php new file mode 100644 index 00000000000..e62c5e3ddae --- /dev/null +++ b/htdocs/webhook/webhookindex.php @@ -0,0 +1,241 @@ + + * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2015 Jean-François Ferry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file webhook/webhookindex.php + * \ingroup webhook + * \brief Home page of webhook top menu + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) { + $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +} +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { + $i--; $j--; +} +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) { + $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +} +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) { + $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +} +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) { + $res = @include "../main.inc.php"; +} +if (!$res && file_exists("../../main.inc.php")) { + $res = @include "../../main.inc.php"; +} +if (!$res && file_exists("../../../main.inc.php")) { + $res = @include "../../../main.inc.php"; +} +if (!$res) { + die("Include of main fails"); +} + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook")); + +$action = GETPOST('action', 'aZ09'); + + +// Security check +// if (! $user->rights->webhook->myobject->read) { +// accessforbidden(); +// } +$socid = GETPOST('socid', 'int'); +if (isset($user->socid) && $user->socid > 0) { + $action = ''; + $socid = $user->socid; +} + +$max = 5; +$now = dol_now(); + + +/* + * Actions + */ + +// None + + +/* + * View + */ + +$form = new Form($db); +$formfile = new FormFile($db); + +llxHeader("", $langs->trans("WebhookArea")); + +print load_fiche_titre($langs->trans("WebhookArea"), '', 'webhook.png@webhook'); + +print '
    '; + + +/* BEGIN MODULEBUILDER DRAFT MYOBJECT +// Draft MyObject +if (! empty($conf->webhook->enabled) && $user->rights->webhook->read) +{ + $langs->load("orders"); + + $sql = "SELECT c.rowid, c.ref, c.ref_client, c.total_ht, c.tva as total_tva, c.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; + $sql.= ", s.code_client"; + $sql.= " FROM ".MAIN_DB_PREFIX."commande as c"; + $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE c.fk_soc = s.rowid"; + $sql.= " AND c.fk_statut = 0"; + $sql.= " AND c.entity IN (".getEntity('commande').")"; + if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); + if ($socid) $sql.= " AND c.fk_soc = ".((int) $socid); + + $resql = $db->query($sql); + if ($resql) + { + $total = 0; + $num = $db->num_rows($resql); + + print ''; + print ''; + print ''; + + $var = true; + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + $i++; + $total += $obj->total_ttc; + } + if ($total>0) + { + + print '"; + } + } + else + { + + print ''; + } + print "
    '.$langs->trans("DraftMyObjects").($num?''.$num.'':'').'
    '; + + $myobjectstatic->id=$obj->rowid; + $myobjectstatic->ref=$obj->ref; + $myobjectstatic->ref_client=$obj->ref_client; + $myobjectstatic->total_ht = $obj->total_ht; + $myobjectstatic->total_tva = $obj->total_tva; + $myobjectstatic->total_ttc = $obj->total_ttc; + + print $myobjectstatic->getNomUrl(1); + print ''; + print ''.price($obj->total_ttc).'
    '.$langs->trans("Total").''.price($total)."
    '.$langs->trans("NoOrder").'

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

    "; + } +} +*/ + +print '
    '; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/zapier/admin/setup.php b/htdocs/zapier/admin/setup.php index 08d2c1703a8..0d3cf64c54f 100644 --- a/htdocs/zapier/admin/setup.php +++ b/htdocs/zapier/admin/setup.php @@ -88,7 +88,7 @@ if ($action == 'edit') { foreach ($arrayofparameters as $key => $val) { print ''; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print ''; + print ''; } print ''; @@ -106,7 +106,7 @@ if ($action == 'edit') { foreach ($arrayofparameters as $key => $val) { print ''; print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); - print ''.$conf->global->$key.''; + print ''.getDolGlobalString($key).''; } print ''; diff --git a/test/phpunit/UserTest.php b/test/phpunit/UserTest.php index c6ccc3b01a0..ea7090f2b54 100644 --- a/test/phpunit/UserTest.php +++ b/test/phpunit/UserTest.php @@ -261,12 +261,40 @@ class UserTest extends PHPUnit\Framework\TestCase return $localobject; } + /** + * testUserHasRight + * @param User $localobject User + * @return User $localobject User + * @depends testUserOther + */ + public function testUserHasRight($localobject) + { + global $conf,$user,$langs,$db; + $conf=$this->savconf; + $user=$this->savuser; + $langs=$this->savlangs; + $db=$this->savdb; + /*$result=$localobject->setstatus(0); + print __METHOD__." id=".$localobject->id." result=".$result."\n"; + $this->assertLessThan($result, 0); + */ + + print __METHOD__." id=". $localobject->id ."\n"; + //$this->assertNotEquals($user->date_creation, ''); + $localobject->addrights(0, 'supplier_proposal'); + $this->assertEquals($localobject->hasRight('member', ''), 0); + $this->assertEquals($localobject->hasRight('member', 'member'), 0);$this->assertEquals($localobject->hasRight('product', 'member', 'read'), 0); + $this->assertEquals($localobject->hasRight('member', 'member'), 0);$this->assertEquals($localobject->hasRight('produit', 'member', 'read'), 0); + + return $localobject; + } + /** * testUserSetPassword * * @param User $localobject User * @return void - * @depends testUserOther + * @depends testUserHasRight * The depends says test is run only if previous is ok */ public function testUserSetPassword($localobject)