diff --git a/.travis.yml b/.travis.yml index d66915eb44b..ad8eb84a225 100644 --- a/.travis.yml +++ b/.travis.yml @@ -313,13 +313,13 @@ script: php upgrade2.php 3.9.0 4.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade390400-2.log php step5.php 3.9.0 4.0.0 > $TRAVIS_BUILD_DIR/upgrade390400-3.log php upgrade.php 4.0.0 5.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade400500.log - php upgrade2.php 4.0.0 5.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade400500-2.log + php upgrade2.php 4.0.0 5.0.0 > $TRAVIS_BUILD_DIR/upgrade400500-2.log php step5.php 4.0.0 5.0.0 > $TRAVIS_BUILD_DIR/upgrade400500-3.log php upgrade.php 5.0.0 6.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade500600.log - php upgrade2.php 5.0.0 6.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade500600-2.log + php upgrade2.php 5.0.0 6.0.0 > $TRAVIS_BUILD_DIR/upgrade500600-2.log php step5.php 5.0.0 6.0.0 > $TRAVIS_BUILD_DIR/upgrade500600-3.log php upgrade.php 6.0.0 7.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade600700.log - php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade600700-2.log + php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_WEBSITE > $TRAVIS_BUILD_DIR/upgrade600700-2.log php step5.php 6.0.0 7.0.0 > $TRAVIS_BUILD_DIR/upgrade600700-3.log cd - set +e diff --git a/COPYRIGHT b/COPYRIGHT index 427784a1552..9242cb8b9c4 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -34,12 +34,11 @@ Swift Mailer 5.4.2-DEV MIT license Yes Stripe 4.7.0 MIT licence Yes Library for Stripe module JS libraries: -jQuery 1.11.3 MIT License Yes JS library -jQuery UI 1.11.4 GPL and MIT License Yes JS library plugin UI -jQuery select2 3.5.2 GPL and Apache License Yes JS library plugin for sexier multiselect +jQuery 3.1.1 MIT License Yes JS library +jQuery UI 1.12.1 GPL and MIT License Yes JS library plugin UI +jQuery select2 4.0.4 GPL and Apache License Yes JS library plugin for sexier multiselect jQuery blockUI 2.70.0 GPL and MIT License Yes JS library plugin blockUI (to use ajax popups) jQuery Colorpicker 1.1 MIT License Yes JS library for color picker for a defined list of colors -jQuery FileUpload 5.0.3 GPL and MIT License Yes JS library to upload files jQuery Flot 0.8.3 MIT License Yes JS library to build graph jQuery JCrop 0.9.8 GPL and MIT License Yes JS library plugin Crop (to crop images) jQuery Jeditable 1.7.1 GPL and MIT License Yes JS library plugin jeditable (to edit in place) @@ -49,8 +48,7 @@ jQuery jqueryFileTree 1.0.1 GPL and MIT License Yes jQuery jquerytreeview 1.4.1 MIT License Yes JS library for filetree jQuery TableDnD 0.6 GPL and MIT License Yes JS library plugin TableDnD (to reorder table rows) jQuery Timepicker 1.1.0 GPL and MIT License Yes JS library Timepicker addon for Datepicker -jQuery Tiptip 1.3 GPL and MIT License Yes JS library for tooltips -jsGanttImproved 1.7.5.2 BSD License Yes JS library (to build Gantt reports) +jsGanttImproved 1.7.5.4 BSD License Yes JS library (to build Gantt reports) JsTimezoneDetect 1.0.6 MIT License Yes JS library to detect user timezone SwaggerUI 2.0.24 GPL-2+ Yes JS library to offer the REST API explorer Ace 1.2.8 BSD Yes JS library to get code syntaxique coloration in a textarea. diff --git a/ChangeLog b/ChangeLog index 9b5eef7aca5..5b6a62c4e03 100644 --- a/ChangeLog +++ b/ChangeLog @@ -23,6 +23,9 @@ Following changes may create regressions for some external modules, but were nec follow page naming conventions (so default filter/sort order features can also work). * The trigger ORDER_SUPPLIER_STATUS_ONPROCESS was renamed into ORDER_SUPPLIER_STATUS_ORDERED * The trigger ORDER_SUPPLIER_STATUS_RECEIVED_ALL was renamed into ORDER_SUPPLIER_STATUS_RECEIVED_COMPLETELY +* The parameter note into method cloture() is added at end of private note (previously in v6, it replaced) +* The parameter $user is now mandatory for method createFromOrder and createFromPropal. +* Remove js library fileupload that was not used by core code. ***** ChangeLog for 6.0.2 compared to 6.0.1 ***** diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 3b9ef4cc447..945e7d36ca7 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -82,8 +82,14 @@ with // LDR To open in same window //var OpenWindow=window.open(pRef, "newwin", "height="+vHeight+",width="+vWidth); window.location.href=pRef -* Replace hard coded string with i18n["String"]; +* Replace +vTmpDiv=this.newNode(vTmpCell, 'div', null, null, vTaskList[i].getResource()); +with +var vTmpNode=this.newNode(vTmpCell, 'div', null, ''); +vTmpNode=this.newNode(vTmpNode, 'a', null, '', vLangs[vLang]['moreinfo']); +vTmpNode.setAttribute('href',vTaskList[i].getLink()); + JCROP: ------ diff --git a/dev/resources/sepa/test.xml b/dev/resources/sepa/test.xml new file mode 100644 index 00000000000..fc969a7624c --- /dev/null +++ b/dev/resources/sepa/test.xml @@ -0,0 +1,133 @@ + + + + + PREL20171012/REF10 + 2017-10-12T00:08:30 + 2 + 734.4 + + MyBigCompany + + + + FR76AAAAA + + + + + + + PREL20171012/ID00010-T171001 + DD + 2 + 734.4 + + + SEPA + + + CORE + + RCUR + + 2017-10-12 + + MyBigCompany + + FR + Address1 + Address2 + + + + + FR76123456 + + + + + BICABCDEF + + + SLEV + + + + + FR76AAAAA + + SEPA + + + + + + + + AS-FA1710-0416-000679 + + 540 + + + RUM-CU1610-0001-3-1476058417 + 2016-10-10 + false + + + + + BICXYZ + + + + CUSTOMER A + + FR + Mr abc + + + + + FR123456 + + + + FA1710-0416 + + + + + AS-FA1710-0415-000683 + + 194.4 + + + RUM-CU1709-0011-4-1506525346 + 2017-09-27 + false + + + + + BICJKL + + + + CUSTOMER2 + + FR + + + + + FR76123456 + + + + FA1710-0415 + + + + + diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index fb48bc8094f..4dcc4be7b01 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2016-2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -67,8 +67,8 @@ $arrayfields=array( 'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), 'aa.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>0), - 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>0, 'help'=>'PcgtypeDesc'), - 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>0, 'help'=>'PcgtypeDesc'), + 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), + 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), 'aa.active'=>array('label'=>$langs->trans("Activated"), 'checked'=>1) ); @@ -105,14 +105,32 @@ if (empty($reshook)) $search_array_options=array(); } - if (GETPOST('change_chart')) + if (GETPOST('change_chart','alpha')) { $chartofaccounts = GETPOST('chartofaccounts', 'int'); - if (! empty($chartofaccounts)) { + if ($chartofaccounts > 0) + { + // Get language code for this $chartofaccounts + $sql ='SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a'; + $sql.=' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $country_code = $obj->code; + } + else dol_print_error($db); + + // Try to load sql file + if ($country_code) + { + $sqlfile = DOL_DOCUMENT_ROOT.'/install/mysql/data/llx_accounting_account_'.strtolower($country_code).'.sql'; + $result = run_sql($sqlfile, 1, 0, 1); + } if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { - $error ++; + $error++; } } else { $error ++; @@ -216,25 +234,29 @@ if ($resql) // Box to select active chart of account print $langs->trans("Selectchartofaccounts") . " : "; print '"; + print ajax_combobox("chartofaccounts"); print ''; print '
'; print '
'; diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 03565528fc1..5adb9760c9c 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -41,14 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -$langs->load("errors"); -$langs->load("admin"); -$langs->load("main"); -$langs->load("companies"); -$langs->load("resource"); -$langs->load("holiday"); -$langs->load("accountancy"); -$langs->load("hrm"); +$langs->loadLangs(array("errors","admin","companies","resource","holiday","compta","accountancy","hrm")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); @@ -100,7 +93,7 @@ $tablib[32]= "DictionaryAccountancyCategory"; // Requests to extract data $tabsql=array(); -$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s"; +$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.fk_country as country_id, c.code as country_code, c.label as country, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s, ".MAIN_DB_PREFIX."c_country as c WHERE s.fk_country=c.rowid and c.active=1"; $tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.sens, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; // Criteria to sort dictionaries @@ -110,17 +103,17 @@ $tabsqlsort[32]="position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[31]= "pcg_version,label"; +$tabfield[31]= "pcg_version,label,country_id,country"; $tabfield[32]= "code,label,range_account,sens,category_type,formula,position,country_id,country"; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[31]= "pcg_version,label"; +$tabfieldvalue[31]= "pcg_version,label,country"; $tabfieldvalue[32]= "code,label,range_account,sens,category_type,formula,position,country"; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[31]= "pcg_version,label"; +$tabfieldinsert[31]= "pcg_version,label,fk_country"; $tabfieldinsert[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; // Nom du rowid si le champ n'est pas de type autoincrement @@ -173,7 +166,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $ok=1; foreach ($listfield as $f => $value) { - if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancysystem','DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory + if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancyCategory','Pcg_version'))) continue; // For some pages, country is not mandatory if ($value == 'country' && in_array($tablib[$id],array('DictionaryCanton','DictionaryCompanyType','DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; @@ -188,6 +181,8 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $ok=0; $fieldnamekey=$listfield[$f]; // We take translate key of field + + if ($fieldnamekey == 'pcg_version') $fieldnamekey='Pcg_version'; if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 53569c50b00..d5fb2175b5f 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -569,6 +569,7 @@ if ($id) print ""; $colspan=count($fieldlist)+3; + if ($id == 32) $colspan++; print ' '; // Keep   to have a line with enough height } diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index ce99bd6296c..c4b31c0f169 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -77,7 +77,7 @@ $list_account = array ( * Actions */ -$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; +$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; if (GETPOST('change_chart')) diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 5ce7d6c0413..a6215383f35 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -60,7 +60,7 @@ $list = array ( * Actions */ -$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; +$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; if ($action == 'update') { $error = 0; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php index e80634ad7f6..782a7de7aa4 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php @@ -21,11 +21,10 @@ */ /** - * \file accounting/bookkeeping/thirdparty_lettrage.php + * \file accounting/bookkeeping/thirdparty_lettrage.php * \ingroup Advanced accountancy - * \brief Onglet de gestion de parametrages des ventilations + * \brief Onglet de gestion de parametrages des ventilations */ - require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; @@ -34,52 +33,71 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; -$action=GETPOST('action','aZ09'); -$massaction=GETPOST('massaction','alpha'); -$show_files=GETPOST('show_files','int'); -$confirm=GETPOST('confirm','alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if (empty($page) || $page == - 1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") $sortorder = "ASC"; -if ($sortfield == "") $sortfield = "bk.rowid"; +if ($sortorder == "") + $sortorder = "DESC"; +if ($sortfield == "") + $sortfield = "bk.doc_date"; -$search_year = GETPOST ( "search_year" ); +$search_year = GETPOST("search_year", 'int'); +$search_doc_type = GETPOST("search_doc_type", 'alpha'); +$search_doc_ref = GETPOST("search_doc_ref", 'alpha'); + +$lettering = GETPOST('lettering'); +if (! empty($lettering)) { + $action = $lettering; +} +$toselect = GETPOST('toselect', 'array'); + +// Did we click on purge search criteria ? +// All tests are required to be compatible with all browsers +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $search_year = ''; + $search_doc_type = ''; + $search_doc_ref = ''; +} // Security check -$socid = GETPOST("socid",'int'); +$socid = GETPOST("socid", 'int'); // if ($user->societe_id) $socid=$user->societe_id; $object = new Societe($db); $object->id = $socid; -$object->fetch($socid); - +$result = $object->fetch($socid); +if ($result < 0) { + setEventMessage($object->error, 'errors'); +} $form = new Form($db); $BookKeeping = new lettering($db); $formaccounting = new FormAccounting($db); - /* * Action */ if ($action == 'lettering') { - $result = $BookKeeping->updatelettrage($_POST['ids']); - -// var_dump($result); - if( $result < 0 ){ - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + $result = $BookKeeping->updateLettrage($toselect); + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } } @@ -87,243 +105,214 @@ if ($action == 'autolettrage') { $result = $BookKeeping->lettrageTiers($socid); - if( $result < 0 ) - { - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } - } +llxHeader('', 'Compta - Grand Livre'); -llxHeader ( '', 'Compta - Grand Livre' ); +/* + * Affichage onglets + */ +$head = societe_prepare_head($object); +dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); - /* - * Affichage onglets - */ - $head = societe_prepare_head($object); +dol_fiche_head($head, 'accounting', $langs->trans("ThirdParty"), 0, 'company'); - dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error'); +print ''; +print ''; - dol_fiche_head($head, 'TabAccounting', $langs->trans("ThirdParty"),0,'company'); +if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field +{ + print ''; +} +print ''; +print ''; +print ''; +$langs->load('compta'); +print ''; +print ''; +print ''; +// Address +print ''; - print '
' . $langs->trans("ThirdPartyName") . ''; +$object->next_prev_filter = "te.fournisseur = 1"; +print $form->showrefnav($object, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom', '', ''); +print '
' . $langs->trans('Prefix') . '' . $object->prefix_comm . '
' . $langs->trans("CustomerCode") . ''; +print $object->code_client; +if ($object->check_codeclient() != 0) + print ' (' . $langs->trans("WrongCustomerCode") . ')'; +print '
'; +print $form->editfieldkey("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); +print ''; +print $form->editfieldval("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); +print '
' . $langs->trans("Address") . ''; +dol_print_address($object->address, 'gmap', 'thirdparty', $object->id); +print '
'; - print ''; +// Zip / Town +print ''; +print ''; - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } +// Country +print ''; +print '
'.$langs->trans("ThirdPartyName").''; - $object->next_prev_filter="te.fournisseur = 1"; - print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom','',''); - print '
' . $langs->trans("Zip") . ' / ' . $langs->trans("Town") . '' . $object->zip . (($object->zip && $object->town) ? ' / ' : '') . $object->town . '
'.$langs->trans('Prefix').''.$object->prefix_comm.'
' . $langs->trans("Country") . ''; +// $img=picto_from_langcode($object->country_code); +$img = ''; +if ($object->isInEEC()) + print $form->textwithpicto(($img ? $img . ' ' : '') . $object->country, $langs->trans("CountryIsInEEC"), 1, 0); +else + print ($img ? $img . ' ' : '') . $object->country; +print '
'; - print ''; - print ''.$langs->trans("CustomerCode"). ''; - print $object->code_client; - if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; - print ''; - print ''; +$sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, "; +$sql .= " bk.thirdparty_code, bk.numero_compte , bk.label_compte, bk.debit, "; +$sql .= " bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; +$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; +$sql .= " WHERE (bk.thirdparty_code = '" . $object->code_compta . "' AND bk.numero_compte = '" . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . "' )"; - $langs->load('compta'); - print ''; - print ''; - print $form->editfieldkey("CustomerAccountancyCode",'customeraccountancycode',$object->code_compta,$object,$user->rights->societe->creer); - print ''; - print $form->editfieldval("CustomerAccountancyCode",'customeraccountancycode',$object->code_compta,$object,$user->rights->societe->creer); - print ''; - print ''; +if (dol_strlen($search_year)) { + $date_start = dol_mktime(0, 0, 0, 1, 1, $search_year); + $date_end = dol_mktime(23, 59, 59, 12, 31, $search_year); + $sql .= " AND ( bk.doc_date BETWEEN '" . $db->idate($date_start) . "' AND '" . $db->idate($date_end) . "' )"; +} +$sql .= $db->order($sortfield, $sortorder); - // Address - print ''.$langs->trans("Address").''; - dol_print_address($object->address,'gmap','thirdparty',$object->id); - print ''; +$debit = 0; +$credit = 0; +$solde = 0; +// Count total nb of records and calc total sum +$nbtotalofrecords = ''; +$resql = $db->query($sql); +if (! $resql) { + dol_print_error($db); + exit(); +} +$nbtotalofrecords = $db->num_rows($resql); - // Zip / Town - print ''.$langs->trans("Zip").' / '.$langs->trans("Town").''.$object->zip.(($object->zip && $object->town)?' / ':'').$object->town.''; +while ( $obj = $db->fetch_object($resql) ) { + $debit += $obj->debit; + $credit += $obj->credit; + + $solde += ($obj->credit - $obj->debit); +} + +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog("/accountancy/bookkeeping/thirdparty_lettrage.php", LOG_DEBUG); +$resql = $db->query($sql); +if (! $resql) { + dol_print_error($db); + exit(); +} + +$num = $db->num_rows($resql); + +dol_syslog("/accountancy/bookkeeping/thirdparty_lettrage.php", LOG_DEBUG); +if ($resql) { + $i = 0; + + print '
'; + print ''; + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + + print ""; + print ''; + print_liste_field_titre("Doctype", $_SERVER["PHP_SELF"], "bk.doc_type", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Docdate", $_SERVER["PHP_SELF"], "bk.doc_date", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Docref", $_SERVER["PHP_SELF"], "bk.doc_ref", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Labelcompte", $_SERVER["PHP_SELF"], "bk.label_compte", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Debit", $_SERVER["PHP_SELF"], "bk.debit", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Credit", $_SERVER["PHP_SELF"], "bk.credit", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "bk.montant", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Sens", $_SERVER["PHP_SELF"], "bk.sens", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Codejournal", $_SERVER["PHP_SELF"], "bk.code_journal", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Solde", $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); + print ''; + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; - // Country - print ''; + $var = false; + $solde = 0; + $tmp = ''; + while ( $obj = $db->fetch_object($resql) ) { - print '
 '; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'.$langs->trans("Country").''; - //$img=picto_from_langcode($object->country_code); - $img=''; - if ($object->isInEEC()) print $form->textwithpicto(($img?$img.' ':'').$object->country,$langs->trans("CountryIsInEEC"),1,0); - else print ($img?$img.' ':'').$object->country; - print '
'; + if ($tmp != $obj->lettering_code || empty($tmp)) + $tmp = $obj->lettering_code; + if ($tmp != $obj->lettering_code || empty($obj->lettering_code)) + $var = ! $var; + $solde += ($obj->credit - $obj->debit); + print ""; + if (empty($obj->lettering_code)) { + print ''; + print img_edit(); + print ' ' . $obj->doc_type . '' . "\n"; + } else + print '' . $obj->doc_type . '' . "\n"; - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE (bk.code_tiers = '" . $object->code_compta . "' AND bk.numero_compte = '" .$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER. "' )" ; + print '' . dol_print_date($db->jdate($obj->doc_date), 'day') . ''; + print '' . $obj->doc_ref . ''; + print '' . $obj->label_compte . ''; + print '' . price($obj->debit) . ''; + print '' . price($obj->credit) . ''; + print '' . price($obj->montant) . ''; + print '' . $obj->sens . ''; + print '' . $obj->code_journal . ''; + print '' . round($solde, 2) . ''; + if (empty($obj->lettering_code)) { + print ''; + } else + print '' . $obj->lettering_code . ''; - - if (dol_strlen ( $search_year )) { - $sql .= " AND ( bk.doc_date BETWEEN '" . $search_year . "-0-0' AND '" . ($search_year+1). "-0-0' )"; - } - - - $sql .= " ORDER BY bk.lettering_code ASC, bk.doc_date ASC" ;//. $db->plimit ( $conf->liste_limit + 1, $offset ); - -// echo $sql; -// dol_syslog ( "bookkeping:liste:create sql=" . $sql, LOG_DEBUG ); - $resql = $db->query ( $sql ); - if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; - - - print ''; - print ''; - print ''; - - print ""; - print ''; - print ''; - print_liste_field_titre("Doctype", "liste.php", "bk.doc_type" ); - print_liste_field_titre("Docdate", "liste.php", "bk.doc_date" ); - print_liste_field_titre("Docref", "liste.php", "bk.doc_ref" ); -// print_liste_field_titre("Numerocompte", "liste.php", "bk.numero_compte" ); -// print_liste_field_titre("Code_tiers", "liste.php", "bk.code_tiers" ); - print_liste_field_titre("LabelAccount", "liste.php", "bk_label_compte" ); - print_liste_field_titre("Debit", "liste.php", "bk.debit" ); - print_liste_field_titre("Credit", "liste.php", "bk.credit" ); -// print_liste_field_titre("Amount", "liste.php", "bk.montant" ); -// print_liste_field_titre("Sens", "liste.php", "bk.sens" ); - print_liste_field_titre("Codejournal", "liste.php", "bk.code_journal" ); - print ''; - print ''; print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $var = false; - - $debit = 0; - $credit = 0; - $solde = 0; - $tmp = ''; - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); - - if($tmp !=$obj->lettering_code || empty($tmp) ) - $tmp =$obj->lettering_code; - - if($tmp !=$obj->lettering_code || empty($obj->lettering_code)) - $var = ! $var; - - - $debit+= $obj->debit; - $credit+= $obj->credit; - - $solde+=($obj->credit-$obj->debit); - print ""; - - print ''; - if(empty($obj->lettering_code)){ - print '' . "\n"; - } - else - print '' . "\n"; - - - - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - - if(empty($obj->lettering_code)){ - print ''; - } - else - print ''; - - print "\n"; - - $i ++; - - - - - } - - print ''; - - print '' . "\n"; - print ''; - // print ''; - // print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print ""; - print '' . "\n"; - // print ''; - // print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print "
     '; - print ''; - print '   
' . $obj->rowid . ''; - print img_edit (); - print ' ' . $obj->doc_type . ''.$obj->doc_type . '' . dol_print_date ( $db->jdate ( $obj->doc_date ), 'day' ) . '' . $obj->doc_ref . '' . $obj->numero_compte . '' . $obj->code_tiers . '' . $obj->label_compte . '' . $obj->debit . '' . $obj->credit . '' . $obj->montant . '' . $obj->sens . '' . $obj->code_journal . '' . round($solde, 2) . '' . $obj->lettering_code . '
Mouvement totaux' . $debit . '' . $credit . ' 
Solde Comptable' . ($credit-$debit) . ' 
"; - - print ''; - print 'auto lettering'; - print ""; - $db->free($resql); - } else { - dol_print_error($db); } + print ''; + + print 'Mouvement totaux' . "\n"; + print '' . price($debit) . ''; + print '' . price($credit) . ''; + print ''; + print "\n"; + + print ""; + print 'Solde Comptable' . "\n"; + print '' . price($credit - $debit) . ''; + print ''; + print "\n"; + + print ""; + + print ''; + print '' . $langs->trans('AccountancyAutoLettering') . ''; + print ""; + $db->free($resql); +} else { + dol_print_error($db); +} // End of page llxFooter(); diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php index 99374a97118..5ac224673aa 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php @@ -21,9 +21,9 @@ */ /** - * \file accounting/bookkeeping/thirdparty_lettrage.php + * \file accounting/bookkeeping/thirdparty_lettrage.php * \ingroup Advanced accountancy - * \brief Tab to setup lettering + * \brief Tab to setup lettering */ // Dolibarr environment @@ -35,52 +35,73 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; - -$action=GETPOST('action','aZ09'); -$massaction=GETPOST('massaction','alpha'); -$show_files=GETPOST('show_files','int'); -$confirm=GETPOST('confirm','alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if (empty($page) || $page == - 1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") $sortorder = "ASC"; -if ($sortfield == "") $sortfield = "bk.rowid"; +if ($sortorder == "") + $sortorder = "DESC"; +if ($sortfield == "") + $sortfield = "bk.doc_date"; -$search_year = GETPOST ( "search_year" ); +$search_year = GETPOST("search_year",'int'); +$search_doc_type = GETPOST("search_doc_type",'alpha'); +$search_doc_ref = GETPOST("search_doc_ref",'alpha'); + +$lettering = GETPOST('lettering'); +if (!empty($lettering)) { + $action=$lettering; +} +$toselect = GETPOST('toselect','array'); + +// Did we click on purge search criteria ? +// All tests are required to be compatible with all browsers +if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) +{ + $search_year=''; + $search_doc_type=''; + $search_doc_ref=''; +} // Security check -$socid = GETPOST("socid",'int'); +$socid = GETPOST("socid", 'int'); // if ($user->societe_id) $socid=$user->societe_id; $object = new Societe($db); $object->id = $socid; -$object->fetch($socid); +$result = $object->fetch($socid); +if ($result<0) { + setEventMessage($object->error,'errors'); +} $form = new Form($db); $BookKeeping = new lettering($db); $formaccounting = new FormAccounting($db); - /* * Action */ if ($action == 'lettering') { - $result = $BookKeeping->updatelettrage($_POST['ids']); - -// var_dump($result); - if( $result < 0 ){ - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + $result = $BookKeeping->updateLettrage($toselect); + // var_dump($result); + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } } @@ -88,247 +109,230 @@ if ($action == 'autolettrage') { $result = $BookKeeping->lettrageTiers($socid); - if ( $result < 0 ) - { - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } - } +$title = 'AccountancyLettrage'; -llxHeader ( '', 'Compta - Grand Livre' ); +llxHeader('', $title); - /* - * Affichage onglets - */ - $head = societe_prepare_head($object); +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if (!empty($search_year)) $param.='&search_year='.$search_year; +if (!empty($socid)) $param.='&socid='.$socid; +if (!empty($search_doc_type)) $param.='&search_doc_type='.$search_doc_type; +if (!empty($search_doc_ref)) $param.='&search_doc_ref='.$search_doc_ref; - dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error'); - - dol_fiche_head($head, 'TabAccounting', $langs->trans("ThirdParty"),0,'company'); - - - - - print ''; - print ''; - - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } - - - print ''; - print ''; - print ''; - - $langs->load('compta'); - print ''; - print ''; - print ''; - - - // Address - print ''; - - // Zip / Town - print ''; - print ''; - - // Country - print ''; - - print '
'.$langs->trans("ThirdPartyName").''; - $object->next_prev_filter="te.fournisseur = 1"; - print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom','',''); - print '
'.$langs->trans('Prefix').''.$object->prefix_comm.'
'.$langs->trans("SupplierCode"). ''; - print $object->code_fournisseur; - if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; - print '
'; - print $form->editfieldkey("SupplierAccountancyCode",'supplieraccountancycode',$object->code_compta_fournisseur,$object,$user->rights->societe->creer); - print ''; - print $form->editfieldval("SupplierAccountancyCode",'supplieraccountancycode',$object->code_compta_fournisseur,$object,$user->rights->societe->creer); - print '
'.$langs->trans("Address").''; - dol_print_address($object->address,'gmap','thirdparty',$object->id); - print '
'.$langs->trans("Zip").' / '.$langs->trans("Town").''.$object->zip.(($object->zip && $object->town)?' / ':'').$object->town.'
'.$langs->trans("Country").''; - //$img=picto_from_langcode($object->country_code); - $img=''; - if ($object->isInEEC()) print $form->textwithpicto(($img?$img.' ':'').$object->country,$langs->trans("CountryIsInEEC"),1,0); - else print ($img?$img.' ':'').$object->country; - print '
'; - -// print_r($soc); -// exit; -// [code_compta] => 411DOUA -// [code_compta_fournisseur] => 401SUPPCODE /* - * Mode Liste - * - * - * + * Affichage onglets */ +$head = societe_prepare_head($object); - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE (bk.code_tiers = '" . $object->code_compta_fournisseur . "' AND bk.numero_compte = '" .$conf->global->ACCOUNTING_ACCOUNT_SUPPLIER. "' )" ; +dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); +dol_fiche_head($head, 'accounting_supplier', $langs->trans("ThirdParty"), 0, 'company'); +print ''; +print ''; - if (dol_strlen ( $search_year )) { - $sql .= " AND ( bk.doc_date BETWEEN '" . $search_year . "-0-0' AND '" . ($search_year+1). "-0-0' )"; - } +if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field +{ + print ''; +} +print ''; +print ''; +print ''; - $sql .= " ORDER BY bk.lettering ASC, bk.doc_date ASC" ;//. $db->plimit ( $conf->liste_limit + 1, $offset ); +$langs->load('compta'); +print ''; +print ''; +print ''; -// echo $sql; -// dol_syslog ( "bookkeping:liste:create sql=" . $sql, LOG_DEBUG ); - $resql = $db->query ( $sql ); - if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; +// Address +print ''; +// Zip / Town +print ''; +print ''; - print ''; - print ''; - print ''; +// Country +print ''; + +print '
' . $langs->trans("ThirdPartyName") . ''; +$object->next_prev_filter = "te.fournisseur = 1"; +print $form->showrefnav($object, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom', '', ''); +print '
' . $langs->trans('Prefix') . '' . $object->prefix_comm . '
' . $langs->trans("SupplierCode") . ''; +print $object->code_fournisseur; +if ($object->check_codefournisseur() != 0) + print ' (' . $langs->trans("WrongSupplierCode") . ')'; +print '
'; +print $form->editfieldkey("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); +print ''; +print $form->editfieldval("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); +print '
' . $langs->trans("Address") . ''; +dol_print_address($object->address, 'gmap', 'thirdparty', $object->id); +print '
' . $langs->trans("Zip") . ' / ' . $langs->trans("Town") . '' . $object->zip . (($object->zip && $object->town) ? ' / ' : '') . $object->town . '
' . $langs->trans("Country") . ''; +// $img=picto_from_langcode($object->country_code); +$img = ''; +if ($object->isInEEC()) + print $form->textwithpicto(($img ? $img . ' ' : '') . $object->country, $langs->trans("CountryIsInEEC"), 1, 0); +else + print ($img ? $img . ' ' : '') . $object->country; +print '
'; + +$sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, "; +$sql .= " bk.thirdparty_code, bk.numero_compte , bk.label_compte, bk.debit, "; +$sql .= " bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; +$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; +$sql .= " WHERE (bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' AND bk.numero_compte = '" . $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER . "' )"; + +if (dol_strlen($search_year)) { + $date_start = dol_mktime(0, 0, 0, 1, 1, $search_year); + $date_end = dol_mktime(23, 59, 59, 12, 31, $search_year); + $sql .= " AND ( bk.doc_date BETWEEN '".$db->idate($date_start)."' AND '".$db->idate($date_end)."' )"; +} + +$sql.= $db->order($sortfield,$sortorder); + +$debit = 0; +$credit = 0; +$solde = 0; +// Count total nb of records and calc total sum +$nbtotalofrecords = ''; +$resql = $db->query($sql); +if (! $resql) +{ + dol_print_error($db); + exit; +} +$nbtotalofrecords = $db->num_rows($resql); + +while ($obj = $db->fetch_object($resql)) { + $debit += $obj->debit; + $credit += $obj->credit; + + $solde += ($obj->credit - $obj->debit); +} + +$sql.= $db->plimit($limit+1, $offset); + +dol_syslog ( "/accountancy/bookkeeping/thirdparty_lettrage_supplier.php", LOG_DEBUG ); +$resql = $db->query($sql); +if (! $resql) +{ + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + +dol_syslog ( "/accountancy/bookkeeping/thirdparty_lettrage_supplier.php", LOG_DEBUG ); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + + print ''; + print ''; + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + + print ""; + print ''; + print_liste_field_titre("Doctype", $_SERVER["PHP_SELF"], "bk.doc_type","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Docdate", $_SERVER["PHP_SELF"], "bk.doc_date","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Docref", $_SERVER["PHP_SELF"], "bk.doc_ref","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Labelcompte", $_SERVER["PHP_SELF"], "bk.label_compte","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Debit", $_SERVER["PHP_SELF"], "bk.debit","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Credit", $_SERVER["PHP_SELF"], "bk.credit","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "bk.montant","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Sens", $_SERVER["PHP_SELF"], "bk.sens","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Codejournal", $_SERVER["PHP_SELF"], "bk.code_journal","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Solde", $_SERVER["PHP_SELF"], "","",$param,"",$sortfield,$sortorder); + print ''; + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $var = false; + $solde = 0; + $tmp = ''; + while ($obj = $db->fetch_object($resql)) { + + if ($tmp != $obj->lettering_code || empty($tmp)) + $tmp = $obj->lettering_code; + + if ($tmp != $obj->lettering_code || empty($obj->lettering_code)) + $var = ! $var; + + $solde += ($obj->credit - $obj->debit); + + print ""; + + if (empty($obj->lettering_code)) { + print '' . "\n"; + } else + print '' . "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + if (empty($obj->lettering_code)) { + print ''; + } else + print ''; - print "
 '; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '
'; + print img_edit(); + print ' ' . $obj->doc_type . '' . $obj->doc_type . '' . dol_print_date($db->jdate($obj->doc_date), 'day') . '' . $obj->doc_ref . '' . $obj->label_compte . '' . price($obj->debit) . '' . price($obj->credit) . '' . price($obj->montant) . '' . $obj->sens . '' . $obj->code_journal . '' . round($solde, 2) . '' . $obj->lettering_code . '
"; - print ''; - print ''; - print_liste_field_titre("Doctype", "liste.php", "bk.doc_type" ); - print_liste_field_titre("Docdate", "liste.php", "bk.doc_date" ); - print_liste_field_titre("Docref", "liste.php", "bk.doc_ref" ); -// print_liste_field_titre("Numerocompte", "liste.php", "bk.numero_compte" ); -// print_liste_field_titre("Code_tiers", "liste.php", "bk.code_tiers" ); - print_liste_field_titre("LabelAccount", "liste.php", "bk_label_compte" ); - print_liste_field_titre("Debit", "liste.php", "bk.debit" ); - print_liste_field_titre("Credit", "liste.php", "bk.credit" ); - print_liste_field_titre("Amount", "liste.php", "bk.montant" ); - print_liste_field_titre("Sens", "liste.php", "bk.sens" ); - print_liste_field_titre("Codejournal", "liste.php", "bk.code_journal" ); - print ''; - print ''; print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $var = false; - - $debit = 0; - $credit = 0; - $solde = 0; - $tmp = ''; - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); - - if($tmp !=$obj->lettering || empty($tmp) ) - $tmp =$obj->lettering; - - if($tmp !=$obj->lettering || empty($obj->lettering)) - $var = ! $var; - - - $debit+= $obj->debit; - $credit+= $obj->credit; - - $solde+=($obj->credit-$obj->debit); - print ""; - - print ''; - if(empty($obj->lettering)){ - print '' . "\n"; - } - else - print '' . "\n"; - - - - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - if(empty($obj->lettering)){ - print ''; - } - else - print ''; - - print "\n"; - - $i ++; - } - - print ''; - - print '' . "\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print ""; - print '' . "\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print "
     '; - print ''; - print '   
' . $obj->rowid . ''; - print img_edit (); - print ' ' . $obj->doc_type . ''.$obj->doc_type . '' . dol_print_date ( $db->jdate ( $obj->doc_date ), 'day' ) . '' . $obj->doc_ref . '' . $obj->numero_compte . '' . $obj->code_tiers . '' . $obj->label_compte . '' . $obj->debit . '' . $obj->credit . '' . $obj->montant . '' . $obj->sens . '' . $obj->code_journal . '' . round($solde, 2) . '' . $obj->lettering . '
Mouvement totaux' . $debit . '' . $credit . ' 
Solde Comptable' . ($credit-$debit) . ' 
"; - - print ''; - print 'auto lettering'; - print ""; - $db->free ( $resql ); - } else { - dol_print_error ( $db ); } + print ''; + + print 'Mouvement totaux' . "\n"; + print '' . price($debit) . ''; + print '' . price($credit) . ''; + print ''; + print "\n"; + + print ""; + print 'Solde Comptable' . "\n"; + print '' . price($credit - $debit) . ''; + print ''; + print "\n"; + + print ""; + + print ''; + print ''.$langs->trans('AccountancyAutoLettering').''; + print ""; + $db->free($resql); +} else { + dol_print_error($db); +} // End of page llxFooter(); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 52f7a473bed..2b03f86d2e9 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -279,7 +279,7 @@ class BookKeeping extends CommonObject $sql .= ', entity'; $sql .= ") VALUES ("; $sql .= "'" . $this->db->idate($this->doc_date) . "'"; - $sql .= ",'" . $this->db->idate($this->date_lim_reglement) . "'"; + $sql .= ", ".(! isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'" . $this->db->idate($this->date_lim_reglement) . "'"); $sql .= ",'" . $this->db->escape($this->doc_type) . "'"; $sql .= ",'" . $this->db->escape($this->doc_ref) . "'"; $sql .= "," . $this->fk_doc; @@ -1079,22 +1079,26 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return number <0 if KO, >0 if OK */ - public function updateByMvt($piece_num='', $field='', $value='', $mode='') { + public function updateByMvt($piece_num='', $field='', $value='', $mode='') + { + $error=0; + $this->db->begin(); + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . $mode . " as ab"; $sql .= ' SET ab.' . $field . '=' . (is_numeric($value)?$value:"'".$value."'"); $sql .= ' WHERE ab.piece_num=' . $piece_num ; $resql = $this->db->query($sql); if (! $resql) { - $error ++; + $error++; $this->errors[] = 'Error ' . $this->db->lasterror(); dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); } if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -1521,11 +1525,16 @@ class BookKeeping extends CommonObject * @param string $piece_num Piece num * @return void */ - public function transformTransaction($direction=0,$piece_num='') { + public function transformTransaction($direction=0,$piece_num='') + { + $error = 0; + $this->db->begin(); - if ($direction==0) { + + if ($direction==0) + { $next_piecenum=$this->getNextNumMvt(); - if ($result < 0) { + if ($next_piecenum < 0) { $error++; } $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element.'(doc_date, doc_type,'; diff --git a/htdocs/accountancy/class/lettering.class.php b/htdocs/accountancy/class/lettering.class.php index f3d9359b19d..81e0ad5e20e 100644 --- a/htdocs/accountancy/class/lettering.class.php +++ b/htdocs/accountancy/class/lettering.class.php @@ -18,321 +18,287 @@ */ /** - * \file accountancy/class/bookkeeping.class.php - * \ingroup Advanced accountancy - * \brief File of class for lettering + * \file accountancy/class/bookkeeping.class.php + * \ingroup Advanced accountancy + * \brief File of class for lettering */ - -include_once DOL_DOCUMENT_ROOT."/accountancy/class/bookkeeping.class.php"; -include_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"; -include_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; - +include_once DOL_DOCUMENT_ROOT . "/accountancy/class/bookkeeping.class.php"; +include_once DOL_DOCUMENT_ROOT . "/societe/class/societe.class.php"; +include_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php"; /** * Class lettering */ class lettering extends BookKeeping { - /** - * lettrageTiers - * - * @param int $socid Thirdparty id - * @return int <0 if KO, >0 if OK - */ + /** + * lettrageTiers + * + * @param int $socid Thirdparty id + * @return void + */ public function lettrageTiers($socid) { - $db = $this->db; $object = new Societe($this->db); $object->id = $socid; $object->fetch($socid); - - if( $object->code_compta == '411CUSTCODE') + if ($object->code_compta == '411CUSTCODE') { $object->code_compta = ''; - - if( $object->code_compta_fournisseur == '401SUPPCODE') - $object->code_compta_fournisseur = ''; - - - - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.lettering_code, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE code_journal = 'BQ' AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - - $sql .= " ) AND ( bk.date_lettering ='' OR bk.date_lettering IS NULL ) AND bk.lettering_code !='' "; - - $sql .= " GROUP BY bk.lettering_code "; - - - $resql = $db->query ( $sql ); - if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; - - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); - $i++; - - $sql = "SELECT bk.rowid "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE bk.lettering_code = '".$obj->lettering_code."' "; - $sql .= " AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) "; -// echo $sql; - $resql2 = $db->query ( $sql ); - if ($resql2) { - $num2 = $db->num_rows ( $resql2 ); - $i2 = 0; - $ids = array(); - while ( $i2 < $num2 ) { - $obj2 = $db->fetch_object ( $resql2 ); - $i2++; - $ids[] = $obj2->rowid; - } - - - if(count($ids) > 1 ){ - $result = $this->updatelettrage($ids); - - // var_dump($result); -// if( $result < 0 ){ -// setEventMessages('', $BookKeeping->errors, 'errors' ); -// $error++; -// -// } - } - } - } } + if ($object->code_compta_fournisseur == '401SUPPCODE') { + $object->code_compta_fournisseur = ''; + } /** - Prise en charge des lettering complexe avec prelevment , virement - */ - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type "; + * Prise en charge des lettering complexe avec prelevment , virement + */ + $sql = "SELECT DISTINCT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.thirdparty_code, "; + $sql .= " bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant "; + $sql .= " , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type "; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) "; - $sql .= " WHERE code_journal = 'BQ' AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) + $sql .= " WHERE ( "; + if (! empty($object->code_compta)) + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; + if (! empty($object->code_compta_fournisseur)) + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) AND date_lettering ='' "; - $sql .= " GROUP BY bk.lettering_code "; + $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) "; + $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) "; + $sql .= $db->order('bk.doc_date', 'DESC'); -// echo $sql; -// - $resql = $db->query ( $sql ); + // echo $sql; + // + $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; + $num = $db->num_rows($resql); - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); + while ( $obj = $db->fetch_object($resql) ) { $ids = array(); - $i++; + $ids_fact = array(); - // print_r($obj); + if ($obj->type == 'payment_supplier') { - - - if($obj->type =='payment_supplier' ) { - $ids[] = $obj->rowid; - - $sql= 'SELECT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank '; - $sql.= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; - $sql.= " INNER JOIN " .MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = facf.ref) "; - // $sqlmid.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as soc ON soc.rowid=facf.fk_soc"; - // $sqlmid.= " INNER JOIN " . MAIN_DB_PREFIX . "c_paiement as payc ON payc.id=payf.fk_paiement"; - $sql .= " WHERE 1 "; - $sql .= " AND fk_paiementfourn = '".$obj->url_id."' "; - // $sql .= " AND (bk.numero_compte = '" . $object->code_compta . "' OR bk.numero_compte = '" . $object->code_compta_fournisseur . "') "; - $sql .= " AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) "; - // echo $sql; - // exit; + $sql = 'SELECT DISTINCT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank, facf.rowid as fact_id'; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON (bk.fk_doc = payf.fk_bank AND bk.code_journal='" . $obj->code_journal . "')"; + $sql .= " WHERE payfacf.fk_paiementfourn = '" . $obj->url_id . "' "; + $sql .= " AND code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=4) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; } - elseif($obj->type =='payment' ){ - $ids[] = $obj->rowid; - - $sql= 'SELECT bk.rowid,fac.facnumber , pay.fk_bank '; - $sql.= " FROM " . MAIN_DB_PREFIX . "facture fac "; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; - $sql.= " INNER JOIN " .MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = fac.rowid) "; - $sql .= " WHERE 1 "; - $sql .= " AND payfac.fk_paiement = '".$obj->url_id."' "; - $sql .= " AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) "; - - // echo $sql; + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - - - $resql2 = $db->query ( $sql ); + $resql2 = $db->query($sql); if ($resql2) { - $num2 = $db->num_rows ( $resql2 ); - $i2 = 0; - - while ( $i2 < $num2 ) { - $obj2 = $db->fetch_object ( $resql2 ); - $i2++; - $ids[] = $obj2->rowid; + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + $ids_fact[] = $obj2->fact_id; } - - // print_r($ids); - // exit; - if(count($ids) > 1 ){ - $result = $this->updatelettrage($ids); - - // var_dump($result); -// if( $result < 0 ){ -// setEventMessages('', $BookKeeping->errors, 'errors' ); -// $error++; -// -// } - } - - // exit; + } else { + $this->errors[] = $this->db->lasterror; + return - 1; } - } - } + if (count($ids_fact)) { + $sql = 'SELECT bk.rowid, facf.ref, facf.ref_supplier '; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = facf.rowid AND facf.rowid IN (" . implode(',', $ids_fact) . "))"; + $sql .= " WHERE bk.code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=3) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + } + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; + } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - return 1; - } + $resql2 = $db->query($sql); + if ($resql2) { + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + } + } else { + $this->errors[] = $this->db->lasterror; + return - 1; + } + } + } elseif ($obj->type == 'payment') { + $sql = 'SELECT DISTINCT bk.rowid, fac.ref, fac.ref, pay.fk_bank, fac.rowid as fact_id'; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON (bk.fk_doc = pay.fk_bank AND bk.code_journal='" . $obj->code_journal . "')"; + $sql .= " WHERE payfac.fk_paiement = '" . $obj->url_id . "' "; + $sql .= " AND bk.code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=4) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + } + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; + } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - public function updatelettrage($ids, $notrigger=false){ - $error = 0; + $resql2 = $db->query($sql); + if ($resql2) { + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + $ids_fact[] = $obj2->fact_id; + } + } else { + $this->errors[] = $this->db->lasterror; + return - 1; + } + if (count($ids_fact)) { + $sql = 'SELECT bk.rowid, fac.ref, fac.ref_supplier '; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = fac.rowid AND fac.rowid IN (" . implode(',', $ids_fact) . "))"; + $sql .= " WHERE code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=2) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + } + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; + } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - $lettre=''; + $resql2 = $db->query($sql); + if ($resql2) { + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + } + } else { + $this->errors[] = $this->db->lasterror; + return - 1; + } + } + } - $sql = "SELECT lettering_code FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; - $sql .= " lettering_code != '' GROUP BY lettering_code ORDER BY lettering_code DESC limit 1; "; -// echo $sql; - $result = $this->db->query ( $sql ); - if ($result) { - $obj = $this->db->fetch_object ( $result ); - $lettre = (empty($obj->lettering_code)? 'AAA' : $obj->lettering_code ); - if(!empty($obj->lettering_code)) - $lettre++; - } - else{ - $this->errors[] = 'Error'.$this->db->lasterror();; - $error++; - } -// var_dump(__line__, $error); - - if (! $error) - { - $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; - $sql .= " rowid IN (".implode(',', $ids).") "; - $result = $this->db->query ( $sql ); - if ($result) { - $obj = $this->db->fetch_object ( $result ); - // print_r($obj); - if( !(round(abs($obj->deb),2) === round(abs($obj->cred),2)) ){ - // echo $sql; - // print_r($obj); - $this->errors[] = 'Total not exacts '.round(abs($obj->deb),2).' vs '. round(abs($obj->cred),2); - $error++; + if (count($ids) > 1) { + $result = $this->updatelettrage($ids); } } - else{ - $this->errors[] = 'Erreur sql'.$this->db->lasterror();; - $error++; - } } + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::" . __METHOD__ . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + return - 1 * $error; + } else { + return 1; + } + } + + /** + * + * @param array $ids ids array + * @param boolean $notrigger no trigger + * @return number + */ + public function updateLettrage($ids = array(), $notrigger = false) { + $error = 0; + + dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG); + + $sql = "SELECT DISTINCT lettering_code FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; + $sql .= " lettering_code != '' ORDER BY lettering_code DESC limit 1; "; + + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + $lettre = (empty($obj->lettering_code) ? 'AAA' : $obj->lettering_code); + if (! empty($obj->lettering_code)) + $lettre ++; + } else { + $this->errors[] = 'Error' . $this->db->lasterror(); + ; + $error ++; + } + + $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; + $sql .= " rowid IN (" . implode(',', $ids) . ") "; + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + if (! (round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) { + $this->errors[] = 'Total not exacts ' . round(abs($obj->deb), 2) . ' vs ' . round(abs($obj->cred), 2); + $error ++; + } + } else { + $this->errors[] = 'Erreur sql' . $this->db->lasterror(); + ; + $error ++; + } + + // Update request $now = dol_now(); - // Update request - if (! $error) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET"; - $sql.= " lettering_code='".$lettre."'"; - $sql.= " , date_lettering = " .$now ; // todo correct date it's false - $sql.= " WHERE rowid IN (".implode(',', $ids).") "; - // echo $sql ; - // - // var_dump(__line__, $error); - // print_r($this->errors); - // exit; - $this->db->begin(); + $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET"; + $sql .= " lettering_code='" . $lettre . "'"; + $sql .= " , date_lettering = '" . $this->db->idate($now) . "'"; // todo correct date it's false + $sql .= " WHERE rowid IN (" . implode(',', $ids) . ") "; + $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. + if (! $error) { + if (! $notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. - //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } - } -// var_dump(__line__, $error); - - // Commit or rollback - if ($error) - { -// foreach($this->errors as $errmsg) -// { -// dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); -// $this->error.=($this->error?', '.$errmsg:$errmsg); -// } - $this->db->rollback(); -// echo $this->error; -// var_dump(__line__, $error); - return -1*$error; - } - else - { - $this->db->commit(); - return 1; + // // Call triggers + // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + // $interface=new Interfaces($this->db); + // $result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + // if ($result < 0) { $error++; $this->errors=$interface->errors; } + // // End call triggers } } - return -1; + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } else { + $this->db->commit(); + return 1; + } } - } diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index 0e3e71c1527..13602160c48 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -32,6 +32,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; // Langs $langs->load("bills"); @@ -51,6 +53,9 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); +$search_day=GETPOST("search_day","int"); +$search_month=GETPOST("search_month","int"); +$search_year=GETPOST("search_year","int"); $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); @@ -95,6 +100,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; $search_country = ''; $search_tvaintra = ''; } @@ -131,6 +139,7 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { */ $form = new Form($db); +$formother = new FormOther($db); llxHeader('', $langs->trans("CustomersVentilation") . ' - ' . $langs->trans("Dispatched")); @@ -197,6 +206,19 @@ if (strlen(trim($search_account))) { if (strlen(trim($search_vat))) { $sql .= natural_search("fd.tva_tx", $search_vat); } +if ($search_month > 0) +{ + if ($search_year > 0 && empty($search_day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'"; + else if ($search_year > 0 && ! empty($search_day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'"; + else + $sql.= " AND date_format(f.datef, '%m') = '".$db->escape($search_month)."'"; +} +else if ($search_year > 0) +{ + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($search_year,1,false))."' AND '".$db->idate(dol_get_last_day($search_year,12,false))."'"; +} if (strlen(trim($search_country))) { $sql .= natural_search("co.label", $search_country); } @@ -237,6 +259,9 @@ if ($result) { $param .= "&search_account=" . $search_account; if ($search_vat) $param .= "&search_vat=" . $search_vat; + if ($search_day) $param.='&search_day='.urlencode($search_day); + if ($search_month) $param.='&search_month='.urlencode($search_month); + if ($search_year) $param.='&search_year='.urlencode($search_year); if ($search_country) $param .= "&search_country=" . $search_country; if ($search_tvaintra) @@ -267,7 +292,11 @@ if ($result) { print ''; print ''; print ''; - print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year,'search_year',1, 20, 5); + print ''; print ''; //print ''; print ''; diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index 51f62ecabf6..2d26a2d06d8 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -115,6 +115,7 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; $search_month = ''; $search_year = ''; } diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index 156d80f09e4..750a5bc9f25 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -31,6 +31,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; // Langs $langs->load("compta"); @@ -50,6 +52,9 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); +$search_day=GETPOST("search_day","int"); +$search_month=GETPOST("search_month","int"); +$search_year=GETPOST("search_year","int"); // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); @@ -90,6 +95,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; } if (is_array($changeaccount) && count($changeaccount) > 0) { @@ -123,6 +131,9 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { * View */ +$form = new Form($db); +$formother = new FormOther($db); + llxHeader('', $langs->trans("ExpenseReportsVentilation") . ' - ' . $langs->trans("Dispatched")); print ''; $ret .= ''; diff --git a/htdocs/cashdesk/affPied.php b/htdocs/cashdesk/affPied.php index efe56ac2762..8f54dd732a7 100644 --- a/htdocs/cashdesk/affPied.php +++ b/htdocs/cashdesk/affPied.php @@ -24,17 +24,24 @@ ?>
-use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) { - print "\n\n"; + print "\n\n"; print '' . "\n"; + jQuery(".classfortooltip").tooltip({ + show: { collision: "flipfit", effect:\'toggle\', delay:50 }, + hide: { effect:\'toggle\', delay: 50 }, + tooltipClass: "mytooltip", + content: function () { + return $(this).prop(\'title\'); /* To force to get title as is */ + } + }); + }); + ' . "\n"; } printCommonFooter('private'); diff --git a/htdocs/cashdesk/class/Facturation.class.php b/htdocs/cashdesk/class/Facturation.class.php index b55524a874a..8bfd1d3082c 100644 --- a/htdocs/cashdesk/class/Facturation.class.php +++ b/htdocs/cashdesk/class/Facturation.class.php @@ -117,7 +117,7 @@ class Facturation } // Define part of HT, VAT, TTC - $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $use_npr, $product->type, $mysoc, $localtaxarray); + $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $vat_npr, $product->type, $mysoc, $localtaxarray); // Calcul du total ht sans remise $total_ht = $resultarray[0]; @@ -207,6 +207,9 @@ class Facturation $total_ht=0; $total_ttc=0; + $total_vat = 0; + $total_localtax1 = 0; + $total_localtax2 = 0; $tab=array(); $tab = $_SESSION['poscart']; @@ -309,7 +312,7 @@ class Facturation public function ref($aRef=null) { - if ( !$aRef ) + if (is_null($aRef)) { return $this->ref; } @@ -330,9 +333,9 @@ class Facturation * @param int $aQte Qty * @return int Qty */ - public function qte( $aQte=null ) + public function qte($aQte=null) { - if ( !$aQte ) + if (is_null($aQte)) { return $this->qte; } @@ -357,7 +360,7 @@ class Facturation public function stock($aStock=null) { - if ( !$aStock ) + if (is_null($aStock)) { return $this->stock; } @@ -381,7 +384,7 @@ class Facturation public function remisePercent($aRemisePercent=null) { - if ( !$aRemisePercent ) + if (is_null($aRemisePercent)) { return $this->remise_percent; } @@ -405,7 +408,7 @@ class Facturation public function montantRemise($aMontantRemise=null) { - if ( !$aMontantRemise ) { + if (is_null($aMontantRemise)) { return $this->montant_remise; @@ -427,10 +430,10 @@ class Facturation * @param int $aPrix Price * @return string Stock */ - public function prix ( $aPrix=null ) + public function prix($aPrix=null) { - if ( !$aPrix ) { + if (is_null($aPrix)) { return $this->prix; @@ -454,7 +457,7 @@ class Facturation */ public function tva($aTva=null) { - if ( !$aTva ) { + if (is_null($aTva)) { return $this->tva; @@ -478,7 +481,7 @@ class Facturation */ public function numInvoice($aNumFacture=null) { - if ( !$aNumFacture ) { + if (is_null($aNumFacture)) { return $this->num_facture; @@ -499,10 +502,10 @@ class Facturation * @param int $aModeReglement Payment mode * @return int Payment mode */ - public function getSetPaymentMode( $aModeReglement=null ) + public function getSetPaymentMode($aModeReglement=null) { - if ( !$aModeReglement ) { + if (is_null($aModeReglement)) { return $this->mode_reglement; @@ -524,10 +527,10 @@ class Facturation * @param int $aMontantEncaisse Amount * @return int Amount */ - public function montantEncaisse( $aMontantEncaisse=null ) + public function montantEncaisse($aMontantEncaisse=null) { - if ( !$aMontantEncaisse ) { + if (is_null($aMontantEncaisse)) { return $this->montant_encaisse; @@ -549,10 +552,10 @@ class Facturation * @param int $aMontantRendu Amount * @return int Amount */ - public function montantRendu( $aMontantRendu=null ) + public function montantRendu($aMontantRendu=null) { - if ( !$aMontantRendu ) { + if (is_null($aMontantRendu)) { return $this->montant_rendu; } else if ( $aMontantRendu == 'RESET' ) { @@ -573,9 +576,9 @@ class Facturation * @param date $aPaiementLe Date * @return date Date */ - public function paiementLe( $aPaiementLe=null ) + public function paiementLe($aPaiementLe=null) { - if ( !$aPaiementLe ) { + if (is_null($aPaiementLe)) { return $this->paiement_le; @@ -596,9 +599,9 @@ class Facturation * @param int $aTotalHt Total amount * @return int Total amount */ - public function prixTotalHt( $aTotalHt=null ) + public function prixTotalHt($aTotalHt=null) { - if ( !$aTotalHt ) { + if (is_null($aTotalHt)) { return $this->prix_total_ht; @@ -619,9 +622,9 @@ class Facturation * @param int $aMontantTva Amount vat * @return int Amount vat */ - public function montantTva( $aMontantTva=null ) + public function montantTva($aMontantTva=null) { - if ( !$aMontantTva ) { + if (is_null($aMontantTva)) { return $this->montant_tva; @@ -643,9 +646,9 @@ class Facturation * @param int $aTotalTtc Amount ttc * @return int Amount ttc */ - public function prixTotalTtc( $aTotalTtc=null ) + public function prixTotalTtc($aTotalTtc=null) { - if ( !$aTotalTtc ) + if (is_null($aTotalTtc)) { return $this->prix_total_ttc; } diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 1c8d9fcfe50..edbc4fa68ce 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -103,7 +103,7 @@ class Categories extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type = '', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 6242691d1f1..7a7a6f06a1f 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -163,7 +163,7 @@ class Categorie extends CommonObject */ public $socid; /** - * @var int Category type + * @var string Category type * * @see Categorie::TYPE_PRODUCT * @see Categorie::TYPE_SUPPLIER @@ -1327,6 +1327,7 @@ class Categorie extends CommonObject { $w = array(); $i = 0; + $forced_color=''; foreach ($way as $cat) { $i++; @@ -1340,12 +1341,7 @@ class Categorie extends CommonObject $forced_color='categtextwhite'; if ($cat->color) { - $hex=$cat->color; - $r = hexdec($hex[0].$hex[1]); - $g = hexdec($hex[2].$hex[3]); - $b = hexdec($hex[4].$hex[5]); - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright >= 0.5) $forced_color='categtextblack'; // Higher than 60% + if (colorIsLight($cat->color)) $forced_color='categtextblack'; } } } @@ -1602,12 +1598,7 @@ class Categorie extends CommonObject $forced_color='categtextwhite'; if ($this->color) { - $hex=$this->color; - $r = hexdec($hex[0].$hex[1]); - $g = hexdec($hex[2].$hex[3]); - $b = hexdec($hex[4].$hex[5]); - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright >= 0.5) $forced_color='categtextblack'; // Higher than 60% + if (colorIsLight($this->color)) $forced_color='categtextblack'; } $link = ''; diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index 3cba48cfc07..2c995543fdf 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -36,7 +36,7 @@ if (! $user->admin) accessforbidden(); if (! ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))) { - $conf->dol_hide_leftmenu = 1; // Force hide of left menu. + $conf->dol_hide_leftmenu = 1; // Force hide of left menu. } $error=0; @@ -71,33 +71,33 @@ if (GETPOST('refreshpage')) $action='preview'; // Add a collab page if ($action == 'add') { - $db->begin(); + $db->begin(); - $objectpage->title = GETPOST('WEBSITE_TITLE'); - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); + $objectpage->title = GETPOST('WEBSITE_TITLE'); + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); - if (empty($objectpage->title)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); - $error++; - } + if (empty($objectpage->title)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); + $error++; + } - if (! $error) - { - $res = $objectpage->create($user); - if ($res <= 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - } + if (! $error) + { + $res = $objectpage->create($user); + if ($res <= 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + } if (! $error) { $db->commit(); - setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; + setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); + $action=''; } else { @@ -111,38 +111,38 @@ if ($action == 'add') // Update page if ($action == 'delete') { - $db->begin(); + $db->begin(); - $res = $object->fetch(0, $website); + $res = $object->fetch(0, $website); - $res = $objectpage->fetch($pageid, $object->fk_website); + $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res > 0) - { - $res = $objectpage->delete($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } + if ($res > 0) + { + $res = $objectpage->delete($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); - exit; - } - else - { - $db->rollback(); - } - } - else - { - dol_print_error($db); - } + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); + exit; + } + else + { + $db->rollback(); + } + } + else + { + dol_print_error($db); + } } @@ -161,7 +161,7 @@ print "\n".'
'; print ''; if ($action == 'create') { - print ''; + print ''; } @@ -174,225 +174,225 @@ print '
'; if (count($object->records) > 0) { - // ***** Part for web sites + // ***** Part for web sites - print '
'; - print $langs->trans("Website").': '; - print '
'; + print '
'; + print $langs->trans("Website").': '; + print '
'; - // List of websites - print '
'; - $out=''; - $out.=''; + if (empty($object->records)) $out.=''; + // Loop on each sites + $i=0; + foreach($object->records as $key => $valwebsite) + { + if (empty($website)) $website=$valwebsite->ref; - $out.=''; - $i++; - } - $out.=''; - $out.=ajax_combobox('website'); - print $out; - print ''; + $out.=''; + $i++; + } + $out.=''; + $out.=ajax_combobox('website'); + print $out; + print ''; - if ($website) - { - $virtualurl=''; - $dataroot=DOL_DATA_ROOT.'/websites/'.$website; - if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; - } + if ($website) + { + $virtualurl=''; + $dataroot=DOL_DATA_ROOT.'/collab/'.$website; + if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; + } - if ($website && $action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($website && $action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - print '   '; + print '   '; - //print ''; - print ''; - print ''; - print ''; - } + //print ''; + print ''; + print ''; + print ''; + } - print '
'; + print '
'; - // Button for websites - print '
'; + // Button for websites + print '
'; - if ($action == 'preview') - { - print '
'; - print ''; - //print ''; - $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); - print $form->textwithpicto('', $htmltext); - print '
'; + if ($action == 'preview') + { + print '
'; + print ''; + //print ''; + $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); + print $form->textwithpicto('', $htmltext); + print '
'; - $urlext=$virtualurl; - $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; - //if (! empty($object->virtualhost)) - //{ - print '
transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - //} + $urlext=$virtualurl; + $urlint=$urlwithroot.'/public/collab/index.php?website='.$website; + //if (! empty($object->virtualhost)) + //{ + print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + //} - print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); - print ''; - } + print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); + print ''; + } - if (in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } + if (in_array($action, array('editcss','editmenu','create'))) + { + if ($action != 'preview') print ''; + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + } - print '
'; + print '
'; - // ***** Part for pages + // ***** Part for pages - if ($website) - { - print '
'; + if ($website) + { + print '
'; - $array=$objectpage->fetchAll($object->id); - if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); - $atleastonepage=(is_array($array) && count($array) > 0); + $array=$objectpage->fetchAll($object->id); + if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + $atleastonepage=(is_array($array) && count($array) > 0); - print '
'; - print '
'; - print $langs->trans("Page").': '; - print '
'; - print '
'; + print '
'; + print '
'; + print $langs->trans("Page").': '; + print '
'; + print '
'; - if ($action != 'add') - { - $out=''; - $out.=''; + if ($atleastonepage) + { + if (empty($pageid) && $action != 'create') // Page id is not defined, we try to take one + { + $firstpageid=0;$homepageid=0; + foreach($array as $key => $valpage) + { + if (empty($firstpageid)) $firstpageid=$valpage->id; + if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id; + } + $pageid=$homepageid?$homepageid:$firstpageid; // We choose home page and if not defined yet, we take first page + } - foreach($array as $key => $valpage) - { - $out.=''; - } - } - else $out.=''; - $out.=''; - $out.=ajax_combobox('pageid'); - print $out; - } - else - { - print $langs->trans("New"); - } + foreach($array as $key => $valpage) + { + $out.=''; + } + } + else $out.=''; + $out.=''; + $out.=ajax_combobox('pageid'); + print $out; + } + else + { + print $langs->trans("New"); + } - print ''; - //print $form->selectarray('page', $array); + print ''; + //print $form->selectarray('page', $array); - if ($action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - if ($pageid > 0) - { - print '   '; + if ($pageid > 0) + { + print '   '; - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; - else print ''; - print ''; - print ''; - //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; - //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; - print ''; - } - } + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; + else print ''; + print ''; + print ''; + //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; + //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; + print ''; + } + } - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print '
'; + print '
'; - if ($website && $pageid > 0 && $action == 'preview') - { - $websitepage = new WebSitePage($db); - $websitepage->fetch($pageid); + if ($website && $pageid > 0 && $action == 'preview') + { + $websitepage = new WebSitePage($db); + $websitepage->fetch($pageid); - $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&page='.$pageid; - $pagealias = $websitepage->pageurl; + $realpage=$urlwithroot.'/public/collab/index.php?website='.$website.'&page='.$pageid; + $pagealias = $websitepage->pageurl; - print '
'; - print ''; - //print ''; - $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); - print $form->textwithpicto('', $htmltext); - print '
'; + print '
'; + print ''; + //print ''; + $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); + print $form->textwithpicto('', $htmltext); + print '
'; - if (! empty($object->virtualhost)) - { - $urlext=$virtualurl.'/'.$pagealias.'.php'; - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } - else - { - print ''; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } + if (! empty($object->virtualhost)) + { + $urlext=$virtualurl.'/'.$pagealias.'.php'; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + } + else + { + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + } - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); - print ''; // View page in new Tab - //print ''; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); + print ''; // View page in new Tab + //print ''; - // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext - } - if (! in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } + // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext + } + if (! in_array($action, array('editcss','editmenu','create'))) + { + if ($action != 'preview') print ''; + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + } - print '
'; + print '
'; - if ($action == 'preview') - { - // Adding jquery code to change on the fly url of preview ext - if (! empty($conf->use_javascript_ajax)) - { - print ''; - } - } - } + } + } + } } else { - print '
'; - $langs->load("errors"); - print $langs->trans("ErrorModuleSetupNotComplete"); - print '
'; - $action=''; + print '
'; + $langs->load("errors"); + print $langs->trans("ErrorModuleSetupNotComplete"); + print '
'; + $action=''; } @@ -437,21 +437,21 @@ $head = array(); if ($action == 'editcontent') { - /* + /* * Editing global variables not related to a specific theme */ - $csscontent = @file_get_contents($filecss); + $csscontent = @file_get_contents($filecss); - $contentforedit = ''; - /*$contentforedit.=''."\n";*/ - $contentforedit .= $objectpage->content; + $contentforedit .= $objectpage->content; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); - $doleditor->Create(0, '', false); + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); + $doleditor->Create(0, '', false); } print "
\n\n"; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index c8b92acd5fc..15218406a94 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -199,8 +199,8 @@ if ($action == 'add') $percentage=in_array(GETPOST('status'),array(-1,100))?GETPOST('status'):(in_array(GETPOST('complete'),array(-1,100))?GETPOST('complete'):GETPOST("percentage")); // If status is -1 or 100, percentage is not defined and we must use status // Clean parameters - $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour"), $fulldayevent?'00':GETPOST("apmin"), 0, GETPOST("apmonth"), GETPOST("apday"), GETPOST("apyear")); - $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour"), $fulldayevent?'59':GETPOST("p2min"), $fulldayevent?'59':'0', GETPOST("p2month"), GETPOST("p2day"), GETPOST("p2year")); + $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour",'int'), $fulldayevent?'00':GETPOST("apmin",'int'), $fulldayevent?'00':GETPOST("apsec",'int'), GETPOST("apmonth",'int'), GETPOST("apday",'int'), GETPOST("apyear",'int')); + $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour",'int'), $fulldayevent?'59':GETPOST("p2min",'int'), $fulldayevent?'59':GETPOST("apsec",'int'), GETPOST("p2month",'int'), GETPOST("p2day",'int'), GETPOST("p2year",'int')); // Check parameters if (! $datef && $percentage == 100) @@ -577,7 +577,7 @@ if ($action == 'mupdate') // Actions to delete doc $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); -$permissioncreate = ($user->rights->agenda->allactions->delete || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->delete)); +$permissioncreate = ($user->rights->agenda->allactions->create || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->read)); include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; @@ -1478,8 +1478,8 @@ if ($id > 0) $filedir=$conf->agenda->multidir_output[$conf->entity].'/'.$object->id; $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->agenda->myactions->create; - $delallowed=$user->rights->agenda->myactions->delete; + $genallowed=$user->rights->agenda->myactions->read; + $delallowed=$user->rights->agenda->myactions->create; $var=true; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 12c11f863f1..36d551ea577 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -907,7 +907,7 @@ class ActionComm extends CommonObject return $db->lasterror(); } } - + /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * @@ -918,7 +918,7 @@ class ActionComm extends CommonObject function load_board($user, $load_state_board=0) { global $conf, $langs; - + if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp"; else { $this->nb=array(); @@ -934,7 +934,7 @@ class ActionComm extends CommonObject if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; if ($user->societe_id) $sql.=" AND a.fk_soc = ".$user->societe_id; if (! $user->rights->agenda->allactions->read) $sql.= " AND (a.fk_user_author = ".$user->id . " OR a.fk_user_action = ".$user->id . " OR a.fk_user_done = ".$user->id . ")"; - + $resql=$this->db->query($sql); if ($resql) { @@ -956,7 +956,7 @@ class ActionComm extends CommonObject if ($agenda_static->hasDelay()) $response->nbtodolate++; } else $this->nb["actionscomm"]=$obj->nb; } - + $this->db->free($resql); if(empty($load_state_board)) return $response; else return 1; @@ -1375,7 +1375,7 @@ class ActionComm extends CommonObject if ($qualified && $datestart) { - $eventarray[$datestart]=$event; + $eventarray[]=$event; } } } diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 68a36844e39..981ae1025cf 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -75,7 +75,7 @@ if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="name"; $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); -$modulepart='contract'; +$modulepart='actions'; /* diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 35767c16167..835d5971ed2 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -44,6 +44,7 @@ require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/modules/propale/modules_propale.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/propal.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; if (! empty($conf->projet->enabled)) { @@ -612,14 +613,14 @@ if (empty($reshook)) // Close proposal else if ($action == 'setstatut' && $user->rights->propal->cloturer && ! GETPOST('cancel','alpha')) { - if (! GETPOST('statut')) { + if (! GETPOST('statut','int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CloseAs")), null, 'errors'); $action = 'statut'; } else { // prevent browser refresh from closing proposal several times if ($object->statut == Propal::STATUS_VALIDATED) { - $result=$object->cloture($user, GETPOST('statut','int'), GETPOST('note_private','alpha')); + $result=$object->cloture($user, GETPOST('statut','int'), GETPOST('note_private','none')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1687,8 +1688,8 @@ if ($action == 'create') //Form to close proposal (signed or not) $formquestion = array( array('type' => 'select','name' => 'statut','label' => $langs->trans("CloseAs"),'values' => array(2=>$object->labelstatut [2],3=>$object->labelstatut [3])), - //array('type' => 'other','name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '')); - array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => $object->note_private)); + array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '') // Field to complete private note (not replace) + ); if (! empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; @@ -2284,6 +2285,14 @@ if ($action == 'create') } } + // Create an intervention + if (! empty($conf->service->enabled) && ! empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) { + if ($user->rights->ficheinter->creer) { + $langs->load("interventions"); + print ''; + } + } + // Create contract if ($conf->contrat->enabled && $object->statut == Propal::STATUS_SIGNED) { $langs->load("contracts"); @@ -2343,8 +2352,8 @@ if ($action == 'create') $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->propal->dir_output . "/" . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->propal->creer; - $delallowed = $user->rights->propal->supprimer; + $genallowed = $user->rights->propal->lire; + $delallowed = $user->rights->propal->creer; $var = true; @@ -2354,6 +2363,15 @@ if ($action == 'create') $linktoelem = $form->showLinkToObjectBlock($object, null, array('propal')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show online signature link + $useonlinepayment = $conf->global->MAIN_FEATURES_LEVEL; + + if ($object->statut != Propal::STATUS_DRAFT && $useonlinepayment) + { + print '
'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + print showOnlineSignatureUrl('proposal', $object->ref); + } print '
'; diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 325fad1a326..364f63bd4e4 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -90,11 +90,11 @@ class Proposals extends DolibarrApi * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter commercial proposal of. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} + * @param string $thirdparty_ids Thirdparty ids to filter commercial proposal of. Example: '1' or '1,2,3' {@pattern /^2|3$/i} * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" * @return array Array of order objects */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -257,39 +257,39 @@ class Proposals extends DolibarrApi $request_data = (object) $request_data; - $updateRes = $this->propal->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - 'HT', - 0, - $request_data->info_bits, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->date_start, - $request_data->date_end, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id, - $request_data->multicurrency_subprice, - $request_data->fk_remise_except - ); - - if ($updateRes > 0) { - return $this->get($id)->line->rowid; + $updateRes = $this->propal->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + 'HT', + 0, + $request_data->info_bits, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->date_start, + $request_data->date_end, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice, + $request_data->fk_remise_except + ); + if ($updateRes > 0) { + return $updateRes; } + return false; } @@ -507,6 +507,49 @@ class Proposals extends DolibarrApi ); } + /** + * Close (Accept or refuse) a quote / commercial proposal + * + * @param int $id Commercial proposal ID + * @param int $status Must be 2 (accepted) or 3 (refused) {@min 2}{@max 3} + * @param string $note_private Add this mention at end of private note + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return array + */ + function close($id, $status, $note_private='', $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->propal->cloture(DolibarrApiAccess::$user, $status, $note_private, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Commercial Proposal: '.$this->propal->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal closed (Ref='.$this->propal->ref.')' + ) + ); + } + + /** * Validate fields before create or update object * @@ -526,6 +569,7 @@ class Proposals extends DolibarrApi return $propal; } + /** * Clean sensible object datas * diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index cd5f81783b7..19e70235e9e 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -569,28 +569,33 @@ class Propal extends CommonObject // Reorder if child line if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); - // Mise a jour informations denormalisees au niveau de la propale meme - $result=$this->update_price(1,'auto',0,$mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { - $this->db->commit(); - return $this->line->rowid; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$this->line->error; - $this->db->rollback(); - return -2; - } + // Mise a jour informations denormalisees au niveau de la propale meme + $result=$this->update_price(1,'auto',0,$mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. + if ($result > 0) + { + $this->db->commit(); + return $this->line->rowid; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$this->line->error; + $this->db->rollback(); + return -2; + } + } + else + { + dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); + return -3; } - } + } /** @@ -955,13 +960,55 @@ class Propal extends CommonObject $resql=$this->db->query($sql); if (! $resql) $error++; - /* + if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + { + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds + } + + // Add object linked + if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + { + foreach($this->linked_objects as $origin => $tmp_origin_id) + { + if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + { + foreach($tmp_origin_id as $origin_id) + { + $ret = $this->add_object_linked($origin, $origin_id); + if (! $ret) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (! $ret) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + } + + // Add linked object (deprecated, use ->linkedObjectsIds instead) + if (! $error && $this->origin && $this->origin_id) + { + $ret = $this->add_object_linked(); + if (! $ret) dol_print_error($this->db); + } + + /* * Insertion du detail des produits dans la base - */ - if (! $error) - { - $fk_parent_line=0; - $num=count($this->lines); + */ + if (! $error) + { + $fk_parent_line=0; + $num=count($this->lines); for ($i=0;$i<$num;$i++) { @@ -1252,7 +1299,7 @@ class Propal extends CommonObject $sql.= ", p.datep as dp"; $sql.= ", p.fin_validite as dfv"; $sql.= ", p.date_livraison as date_livraison"; - $sql.= ", p.model_pdf, p.ref_client, p.extraparams"; + $sql.= ", p.model_pdf, p.last_main_doc, p.ref_client, p.extraparams"; $sql.= ", p.note_private, p.note_public"; $sql.= ", p.fk_projet, p.fk_statut"; $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; @@ -1306,6 +1353,7 @@ class Propal extends CommonObject $this->socid = $obj->fk_soc; $this->fk_project = $obj->fk_projet; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->note = $obj->note_private; // TODO deprecated $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; @@ -1505,48 +1553,6 @@ class Propal extends CommonObject } } - /** - * Update value of extrafields on the proposal - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - global $conf, $hookmanager; - - $action='update'; - $error = 0; - - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('propaldao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (!$error) - { - return 1; - } - else - { - return -1; - } - - } - /** * Set status to validated * @@ -2257,8 +2263,8 @@ class Propal extends CommonObject * * @param User $user Object user that close * @param int $statut Statut - * @param string $note Comment - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param string $note Complete private note with this note + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int <0 if KO, >0 if OK */ function cloture($user, $statut, $note, $notrigger=0) @@ -2270,8 +2276,10 @@ class Propal extends CommonObject $this->db->begin(); + $newprivatenote = dol_concatdesc($this->note_private, $note); + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; + $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; $sql.= " WHERE rowid = ".$this->id; $resql=$this->db->query($sql); @@ -2297,7 +2305,7 @@ class Propal extends CommonObject return -2; } } - if ($statut == self::STATUS_BILLED) + if ($statut == self::STATUS_BILLED) // Why this ? { $trigger_name='PROPAL_CLASSIFY_BILLED'; } diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index bb8e0d880b9..ebca22f8114 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -947,7 +947,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->lire; + $delallowed=$user->rights->propal->creer; print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index c385fe9a6ae..1402cc75870 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -170,7 +170,7 @@ if (empty($reshook)) $result = $object->set_reopen($user); if ($result > 0) { - setEventMessages($langs->trans('OrderReopened', $object->ref), null); + setEventMessages($langs->trans('OrderReopened', $object->ref), null); } else { @@ -264,12 +264,12 @@ if (empty($reshook)) $object->modelpdf = GETPOST('model'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->date_livraison = $datelivraison; - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); - $object->warehouse_id = GETPOST('warehouse_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->warehouse_id = GETPOST('warehouse_id', 'int'); $object->fk_delivery_address = GETPOST('fk_address'); $object->contactid = GETPOST('contactid'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -279,8 +279,8 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form if (! $error) { - $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) $error++; + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error++; } // If creation from another object of another module (Example: origin=propal, originid=1) @@ -366,7 +366,7 @@ if (empty($reshook)) // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - // trigger used + // trigger used { $lines[$i]->fetch_optionals($lines[$i]->rowid); $array_options = $lines[$i]->array_options; @@ -423,7 +423,7 @@ if (empty($reshook)) $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook if ($reshook < 0) - $error++; + $error++; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -491,10 +491,10 @@ if (empty($reshook)) } else if ($action == 'classifyunbilled' && $user->rights->commande->creer) { - $ret=$object->classifyUnBilled(); - if ($ret < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $ret=$object->classifyUnBilled(); + if ($ret < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Positionne ref commande client @@ -502,7 +502,7 @@ if (empty($reshook)) $result = $object->set_ref_client($user, GETPOST('ref_client')); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -510,7 +510,7 @@ if (empty($reshook)) $result = $object->set_remise($user, GETPOST('remise')); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -563,7 +563,7 @@ if (empty($reshook)) else if ($action == 'setavailability' && $user->rights->commande->creer) { $result = $object->availability(GETPOST('availability_id')); if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else if ($action == 'setdemandreason' && $user->rights->commande->creer) { @@ -596,36 +596,36 @@ if (empty($reshook)) // Set incoterm elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } // bank account else if ($action == 'setbankaccount' && $user->rights->commande->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // shipping method else if ($action == 'setshippingmethod' && $user->rights->commande->creer) { - $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - // warehouse - else if ($action == 'setwarehouse' && $user->rights->commande->creer) { - $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + // warehouse + else if ($action == 'setwarehouse' && $user->rights->commande->creer) { + $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else if ($action == 'setremisepercent' && $user->rights->commande->creer) { $result = $object->set_remise($user, GETPOST('remise_percent')); @@ -898,18 +898,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); } else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -1062,13 +1062,13 @@ if (empty($reshook)) } else if ($action == 'confirm_validate' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1121,7 +1121,7 @@ if (empty($reshook)) else if ($action == 'confirm_modif' && $user->rights->commande->creer) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1174,13 +1174,13 @@ if (empty($reshook)) } else if ($action == 'confirm_cancel' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1223,7 +1223,7 @@ if (empty($reshook)) $hookmanager->initHooks(array('orderdao')); $parameters = array('id' => $object->id); $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by - // some hooks + // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); if ($result < 0) { @@ -1393,10 +1393,10 @@ if ($action == 'create' && $user->rights->commande->creer) $soc = $objectsrc->thirdparty; $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); - $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); - $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); + $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); + $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1421,10 +1421,10 @@ if ($action == 'create' && $user->rights->commande->creer) { $cond_reglement_id = $soc->cond_reglement_id; $mode_reglement_id = $soc->mode_reglement_id; - $fk_account = $soc->fk_account; + $fk_account = $soc->fk_account; $availability_id = $soc->availability_id; - $shipping_method_id = $soc->shipping_method_id; - $warehouse_id = $soc->warehouse_id; + $shipping_method_id = $soc->shipping_method_id; + $warehouse_id = $soc->warehouse_id; $demand_reason_id = $soc->demand_reason_id; $remise_percent = $soc->remise_percent; $remise_absolue = 0; @@ -1537,12 +1537,12 @@ if ($action == 'create' && $user->rights->commande->creer) $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); print ''; - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { print '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; } // Delivery delay @@ -1550,21 +1550,21 @@ if ($action == 'create' && $user->rights->commande->creer) $form->selectAvailabilityDelay($availability_id, 'availability_id', '', 1); print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print '' . $langs->trans('SendingMethod') . ''; - print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print '' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); + print ''; + } - // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print '' . $langs->trans('Warehouse') . ''; - print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); - print ''; - } + // Warehouse + if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct=new FormProduct($db); + print '' . $langs->trans('Warehouse') . ''; + print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); + print ''; + } // What trigger creation print '' . $langs->trans('Source') . ''; @@ -1590,22 +1590,22 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''; - print ''; - $incoterm_id = GETPOST('incoterm_id'); - $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { - $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); - $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); - } - print $form->select_incoterms($incoterm_id, $incoterm_location); + print ''; + $incoterm_id = GETPOST('incoterm_id'); + $incoterm_location = GETPOST('location_incoterms'); + if (empty($incoterm_id)) + { + $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); + $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); + } + print $form->select_incoterms($incoterm_id, $incoterm_location); print ''; } // Other attributes $parameters = array('objectsrc' => $objectsrc, 'socid'=>$socid); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1623,8 +1623,8 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''.fieldLabel('Currency','multicurrency_code').''; - print ''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print ''; } @@ -1686,6 +1686,8 @@ if ($action == 'create' && $user->rights->commande->creer) } print '' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . ''; + + // Amount print '' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . ''; print '' . $langs->trans('TotalVAT') . '' . price($objectsrc->total_tva) . ""; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE @@ -1918,69 +1920,69 @@ if ($action == 'create' && $user->rights->commande->creer) // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); + // Thirdparty + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherOrders").')'; - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->commande->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
'; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
'; + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->commande->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
'; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; if ($soc->outstanding_limit) { - // Outstanding Bill - print ''; - print ''; + // Outstanding Bill + print ''; + print ''; } // Relative and absolute discounts if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final - // invoice + // invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; @@ -2037,7 +2039,7 @@ if ($action == 'create' && $user->rights->commande->creer) } else { print $object->date ? dol_print_date($object->date, 'day') : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; @@ -2062,51 +2064,51 @@ if ($action == 'create' && $user->rights->commande->creer) } else { print $object->date_livraison ? dol_print_date($object->date_livraison, 'daytext') : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } - // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print ''; - print ''; - } + // Warehouse + if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct=new FormProduct($db); + print ''; + print ''; + } // Terms of payment print '
'; - print $langs->trans('OutstandingBill'); - print ''; - print price($soc->get_OutstandingBill()) . ' / '; - print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); - print '
'; + print $langs->trans('OutstandingBill'); + print ''; + print price($soc->get_OutstandingBill()) . ' / '; + print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); + print '
'; - print ''; - if ($action != 'editshippingmethod' && $user->rights->commande->creer) - print ''; - print '
'; - print $langs->trans('SendingMethod'); - print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; - print '
'; - if ($action == 'editshippingmethod') { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); - } else { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); - } - print '
'; + print ''; + if ($action != 'editshippingmethod' && $user->rights->commande->creer) + print ''; + print '
'; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; + print '
'; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); + } + print '
'; - print ''; - if ($action != 'editwarehouse' && $user->rights->commande->creer) - print ''; - print '
'; - print $langs->trans('Warehouse'); - print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).'
'; - print '
'; - if ($action == 'editwarehouse') { - $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); - } else { - $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none'); - } - print '
'; + print ''; + if ($action != 'editwarehouse' && $user->rights->commande->creer) + print ''; + print '
'; + print $langs->trans('Warehouse'); + print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).'
'; + print '
'; + if ($action == 'editwarehouse') { + $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); + } else { + $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none'); + } + print '
'; @@ -2173,9 +2175,9 @@ if ($action == 'create' && $user->rights->commande->creer) print '
'; print ''; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { - list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); - } + if($action == 'actualizemulticurrencyrate') { + list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); + } $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); @@ -2243,30 +2245,30 @@ if ($action == 'create' && $user->rights->commande->creer) $totalVolume=$tmparray['volume']; if ($totalWeight || $totalVolume) { - print ''.$langs->trans("CalculatedWeight").''; - print ''; - print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); - print ''; - print ''.$langs->trans("CalculatedVolume").''; - print ''; - print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); - print ''; + print ''.$langs->trans("CalculatedWeight").''; + print ''; + print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); + print ''; + print ''.$langs->trans("CalculatedVolume").''; + print ''; + print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); + print ''; } - // TODO How record was recorded OrderMode (llx_c_input_method) + // TODO How record was recorded OrderMode (llx_c_input_method) // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print '
'; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->commande->creer) print ''.img_edit().''; - else print ' '; - print '
'; - print ''; - print ''; + print '
'; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->commande->creer) print ''.img_edit().''; + else print ' '; + print '
'; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2275,27 +2277,27 @@ if ($action == 'create' && $user->rights->commande->creer) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { - print ''; - print ''; - print '
'; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->commande->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ''; - print ''; + print ''; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ''; + print ''; } // Other attributes @@ -2312,20 +2314,20 @@ if ($action == 'create' && $user->rights->commande->creer) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Total HT @@ -2357,7 +2359,7 @@ if ($action == 'create' && $user->rights->commande->creer) // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } @@ -2395,7 +2397,7 @@ if ($action == 'create' && $user->rights->commande->creer) include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
'; + print '
'; print ''; // Show object lines @@ -2421,7 +2423,7 @@ if ($action == 'create' && $user->rights->commande->creer) } } print '
'; - print '
'; + print '
'; print "\n"; @@ -2435,7 +2437,7 @@ if ($action == 'create' && $user->rights->commande->creer) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { // Send if ($object->statut > Commande::STATUS_DRAFT) { @@ -2445,10 +2447,10 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; } - // Valid + // Valid if ($object->statut == Commande::STATUS_DRAFT && $object->total_ttc >= 0 && $numlines > 0 && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { print ''; @@ -2459,8 +2461,8 @@ if ($action == 'create' && $user->rights->commande->creer) } // Create event if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a - // "workflow" action so should appears somewhere else on - // page. + // "workflow" action so should appears somewhere else on + // page. { print '' . $langs->trans("AddAction") . ''; } @@ -2480,11 +2482,11 @@ if ($action == 'create' && $user->rights->commande->creer) // Create contract if ($conf->contrat->enabled && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)) { - $langs->load("contracts"); + $langs->load("contracts"); - if ($user->rights->contrat->creer) { - print ''; - } + if ($user->rights->contrat->creer) { + print ''; + } } // Ship @@ -2527,9 +2529,9 @@ if ($action == 'create' && $user->rights->commande->creer) } } if ($object->statut > Commande::STATUS_DRAFT && $object->billed) { - if ($user->rights->commande->creer && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { - print ''; - } + if ($user->rights->commande->creer && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { + print ''; + } } // Clone if ($user->rights->commande->creer) { @@ -2538,8 +2540,8 @@ if ($action == 'create' && $user->rights->commande->creer) // Cancel order if ($object->statut == Commande::STATUS_VALIDATED && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->cloturer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->cloturer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))) ) { print ''; @@ -2571,8 +2573,8 @@ if ($action == 'create' && $user->rights->commande->creer) $relativepath = $comref . '/' . $comref . '.pdf'; $filedir = $conf->commande->dir_output . '/' . $comref; $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->commande->creer; - $delallowed = $user->rights->commande->supprimer; + $genallowed = $user->rights->commande->lire; + $delallowed = $user->rights->commande->creer; print $formfile->showdocuments('commande', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index d41fd9cee1d..f494709e441 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -107,7 +107,7 @@ class CommandeApi extends DolibarrApi * @url GET /order/list * @return array Array of order objects */ - function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $mode=0, $societe = 0) { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode=0, $societe = 0) { global $db, $conf; $obj_ret = array(); @@ -316,7 +316,7 @@ class CommandeApi extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index 6ffca33a4ce..e31aaa4e060 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -52,9 +52,9 @@ class Orders extends DolibarrApi } /** - * Get properties of a commande object + * Get properties of an order object * - * Return an array with commande informations + * Return an array with order informations * * @param int $id ID of order * @return array|mixed data without useless information @@ -176,7 +176,7 @@ class Orders extends DolibarrApi * Create order object * * @param array $request_data Request data - * @return int ID of commande + * @return int ID of order */ function post($request_data = NULL) { @@ -196,6 +196,7 @@ class Orders extends DolibarrApi } $this->commande->lines = $lines; }*/ + if ($this->commande->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors)); } @@ -236,8 +237,8 @@ class Orders extends DolibarrApi /** * Add a line to given order * - * @param int $id Id of commande to update - * @param array $request_data Orderline data + * @param int $id Id of order to update + * @param array $request_data OrderLine data * * @url POST {id}/lines * @@ -281,12 +282,13 @@ class Orders extends DolibarrApi $request_data->label, $request_data->array_options, $request_data->fk_unit, - $this->element, - $request_data->id + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; @@ -295,9 +297,9 @@ class Orders extends DolibarrApi /** * Update a line to given order * - * @param int $id Id of commande to update + * @param int $id Id of order to update * @param int $lineid Id of line to update - * @param array $request_data Orderline data + * @param array $request_data OrderLine data * * @url PUT {id}/lines/{lineid} * @@ -310,7 +312,7 @@ class Orders extends DolibarrApi $result = $this->commande->fetch($id); if( ! $result ) { - throw new RestException(404, 'Commande not found'); + throw new RestException(404, 'Order not found'); } if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { @@ -338,7 +340,8 @@ class Orders extends DolibarrApi $request_data->label, $request_data->special_code, $request_data->array_options, - $request_data->fk_unit + $request_data->fk_unit, + $request_data->multicurrency_subprice ); if ($updateRes > 0) { @@ -387,7 +390,7 @@ class Orders extends DolibarrApi /** * Update order general fields (won't touch lines of order) * - * @param int $id Id of commande to update + * @param int $id Id of order to update * @param array $request_data Datas * * @return int @@ -399,7 +402,7 @@ class Orders extends DolibarrApi $result = $this->commande->fetch($id); if( ! $result ) { - throw new RestException(404, 'Commande not found'); + throw new RestException(404, 'Order not found'); } if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { @@ -498,6 +501,47 @@ class Orders extends DolibarrApi ); } + /** + * Close an order (Classify it as "Delivered") + * + * @param int $id Order ID + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return array + */ + function close($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + $result = $this->commande->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Order not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Order: '.$this->commande->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Order closed (Ref='.$this->commande->ref.')' + ) + ); + } + + /** * Clean sensible object datas * @@ -509,6 +553,10 @@ class Orders extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 1ad2d876478..e475615a3d1 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -557,9 +557,10 @@ class Commande extends CommonOrder * Close order * * @param User $user Objet user that close + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int <0 if KO, >0 if OK */ - function cloture($user) + function cloture($user, $notrigger=0) { global $conf; @@ -580,10 +581,13 @@ class Commande extends CommonOrder if ($this->db->query($sql)) { - // Call trigger - $result=$this->call_trigger('ORDER_CLOSE',$user); - if ($result < 0) $error++; - // End call triggers + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ORDER_CLOSE',$user); + if ($result < 0) $error++; + // End call triggers + } if (! $error) { @@ -873,6 +877,11 @@ class Commande extends CommonOrder { $this->ref = $initialref; + if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + { + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds + } + // Add object linked if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) { @@ -885,7 +894,7 @@ class Commande extends CommonOrder $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -896,7 +905,7 @@ class Commande extends CommonOrder $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -1077,11 +1086,12 @@ class Commande extends CommonOrder * Load an object from a proposal and create a new order into database * * @param Object $object Object source + * @param User $user User making creation * @return int <0 if KO, 0 if nothing done, 1 if OK */ - function createFromProposal($object) + function createFromProposal($object, User $user) { - global $conf,$user,$hookmanager; + global $conf, $hookmanager; dol_include_once('/core/class/extrafields.class.php'); @@ -1240,7 +1250,7 @@ class Commande extends CommonOrder { global $mysoc, $conf, $langs, $user; - dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit", LOG_DEBUG); + dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1429,10 +1439,10 @@ class Commande extends CommonOrder return -2; } } - else - { + else + { dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); - return -3; + return -3; } } @@ -1548,7 +1558,7 @@ class Commande extends CommonOrder $sql.= ', c.fk_shipping_method'; $sql.= ', c.fk_warehouse'; $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed'; - $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams'; + $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams'; $sql.= ', c.fk_incoterms, c.location_incoterms'; $sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc"; $sql.= ", i.libelle as libelle_incoterms"; @@ -1603,6 +1613,7 @@ class Commande extends CommonOrder $this->note_public = $obj->note_public; $this->fk_project = $obj->fk_projet; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement_libelle; @@ -3048,48 +3059,6 @@ class Commande extends CommonOrder } } - /** - * Update value of extrafields on order - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - global $hookmanager, $conf; - - $action='create'; - $error = 0; - - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('orderdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (!$error) - { - return 1; - } - else - { - return -1; - } - - } - /** * Delete the customer order * diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 10c1459a087..c792f42f00e 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -1397,7 +1397,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->supprimer; + $delallowed=$user->rights->commande->creer; print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 326e3ece569..a829cdc8cba 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -1114,7 +1114,7 @@ if ($resql) $bankstatic->id=$banklinestatic->fk_account; $bankstatic->label=$banklinestatic->bank_account_ref; print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1); + print $bankstatic->getNomUrl(1,'transactions'); print ' '.$langs->trans("toward").' '; $bankstatic->id=$objp->bankid; $bankstatic->label=$objp->bankref; @@ -1131,7 +1131,7 @@ if ($resql) $banklinestatic->fetch($links[$key]['url_id']); $bankstatic->id=$banklinestatic->fk_account; $bankstatic->label=$banklinestatic->bank_account_ref; - print $bankstatic->getNomUrl(1); + print $bankstatic->getNomUrl(1,'transactions'); print ')'; } //var_dump($links); diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index c6fd3f72def..fa540f43401 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -61,7 +61,7 @@ class BankAccounts extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') { $list = array(); diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 0ecfe01498f..19120e12888 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -74,7 +74,7 @@ $hookmanager->initHooks(array($contextpage)); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('bankaccount'); +$extralabels = $extrafields->fetch_name_optionals_label('bank_account'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // List of fields to search into when doing a "search in all" @@ -143,7 +143,7 @@ $title=$langs->trans('BankAccounts'); // Load array of financial accounts (opened by default) $accounts = array(); -$sql = "SELECT rowid, label, courant, rappro, account_number, fk_accountancy_journal, currency_code, datec as date_creation, tms as date_update"; +$sql = "SELECT b.rowid, b.label, b.courant, b.rappro, b.account_number, b.fk_accountancy_journal, b.currency_code, b.datec as date_creation, b.tms as date_update"; // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); // Add fields from hooks @@ -151,7 +151,7 @@ $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as b"; -if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bankcacount_extrafields as ef on (c.rowid = ef.fk_object)"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account_extrafields as ef on (b.rowid = ef.fk_object)"; $sql.= " WHERE entity IN (".getEntity('bank_account').")"; if ($search_status == 'opened') $sql.= " AND clos = 0"; if ($search_status == 'closed') $sql.= " AND clos = 1"; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 55b128bcb6a..a6f37ae4fc3 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -307,11 +307,11 @@ if (empty($reshook)) $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']); if (empty($date)) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); - exit; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); + exit; } - $object->date=$date; + $object->date=$date; $new_date_lim_reglement = $object->calculate_date_lim_reglement(); if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement; if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date; @@ -323,7 +323,7 @@ if (empty($reshook)) { $object->fetch($id); $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - $object->date_pointoftax=$date_pointoftax; + $object->date_pointoftax=$date_pointoftax; $result = $object->update($user); if ($result < 0) dol_print_error($db, $object->error); } @@ -369,14 +369,14 @@ if (empty($reshook)) // Set incoterm elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + } // bank account else if ($action == 'setbankaccount' && $user->rights->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } else if ($action == 'setremisepercent' && $user->rights->facture->creer) @@ -451,8 +451,8 @@ if (empty($reshook)) // Classify to validated else if ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse','int'); @@ -462,7 +462,7 @@ if (empty($reshook)) // Check parameters - // Check for mandatory fields defined into setup + // Check for mandatory fields defined into setup $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); foreach($array_to_check as $key) { @@ -540,7 +540,7 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } } else @@ -554,7 +554,7 @@ if (empty($reshook)) // Go back to draft status (unvalidate) else if ($action == 'confirm_modif' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) ) { $idwarehouse = GETPOST('idwarehouse'); @@ -831,7 +831,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = $_POST['cond_reglement_id']; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -883,7 +883,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = 0; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -899,62 +899,62 @@ if (empty($reshook)) if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) { - $facture_source = new Facture($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source)>0) - { - $fk_parent_line = 0; + $facture_source = new Facture($db); // fetch origin object + if ($facture_source->fetch($object->fk_facture_source)>0) + { + $fk_parent_line = 0; - foreach($facture_source->lines as $line) - { - // Reset fk_parent_line for no child products and special product - if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { - $fk_parent_line = 0; - } + foreach($facture_source->lines as $line) + { + // Reset fk_parent_line for no child products and special product + if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { + $fk_parent_line = 0; + } - $line->fk_facture = $object->id; - $line->fk_parent_line = $fk_parent_line; + $line->fk_facture = $object->id; + $line->fk_parent_line = $fk_parent_line; - $line->subprice = -$line->subprice; // invert price for object - $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here - $line->total_ht = -$line->total_ht; - $line->total_tva = -$line->total_tva; - $line->total_ttc = -$line->total_ttc; - $line->total_localtax1 = -$line->total_localtax1; - $line->total_localtax2 = -$line->total_localtax2; + $line->subprice = -$line->subprice; // invert price for object + $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here + $line->total_ht = -$line->total_ht; + $line->total_tva = -$line->total_tva; + $line->total_ttc = -$line->total_ttc; + $line->total_localtax1 = -$line->total_localtax1; + $line->total_localtax2 = -$line->total_localtax2; - $line->multicurrency_subprice = -$line->multicurrency_subprice; - $line->multicurrency_total_ht = -$line->multicurrency_total_ht; - $line->multicurrency_total_tva = -$line->multicurrency_total_tva; - $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; + $line->multicurrency_subprice = -$line->multicurrency_subprice; + $line->multicurrency_total_ht = -$line->multicurrency_total_ht; + $line->multicurrency_total_tva = -$line->multicurrency_total_tva; + $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; - $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked + $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked - $object->lines[] = $line; // insert new line in current object + $object->lines[] = $line; // insert new line in current object - // Defined the new fk_parent_line - if ($result > 0 && $line->product_type == 9) { - $fk_parent_line = $result; - } - } + // Defined the new fk_parent_line + if ($result > 0 && $line->product_type == 9) { + $fk_parent_line = $result; + } + } - $object->update_price(1); - } + $object->update_price(1); + } } - if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) - { - $facture_source = new Facture($db); // fetch origin object if not previously defined - if ($facture_source->fetch($object->fk_facture_source)>0) - { - $totalpaye = $facture_source->getSommePaiement(); - $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); - $totaldeposits = $facture_source->getSumDepositsUsed(); - $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits); + if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) + { + $facture_source = new Facture($db); // fetch origin object if not previously defined + if ($facture_source->fetch($object->fk_facture_source)>0) + { + $totalpaye = $facture_source->getSommePaiement(); + $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); + $totaldeposits = $facture_source->getSumDepositsUsed(); + $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits); - $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); - } - } + $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); + } + } } } @@ -985,7 +985,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; @@ -1035,7 +1035,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; @@ -1117,7 +1117,7 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines"); $result = $srcobject->fetch($object->origin_id); - // If deposit invoice + // If deposit invoice if ($_POST['type'] == Facture::TYPE_DEPOSIT) { $typeamount = GETPOST('typedeposit', 'alpha'); @@ -1167,8 +1167,8 @@ if (empty($reshook)) if ($totalamount != 0) { if ($numlines > 0) $numlines = $numlines-1; - $tva_tx = $lines[$numlines]->tva_tx; - if (! empty($lines[$numlines]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$numlines]->vat_src_code.')'; + $tva_tx = $lines[$numlines]->tva_tx; + if (! empty($lines[$numlines]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$numlines]->vat_src_code.')'; $amountdeposit[$tva_tx] = ($totalamount * $valuedeposit) / 100; } else { $amountdeposit[0] = 0; @@ -1205,7 +1205,7 @@ if (empty($reshook)) 0, // date_start 0, // date_end 0, - $lines[$i]->info_bits, // info_bits + $lines[$i]->info_bits, // info_bits 0, 'HT', 0, @@ -1367,8 +1367,8 @@ if (empty($reshook)) // modified by hook if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $error++; + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + $error++; } } else { @@ -1540,16 +1540,16 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error ++; } - if (!$prod_entry_mode) - { - if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) - { - setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); - $error ++; - } - } + if (!$prod_entry_mode) + { + if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) + { + setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); + $error ++; + } + } if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('type') < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error ++; } if ($prod_entry_mode == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '') && $price_ht_devise == '') // Unit price can be 0 but not '' @@ -1634,8 +1634,8 @@ if (empty($reshook)) $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; if (empty($tva_tx)) $tva_npr=0; } } @@ -1790,18 +1790,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); unset($_POST['situations']); unset($_POST['progress']); @@ -1966,18 +1966,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); unset($_POST['situations']); unset($_POST['progress']); @@ -2020,10 +2020,10 @@ if (empty($reshook)) $trackid='inv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Actions to build doc - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; if ($action == 'update_extras') { @@ -2195,7 +2195,7 @@ if ($action == 'create') $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); @@ -2238,14 +2238,14 @@ if ($action == 'create') if ($origin == 'contrat') { - $langs->load("admin"); - $text=$langs->trans("ToCreateARecurringInvoice"); - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); - if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) - { - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); - } - print info_admin($text, 0, 0, 0).'
'; + $langs->load("admin"); + $text=$langs->trans("ToCreateARecurringInvoice"); + $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); + if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) + { + $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); + } + print info_admin($text, 0, 0, 0).'
'; } print '
'; @@ -2303,7 +2303,7 @@ if ($action == 'create') }); '; } - print ' '.$langs->trans("AddThirdParty").''; + print ' '.$langs->trans("AddThirdParty").''; print ''; } print '' . "\n"; @@ -2313,16 +2313,16 @@ if ($action == 'create') // Overwrite value if creation of invoice is from a predefined invoice if (empty($origin) && empty($originid) && GETPOST('fac_rec','int') > 0) { - $invoice_predefined = new FactureRec($db); - $invoice_predefined->fetch(GETPOST('fac_rec','int')); + $invoice_predefined = new FactureRec($db); + $invoice_predefined->fetch(GETPOST('fac_rec','int')); - $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later - if (empty($projectid)) $projectid = $invoice_predefined->fk_project; - $cond_reglement_id = $invoice_predefined->cond_reglement_id; - $mode_reglement_id = $invoice_predefined->mode_reglement_id; - $fk_account = $invoice_predefined->fk_account; - $note_public = $invoice_predefined->note_public; - $note_private = $invoice_predefined->note_private; + $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later + if (empty($projectid)) $projectid = $invoice_predefined->fk_project; + $cond_reglement_id = $invoice_predefined->cond_reglement_id; + $mode_reglement_id = $invoice_predefined->mode_reglement_id; + $fk_account = $invoice_predefined->fk_account; + $note_public = $invoice_predefined->note_public; + $note_private = $invoice_predefined->note_private; $sql = 'SELECT r.rowid, r.titre, r.total_ttc'; $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r'; @@ -2345,17 +2345,17 @@ if ($action == 'create') print ''; $i ++; } print ''; // Option to reload page to retrieve customer informations. Note, this clear other input - if (!empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE)) - { - print ''; - } + } print ''; } $db->free($resql); @@ -2433,9 +2433,9 @@ if ($action == 'create') // Deposit if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) { - print '
'; - $tmp=' '; - print ''; - $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); - print ''; - if (($origin == 'propal') || ($origin == 'commande')) - { - print ''; - print '
'; - print $desc; - print ''; - $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); - print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); - print '' . $langs->trans('Value') . ':'; - } - print '
'; + $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); + print ''; + if (($origin == 'propal') || ($origin == 'commande')) + { + print ''; + print '
'; + print $desc; + print ''; + $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); + print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); + print '' . $langs->trans('Value') . ':'; + } + print '
'; - print '
'; + print '
'; } } @@ -2490,33 +2490,33 @@ if ($action == 'create') // Replacement if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) { - print ''; - print '
'; - $tmp=' + print ''; + print '
'; + $tmp=' jQuery(document).ready(function() { jQuery("#fac_replacement").change(function() { jQuery("#radio_replacement").prop("checked", true); }); }); '; - $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' '; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); - print $desc; - print '
'; + $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' '; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
'; } } else @@ -2534,15 +2534,15 @@ if ($action == 'create') { if ($socid > 0) { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
'; - $tmp=' + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) + { + print '
'; + $tmp=' jQuery(document).ready(function() { if (! jQuery("#radio_creditnote").is(":checked")) { @@ -2556,29 +2556,29 @@ if ($action == 'create') }); }); '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; - print '
'; - print '    0 ? 'checked':'').' /> "; - print '
    0 ? 'checked':'').' /> "; - print '
'; + print '
'; + print '    0 ? 'checked':'').' /> "; + print '
    0 ? 'checked':'').' /> "; + print '
'; - print '
'; - } + print '
'; + } } else { @@ -2652,14 +2652,14 @@ if ($action == 'create') $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id', 'CRDT'); print ''; - // Bank Account + // Bank Account if (isset($_POST['fk_account'])) { $fk_account = $_POST['fk_account']; } - print '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; + print '' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; // Project if (! empty($conf->projet->enabled) && $socid > 0) @@ -2676,22 +2676,22 @@ if ($action == 'create') { print ''; print ''; - print ''; - $incoterm_id = GETPOST('incoterm_id'); - $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { - $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); - $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); - } - print $form->select_incoterms($incoterm_id, $incoterm_location); + print ''; + $incoterm_id = GETPOST('incoterm_id'); + $incoterm_location = GETPOST('location_incoterms'); + if (empty($incoterm_id)) + { + $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); + $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); + } + print $form->select_incoterms($incoterm_id, $incoterm_location); print ''; } // Other attributes $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="2"', 'cols'=>2); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -2709,8 +2709,8 @@ if ($action == 'create') { print ''; print ''.fieldLabel('Currency','multicurrency_code').''; - print ''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print ''; } @@ -2718,28 +2718,28 @@ if ($action == 'create') $htmltext=''; if (GETPOST('fac_rec','int') > 0) { - $dateexample=($datefacture ? $datefacture : $dateinvoice); - if (empty($dateexample)) $dateexample=dol_now(); - $substitutionarray=array( - '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')', - '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')', - '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', - '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', - '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', - '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', - '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', - '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', - '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', - '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', - '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' - ); + $dateexample=($datefacture ? $datefacture : $dateinvoice); + if (empty($dateexample)) $dateexample=dol_now(); + $substitutionarray=array( + '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')', + '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')', + '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', + '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', + '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', + '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', + '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', + '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', + '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', + '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', + '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' + ); - $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($substitutionarray as $key => $val) - { - $htmltext.=$key.' = '.$langs->trans($val).'
'; - } - $htmltext.='
'; + $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; + foreach($substitutionarray as $key => $val) + { + $htmltext.=$key.' = '.$langs->trans($val).'
'; + } + $htmltext.='
'; } // Public note @@ -2810,8 +2810,8 @@ if ($action == 'create') $cntinvoice=count($objectsrc->linkedObjects['facture']); if ($cntinvoice>=1) { - setEventMessages('WarningBillExist', null, 'warnings'); - echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; + setEventMessages('WarningBillExist', null, 'warnings'); + echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; } echo ''; print '' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . ''; @@ -3179,34 +3179,34 @@ else if ($id > 0 || ! empty($ref)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->facture->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
'; @@ -3259,7 +3259,7 @@ else if ($id > 0 || ! empty($ref)) $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, $object->id); if ($result > 0){ - print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
'; + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
'; } } print ''; @@ -3501,16 +3501,16 @@ else if ($id > 0 || ! empty($ref)) print $langs->trans('BankAccount'); print ''; if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; print ''; print ''; if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); } print ""; print ''; @@ -3568,14 +3568,14 @@ else if ($id > 0 || ! empty($ref)) if (!empty($conf->incoterm->enabled)) { print ''; - print '
'; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->facture->creer) print ''.img_edit().''; - else print ' '; - print '
'; - print ''; - print ''; + print '
'; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->facture->creer) print ''.img_edit().''; + else print ' '; + print '
'; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -3584,7 +3584,7 @@ else if ($id > 0 || ! empty($ref)) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } // Other attributes @@ -3602,20 +3602,20 @@ else if ($id > 0 || ! empty($ref)) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Amount @@ -3629,40 +3629,40 @@ else if ($id > 0 || ! empty($ref)) // Amount Local Taxes if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 { - print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . ''; - print '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . ''; + print '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . ''; } if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 { - print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . ''; - print '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . ''; + print '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . ''; } // Revenue stamp if ($selleruserevenustamp) // Test company use revenue stamp { - print ''; - print ''; - if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) - { - print ''; - } - print '
'; - print $langs->trans('RevenueStamp'); - print 'id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '
'; - print ''; - if ($action == 'editrevenuestamp') { - print '
'; - print ''; - print ''; - print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code); - // print ''; - print ' '; - print '
'; - } else { - print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); - } - print ''; + print ''; + print ''; + if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) + { + print ''; + } + print '
'; + print $langs->trans('RevenueStamp'); + print 'id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '
'; + print ''; + if ($action == 'editrevenuestamp') { + print '
'; + print ''; + print ''; + print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code); + // print ''; + print ' '; + print '
'; + } else { + print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); + } + print ''; } // Total with tax @@ -3675,165 +3675,165 @@ else if ($id > 0 || ! empty($ref)) $sign = 1; if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1; - $nbrows = 8; - $nbcols = 3; - if (! empty($conf->projet->enabled)) - $nbrows ++; - if (! empty($conf->banque->enabled)) { - $nbrows ++; - $nbcols ++; - } - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) - $nbrows ++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) - $nbrows ++; - if ($selleruserevenustamp) - $nbrows ++; - if (! empty($conf->multicurrency->enabled)) - $nbrows += 5; - if (! empty($conf->incoterm->enabled)) - $nbrows += 1; + $nbrows = 8; + $nbcols = 3; + if (! empty($conf->projet->enabled)) + $nbrows ++; + if (! empty($conf->banque->enabled)) { + $nbrows ++; + $nbcols ++; + } + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) + $nbrows ++; + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) + $nbrows ++; + if ($selleruserevenustamp) + $nbrows ++; + if (! empty($conf->multicurrency->enabled)) + $nbrows += 5; + if (! empty($conf->incoterm->enabled)) + $nbrows += 1; - if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) - { - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print ''; + if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) + { + if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) + print '
'; - if (count($object->tab_previous_situation_invoice) > 0) { - // List of previous invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + if (count($object->tab_previous_situation_invoice) > 0) { + // List of previous invoices + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - $total_prev_ht = $total_prev_ttc = 0; - foreach ($object->tab_previous_situation_invoice as $prev_invoice) { - $totalpaye = $prev_invoice->getSommePaiement(); - $total_prev_ht += $prev_invoice->total_ht; - $total_prev_ttc += $prev_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + $total_prev_ht = $total_prev_ttc = 0; + foreach ($object->tab_previous_situation_invoice as $prev_invoice) { + $totalpaye = $prev_invoice->getSommePaiement(); + $total_prev_ht += $prev_invoice->total_ht; + $total_prev_ttc += $prev_invoice->total_ttc; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - } + } - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + } - if (count($object->tab_next_situation_invoice) > 0) { - // List of next invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + if (count($object->tab_next_situation_invoice) > 0) { + // List of next invoices + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - $total_next_ht = $total_next_ttc = 0; + $total_next_ht = $total_next_ttc = 0; - foreach ($object->tab_next_situation_invoice as $next_invoice) { - $totalpaye = $next_invoice->getSommePaiement(); - $total_next_ht += $next_invoice->total_ht; - $total_next_ttc += $next_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + foreach ($object->tab_next_situation_invoice as $next_invoice) { + $totalpaye = $next_invoice->getSommePaiement(); + $total_next_ht += $next_invoice->total_ht; + $total_next_ttc += $next_invoice->total_ttc; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - } + } - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; + } - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print '
' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
'; - } + if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) + print ''; + } - // List of payments already done + // List of payments already done - print ''; + print '
'; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) { - print ''; - } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; + print ''; - // Payments already done (from payment on this invoice) - $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; - $sql .= ' c.code as payment_code, c.libelle as payment_label,'; - $sql .= ' pf.amount,'; - $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; - $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; - $sql .= ' AND c.entity IN (' . getEntity('c_paiement').')'; - $sql .= ' ORDER BY p.datep, p.tms'; + // Payments already done (from payment on this invoice) + $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; + $sql .= ' c.code as payment_code, c.libelle as payment_label,'; + $sql .= ' pf.amount,'; + $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; + $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; + $sql .= ' AND c.entity IN (' . getEntity('c_paiement').')'; + $sql .= ' ORDER BY p.datep, p.tms'; - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; - // if ($object->type != 2) - // { - if ($num > 0) { - while ($i < $num) { - $objp = $db->fetch_object($result); + // if ($object->type != 2) + // { + if ($num > 0) { + while ($i < $num) { + $objp = $db->fetch_object($result); - $paymentstatic->id = $objp->rowid; - $paymentstatic->datepaye = $db->jdate($objp->dp); - $paymentstatic->ref = $objp->ref; - $paymentstatic->num_paiement = $objp->num_paiement; - $paymentstatic->payment_code = $objp->payment_code; + $paymentstatic->id = $objp->rowid; + $paymentstatic->datepaye = $db->jdate($objp->dp); + $paymentstatic->ref = $objp->ref; + $paymentstatic->num_paiement = $objp->num_paiement; + $paymentstatic->payment_code = $objp->payment_code; - print ''; - print ''; - $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label; - print ''; - if (! empty($conf->banque->enabled)) - { - $bankaccountstatic->id = $objp->baid; - $bankaccountstatic->ref = $objp->baref; - $bankaccountstatic->label = $objp->baref; + print ''; + print ''; + $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label; + print ''; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; $bankaccountstatic->number = $objp->banumber; if (! empty($conf->accounting->enabled)) { @@ -3845,155 +3845,155 @@ else if ($id > 0 || ! empty($ref)) } print ''; - } - print ''; - print ''; - print ''; - $i ++; - } - } - /*else { + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print ''; + } + print ''; + print ''; + print ''; + $i ++; + } + } + /*else { print ''; }*/ - // } - $db->free($result); - } else { - dol_print_error($db); - } + // } + $db->free($result); + } else { + dol_print_error($db); + } - if ($object->type != Facture::TYPE_CREDIT_NOTE) { - // Total already paid - print ''; + if ($object->type != Facture::TYPE_CREDIT_NOTE) { + // Total already paid + print ''; - $resteapayeraffiche = $resteapayer; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + $resteapayeraffiche = $resteapayer; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - // Loop on each credit note or deposit amount applied - $creditnoteamount = 0; - $depositamount = 0; - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_facture = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new Facture($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_facture_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == Facture::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; - } - } else { - dol_print_error($db); - } + // Loop on each credit note or deposit amount applied + $creditnoteamount = 0; + $depositamount = 0; + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_facture_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_facture = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new Facture($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_facture_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == Facture::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); + } - // Paye partiellement 'escompte' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'badcustomer' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { - print ''; - // $resteapayeraffiche=0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'product_returned' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'abandon' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } + // Paye partiellement 'escompte' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'badcustomer' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { + print ''; + // $resteapayeraffiche=0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'product_returned' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'abandon' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } - // Billed - print ''; + // Billed + print ''; - // Remainder to pay - print ''; - print ''; - print ''; - } - else // Credit note - { - $cssforamountpaymentcomplete=''; + // Remainder to pay + print ''; + print ''; + print ''; + } + else // Credit note + { + $cssforamountpaymentcomplete=''; - // Total already paid back - print ''; + // Total already paid back + print ''; - // Billed - print ''; + // Billed + print ''; - // Remainder to pay back - print ''; - print ''; - print ''; + // Remainder to pay back + print ''; + print ''; + print ''; - // Sold credit note - // print ''; - // print ''; - } + // Sold credit note + // print ''; + // print ''; + } - print '
' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '' . $langs->trans('Date') . '' . $langs->trans('Type') . '' . $langs->trans('BankAccount') . '' . $langs->trans('Amount') . ' 
' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '' . $langs->trans('Date') . '' . $langs->trans('Type') . '' . $langs->trans('BankAccount') . '' . $langs->trans('Amount') . ' 
'; - print $paymentstatic->getNomUrl(1); - print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . '
'; + print $paymentstatic->getNomUrl(1); + print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . ''; - if ($bankaccountstatic->id) - print $bankaccountstatic->getNomUrl(1, 'transactions'); - print '' . price($sign * $objp->amount) . ' 
' . price($sign * $objp->amount) . ' 
' . $langs->trans("None") . '
'; - if ($object->type != Facture::TYPE_DEPOSIT) - print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); - else - print $langs->trans('AlreadyPaid'); - print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
'; + if ($object->type != Facture::TYPE_DEPOSIT) + print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); + else + print $langs->trans('AlreadyPaid'); + print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
'; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == Facture::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
'; + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == Facture::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
'; - print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; - print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; - $text = $langs->trans("HelpAbandonOther"); - if ($object->close_note) - $text .= '

' . $langs->trans("Reason") . ':' . $object->close_note; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); - print '
' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + $text = $langs->trans("HelpAbandonOther"); + if ($object->close_note) + $text .= '

' . $langs->trans("Reason") . ':' . $object->close_note; + print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); + print '
' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
'; - if ($resteapayeraffiche >= 0) - print $langs->trans('RemainderToPay'); - else - print $langs->trans('ExcessReceived'); - print ' :' . price($resteapayeraffiche) . ' 
'; + if ($resteapayeraffiche >= 0) + print $langs->trans('RemainderToPay'); + else + print $langs->trans('ExcessReceived'); + print ' :' . price($resteapayeraffiche) . ' 
'; - print $langs->trans('AlreadyPaidBack'); - print ' :' . price($sign * $totalpaye) . ' 
'; + print $langs->trans('AlreadyPaidBack'); + print ' :' . price($sign * $totalpaye) . ' 
' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
'; - if ($resteapayeraffiche <= 0) - print $langs->trans('RemainderToPayBack'); - else - print $langs->trans('ExcessPaydBack'); - print ' :' . price($sign * $resteapayeraffiche) . ' 
'; + if ($resteapayeraffiche <= 0) + print $langs->trans('RemainderToPayBack'); + else + print $langs->trans('ExcessPaydBack'); + print ' :' . price($sign * $resteapayeraffiche) . ' 
'.$langs->trans('TotalTTC').' :'.price($sign * - // $object->total_ttc).' 
'.$langs->trans('TotalTTC').' :'.price($sign * + // $object->total_ttc).' 
'; + print ''; // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print '
'; @@ -4084,7 +4084,7 @@ else if ($id > 0 || ! empty($ref)) '; if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } print '
'; @@ -4110,7 +4110,7 @@ else if ($id > 0 || ! empty($ref)) } print "\n"; - print "
"; + print "
"; print "\n"; @@ -4138,8 +4138,8 @@ else if ($id > 0 || ! empty($ref)) { if (! $objectidnext && $object->is_last_in_cycle()) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) { print ''; } else { @@ -4166,7 +4166,7 @@ else if ($id > 0 || ! empty($ref)) || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id)) || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))) && ($object->statut == 2 || $object->statut == 3 || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data - && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely) + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely) { if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice { @@ -4179,7 +4179,7 @@ else if ($id > 0 || ! empty($ref)) // Validate if ($object->statut == Facture::STATUS_DRAFT && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) { print ''; } @@ -4200,22 +4200,22 @@ else if ($id > 0 || ! empty($ref)) // Request a direct debit order if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0) { - if ($resteapayer > 0) - { - if ($user->rights->prelevement->bons->creer) - { - $langs->load("withdrawals"); - print ''.$langs->trans("MakeWithdrawRequest").''; - } - else - { - //print ''.$langs->trans("MakeWithdrawRequest").''; - } - } - else - { - //print ''.$langs->trans("MakeWithdrawRequest").''; - } + if ($resteapayer > 0) + { + if ($user->rights->prelevement->bons->creer) + { + $langs->load("withdrawals"); + print ''.$langs->trans("MakeWithdrawRequest").''; + } + else + { + //print ''.$langs->trans("MakeWithdrawRequest").''; + } + } + else + { + //print ''.$langs->trans("MakeWithdrawRequest").''; + } } // Create payment @@ -4364,8 +4364,8 @@ else if ($id > 0 || ! empty($ref)) $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id; - $genallowed = $user->rights->facture->creer; - $delallowed = $user->rights->facture->supprimer; + $genallowed = $user->rights->facture->lire; + $delallowed = $user->rights->facture->creer; print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); $somethingshown = $formfile->numoffiles; @@ -4378,7 +4378,7 @@ else if ($id > 0 || ! empty($ref)) // Show online payment link $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)); - if ($object->statut != 0 && $useonlinepayment) + if ($object->statut != Facture::STATUS_DRAFT && $useonlinepayment) { print '
'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; diff --git a/htdocs/compta/facture/class/api_deprecated_invoice.class.php b/htdocs/compta/facture/class/api_deprecated_invoice.class.php index 360c065a5f2..ac2086fc87e 100644 --- a/htdocs/compta/facture/class/api_deprecated_invoice.class.php +++ b/htdocs/compta/facture/class/api_deprecated_invoice.class.php @@ -23,7 +23,7 @@ * API class for invoice object * * @smart-auto-routing false - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} * @deprecated Use Invoices instead (defined in api_invoices.class.php) */ @@ -31,7 +31,7 @@ class InvoiceApi extends DolibarrApi { /** * - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'socid' @@ -46,7 +46,7 @@ class InvoiceApi extends DolibarrApi * Constructor Warning: Deprecated * * @url GET invoice/ - * + * */ function __construct() { @@ -59,7 +59,7 @@ class InvoiceApi extends DolibarrApi * Get properties of a invoice object Warning: Deprecated * * Return an array with invoice informations - * + * * @param int $id ID of invoice * @return array|mixed data without useless information * @@ -67,16 +67,16 @@ class InvoiceApi extends DolibarrApi * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - + $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -86,9 +86,9 @@ class InvoiceApi extends DolibarrApi /** * List invoices Warning: Deprecated - * + * * Get a list of invoices - * + * * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -101,15 +101,15 @@ class InvoiceApi extends DolibarrApi * @url GET invoice/list * @url GET invoice/list/{mode} * @url GET thirdparty/{socid}/invoice/list - * @url GET thirdparty/{socid}/invoice/list/{mode} + * @url GET thirdparty/{socid}/invoice/list/{mode} */ - function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $mode='') { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $socid=0, $mode='') { global $db, $conf; - + $obj_ret = array(); - + $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $socid; - + // If the internal user must only see his customers, force searching by him $search_sale = 0; if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; @@ -117,27 +117,27 @@ class InvoiceApi extends DolibarrApi $sql = "SELECT s.rowid"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) $sql.= " FROM ".MAIN_DB_PREFIX."facture as s"; - + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale $sql.= ' WHERE s.entity IN ('.getEntity('facture').')'; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc"; if ($socid) $sql.= " AND s.fk_soc = ".$socid; if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - - + + // Example of use $mode if ($mode == 'draft') $sql.= " AND s.fk_statut IN (0)"; if ($mode == 'unpaid') $sql.= " AND s.fk_statut IN (1)"; if ($mode == 'paid') $sql.= " AND s.fk_statut IN (2)"; if ($mode == 'cancelled') $sql.= " AND s.fk_statut IN (3)"; - + // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - + $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { @@ -180,10 +180,10 @@ class InvoiceApi extends DolibarrApi } return $obj_ret; } - + /** * Create invoice object Warning: Deprecated - * + * * @param array $request_data Request datas * @return int ID of invoice * @@ -196,7 +196,7 @@ class InvoiceApi extends DolibarrApi } // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->invoice->$field = $value; } @@ -213,9 +213,9 @@ class InvoiceApi extends DolibarrApi * Update invoice Warning: Deprecated * * @param int $id Id of invoice to update - * @param array $request_data Datas - * @return int - * + * @param array $request_data Datas + * @return int + * * @url PUT invoice/{id} */ function put($id, $request_data = NULL) @@ -223,12 +223,12 @@ class InvoiceApi extends DolibarrApi if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } - + $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -237,20 +237,20 @@ class InvoiceApi extends DolibarrApi if ($field == 'id') continue; $this->invoice->$field = $value; } - + if($this->invoice->update($id, DolibarrApiAccess::$user)) return $this->get ($id); - + return false; } - + /** * Delete invoice Warning: Deprecated * * @param int $id Invoice ID * @return type - * - * @url DELETE invoice/{id} + * + * @url DELETE invoice/{id} */ function delete($id) { @@ -261,31 +261,31 @@ class InvoiceApi extends DolibarrApi if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->facture->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if( !$this->invoice->delete(DolibarrApiAccess::$user)) { throw new RestException(500); } - + return array( 'success' => array( 'code' => 200, 'message' => 'Facture deleted' ) ); - + } - + /** * Validate fields before create or update object - * + * * @param array $data Datas to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index d8a5a231593..344a5d280c7 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -15,9 +15,9 @@ * along with this program. If not, see . */ - use Luracast\Restler\RestException; +use Luracast\Restler\RestException; - require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; /** * API class for invoices @@ -75,6 +75,7 @@ class Invoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); } @@ -94,7 +95,7 @@ class Invoices extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -210,6 +211,142 @@ class Invoices extends DolibarrApi return $this->invoice->id; } + /** + * Get lines of an invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Update a line to a given invoice + * + * @param int $id Id of invoice to update + * @param int $lineid Id of line to update + * @param array $request_data InvoiceLine data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->invoice->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_start, + $request_data->date_end, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->situation_percent, + $request_data->fk_unit, + $request_data->multicurrency_subprice + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + + /** + * Deletes a line of a given invoice + * + * @param int $id Id of invoice + * @param int $lineid Id of the line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return array + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function deleteLine($id, $lineid) { + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($lineid)) { + throw new RestException(400, 'Line ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + $result = $this->invoice->deleteline($lineid); + if( $result < 0) { + throw new RestException(405, $this->invoice->error); + } + + $result = $this->invoice->fetch($id); + + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + /** * Update invoice * @@ -276,95 +413,15 @@ class Invoices extends DolibarrApi ); } - /** - * Get lines of a given invoice - * - * @param int $id Id of invoice - * - * @url GET {id}/lines - * - * @return array - */ - function getLines($id) { - if(! DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Invoice not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->invoice->getLinesArray(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - - /** - * Deletes a line of a given invoice - * - * @param int $id Id of invoice - * @param int $lineid Id of the line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return array - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 - */ - function deleteLine($id, $lineid) { - - if(! DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if(empty($lineid)) { - throw new RestException(400, 'Line ID is mandatory'); - } - - if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->invoice->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Invoice not found'); - } - - $result = $this->invoice->deleteline($lineid); - if( $result < 0) { - throw new RestException(405, $this->invoice->error); - } - - $result = $this->invoice->fetch($id); - - $this->invoice->getLinesArray(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - - - - /** * Add a line to a given invoice * * Exemple of POST query : { "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null } * * @param int $id Id of invoice - * @param array $request_data Invoiceline data + * @param array $request_data InvoiceLine data * - * @url POST {id}/addline + * @url POST {id}/lines * * @return int */ @@ -421,7 +478,7 @@ class Invoices extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } throw new RestException(400, 'Unable to insert the new line. Check your inputs.'); @@ -482,7 +539,7 @@ class Invoices extends DolibarrApi /** * Validate an invoice * - * @param int $id Order ID + * @param int $id Invoice ID * @param int $idwarehouse Warehouse ID * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @@ -600,6 +657,10 @@ class Invoices extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index dd42c8d3fb7..b46c249d1b0 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -201,19 +201,40 @@ class FactureRec extends CommonInvoice } } - // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) - { - foreach($this->linked_objects as $origin => $origin_id) - { - $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) - { - $this->error=$this->db->lasterror(); - $error++; - } - } - } + if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + { + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds + } + + // Add object linked + if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) + { + foreach($this->linked_objects as $origin => $tmp_origin_id) + { + if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + { + foreach($tmp_origin_id as $origin_id) + { + $ret = $this->add_object_linked($origin, $origin_id); + if (! $ret) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1)) + { + $origin_id = $tmp_origin_id; + $ret = $this->add_object_linked($origin, $origin_id); + if (! $ret) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + } if ($error) { diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 6452c689215..a1997318aad 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -448,6 +448,11 @@ class Facture extends CommonInvoice $resql=$this->db->query($sql); if (! $resql) $error++; + if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + { + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds + } + // Add object linked if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) { @@ -460,7 +465,7 @@ class Facture extends CommonInvoice $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -471,7 +476,7 @@ class Facture extends CommonInvoice $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -747,7 +752,7 @@ class Facture extends CommonInvoice * @param int $invertdetail Reverse sign of amounts for lines * @return int <0 if KO, >0 if OK */ - function createFromCurrent($user,$invertdetail=0) + function createFromCurrent(User $user, $invertdetail=0) { global $conf; @@ -948,11 +953,12 @@ class Facture extends CommonInvoice * Load an object from an order and create a new invoice into database * * @param Object $object Object source + * @param User $user Object user * @return int <0 if KO, 0 if nothing done, 1 if OK */ - function createFromOrder($object) + function createFromOrder($object, User $user) { - global $user,$hookmanager; + global $hookmanager; $error=0; @@ -1192,7 +1198,7 @@ class Facture extends CommonInvoice $sql.= ', f.datec as datec'; $sql.= ', f.date_valid as datev'; $sql.= ', f.tms as datem'; - $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf'; + $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf, f.last_main_doc'; $sql.= ', f.fk_facture_source'; $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams'; $sql.= ', f.situation_cycle_ref, f.situation_counter, f.situation_final'; @@ -1261,6 +1267,7 @@ class Facture extends CommonInvoice $this->user_author = $obj->fk_user_author; $this->user_valid = $obj->fk_user_valid; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->situation_cycle_ref = $obj->situation_cycle_ref; $this->situation_counter = $obj->situation_counter; $this->situation_final = $obj->situation_final; @@ -2686,6 +2693,11 @@ class Facture extends CommonInvoice return -2; } } + else + { + dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); + return -3; + } } /** @@ -2698,7 +2710,7 @@ class Facture extends CommonInvoice * @param double $remise_percent Pourcentage de remise de la ligne * @param int $date_start Date de debut de validite du service * @param int $date_end Date de fin de validite du service - * @param double $txtva VAT Rate + * @param double $txtva VAT Rate (Can be '8.5', '8.5 (ABC)') * @param double $txlocaltax1 Local tax 1 rate * @param double $txlocaltax2 Local tax 2 rate * @param string $price_base_type HT or TTC diff --git a/htdocs/compta/facture/class/facturestats.class.php b/htdocs/compta/facture/class/facturestats.class.php index b2fd603a394..b6874862286 100644 --- a/htdocs/compta/facture/class/facturestats.class.php +++ b/htdocs/compta/facture/class/facturestats.class.php @@ -39,7 +39,7 @@ class FactureStats extends Stats var $from; var $field; var $where; - + /** * Constructor @@ -56,8 +56,8 @@ class FactureStats extends Stats $this->db = $db; $this->socid = ($socid > 0 ? $socid : 0); $this->userid = $userid; - $this->cachefilesuffix = $mode; - + $this->cachefilesuffix = $mode; + if ($mode == 'customer') { $object=new Facture($this->db); @@ -195,7 +195,7 @@ class FactureStats extends Stats return $this->_getAllByYear($sql); } - + /** * Return nb, amount of predefined product for year * @@ -218,7 +218,7 @@ class FactureStats extends Stats return $this->_getAllByProduct($sql); } - - + + } diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index deffb252d9c..fbdabad8fa0 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -34,8 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; - //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; } require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; @@ -129,526 +129,526 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('cancel','alpha')) $action=''; + if (GETPOST('cancel','alpha')) $action=''; - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Set note - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + // Set note + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - // Do we click on purge search criteria ? - 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_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_montant_mode=''; - $search_montant_term=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_recurring=''; - $search_frequency=''; - $search_unit_frequency=''; - $search_array_options=array(); - } + // Do we click on purge search criteria ? + 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_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_montant_mode=''; + $search_montant_term=''; + $day=''; + $year=''; + $month=''; + $day_date_when=''; + $year_date_when=''; + $month_date_when=''; + $search_recurring=''; + $search_frequency=''; + $search_unit_frequency=''; + $search_array_options=array(); + } - // Mass actions - /*$objectclass='MyObject'; + // Mass actions + /*$objectclass='MyObject'; $objectlabel='MyObject'; $permtoread = $user->rights->mymodule->read; $permtodelete = $user->rights->mymodule->delete; $uploaddir = $conf->mymodule->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ - // Create predefined invoice - if ($action == 'add') - { - if (! GETPOST('titre')) - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); - $action = "create"; - $error++; - } + // Create predefined invoice + if ($action == 'add') + { + if (! GETPOST('titre')) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); + $action = "create"; + $error++; + } - $frequency=GETPOST('frequency', 'int'); - $reyear=GETPOST('reyear'); - $remonth=GETPOST('remonth'); - $reday=GETPOST('reday'); - $rehour=GETPOST('rehour'); - $remin=GETPOST('remin'); - $nb_gen_max=GETPOST('nb_gen_max', 'int'); - //if (empty($nb_gen_max)) $nb_gen_max =0; + $frequency=GETPOST('frequency', 'int'); + $reyear=GETPOST('reyear'); + $remonth=GETPOST('remonth'); + $reday=GETPOST('reday'); + $rehour=GETPOST('rehour'); + $remin=GETPOST('remin'); + $nb_gen_max=GETPOST('nb_gen_max', 'int'); + //if (empty($nb_gen_max)) $nb_gen_max =0; - if (GETPOST('frequency')) - { - if (empty($reyear) || empty($remonth) || empty($reday)) - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors'); - $action = "create"; - $error++; - } - if ($nb_gen_max === '') - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors'); - $action = "create"; - $error++; - } - } + if (GETPOST('frequency')) + { + if (empty($reyear) || empty($remonth) || empty($reday)) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors'); + $action = "create"; + $error++; + } + if ($nb_gen_max === '') + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors'); + $action = "create"; + $error++; + } + } - if (! $error) - { - $object->titre = GETPOST('titre', 'alpha'); - $object->note_private = GETPOST('note_private','none'); - $object->note_public = GETPOST('note_public','none'); - $object->usenewprice = GETPOST('usenewprice'); + if (! $error) + { + $object->titre = GETPOST('titre', 'alpha'); + $object->note_private = GETPOST('note_private','none'); + $object->note_public = GETPOST('note_public','none'); + $object->usenewprice = GETPOST('usenewprice'); - $object->frequency = $frequency; - $object->unit_frequency = GETPOST('unit_frequency', 'alpha'); - $object->nb_gen_max = $nb_gen_max; - $object->auto_validate = GETPOST('auto_validate', 'int'); + $object->frequency = $frequency; + $object->unit_frequency = GETPOST('unit_frequency', 'alpha'); + $object->nb_gen_max = $nb_gen_max; + $object->auto_validate = GETPOST('auto_validate', 'int'); - $object->fk_project = $projectid; + $object->fk_project = $projectid; - $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear); - $object->date_when = $date_next_execution; + $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear); + $object->date_when = $date_next_execution; - // Get first contract linked to invoice used to generate template - if ($id > 0) - { - $srcObject = new Facture($db); - $srcObject->fetch(GETPOST('facid','int')); + // Get first contract linked to invoice used to generate template + if ($id > 0) + { + $srcObject = new Facture($db); + $srcObject->fetch(GETPOST('facid','int')); - $srcObject->fetchObjectLinked(); + $srcObject->fetchObjectLinked(); - if (! empty($srcObject->linkedObjectsIds['contrat'])) - { - $contractidid = reset($srcObject->linkedObjectsIds['contrat']); + if (! empty($srcObject->linkedObjectsIds['contrat'])) + { + $contractidid = reset($srcObject->linkedObjectsIds['contrat']); - $object->origin = 'contrat'; - $object->origin_id = $contractidid; - $object->linked_objects[$object->origin] = $object->origin_id; - } - } + $object->origin = 'contrat'; + $object->origin_id = $contractidid; + $object->linked_objects[$object->origin] = $object->origin_id; + } + } - $db->begin(); + $db->begin(); - $oldinvoice = new Facture($db); - $oldinvoice->fetch($id); + $oldinvoice = new Facture($db); + $oldinvoice->fetch($id); - $result = $object->create($user, $oldinvoice->id); - if ($result > 0) - { - $result=$oldinvoice->delete($user, 1); - if ($result < 0) - { - $error++; - setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); - $action = "create"; - } - } - else - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } + $result = $object->create($user, $oldinvoice->id); + if ($result > 0) + { + $result=$oldinvoice->delete($user, 1); + if ($result < 0) + { + $error++; + setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); + $action = "create"; + } + } + else + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } - if (! $error) - { - $db->commit(); + if (! $error) + { + $db->commit(); - header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); - exit; - } - else - { - $db->rollback(); + header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); + exit; + } + else + { + $db->rollback(); - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } - } - } + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } + } + } - // Delete - if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) - { - $object->delete($user); - header("Location: " . $_SERVER['PHP_SELF'] ); - exit; - } + // Delete + if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) + { + $object->delete($user); + header("Location: " . $_SERVER['PHP_SELF'] ); + exit; + } - // Update field - // Set condition - if ($action == 'setconditions' && $user->rights->facture->creer) - { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + // Update field + // Set condition + if ($action == 'setconditions' && $user->rights->facture->creer) + { + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - } - // Set mode - elseif ($action == 'setmode' && $user->rights->facture->creer) - { - $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - } - // Set project - elseif ($action == 'classin' && $user->rights->facture->creer) - { - $object->setProject(GETPOST('projectid', 'int')); - } - // Set bank account - elseif ($action == 'setref' && $user->rights->facture->creer) - { - //var_dump(GETPOST('ref', 'alpha'));exit; - $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); - if ($result > 0) - { - $object->titre = GETPOST('ref', 'alpha'); - $object->ref = $object->titre; - } - else dol_print_error($db, $object->error, $object->errors); - } - // Set bank account - elseif ($action == 'setbankaccount' && $user->rights->facture->creer) - { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - } - // Set frequency and unit frequency - elseif ($action == 'setfrequency' && $user->rights->facture->creer) - { - $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); - } - // Set next date of execution - elseif ($action == 'setdate_when' && $user->rights->facture->creer) - { - $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); - if (!empty($date)) $object->setNextDate($date); - } - // Set max period - elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) - { - $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); - } - // Set auto validate - elseif ($action == 'setauto_validate' && $user->rights->facture->creer) - { - $object->setAutoValidate(GETPOST('auto_validate', 'int')); - } + } + // Set mode + elseif ($action == 'setmode' && $user->rights->facture->creer) + { + $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + } + // Set project + elseif ($action == 'classin' && $user->rights->facture->creer) + { + $object->setProject(GETPOST('projectid', 'int')); + } + // Set bank account + elseif ($action == 'setref' && $user->rights->facture->creer) + { + //var_dump(GETPOST('ref', 'alpha'));exit; + $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); + if ($result > 0) + { + $object->titre = GETPOST('ref', 'alpha'); + $object->ref = $object->titre; + } + else dol_print_error($db, $object->error, $object->errors); + } + // Set bank account + elseif ($action == 'setbankaccount' && $user->rights->facture->creer) + { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + } + // Set frequency and unit frequency + elseif ($action == 'setfrequency' && $user->rights->facture->creer) + { + $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); + } + // Set next date of execution + elseif ($action == 'setdate_when' && $user->rights->facture->creer) + { + $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); + if (!empty($date)) $object->setNextDate($date); + } + // Set max period + elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) + { + $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); + } + // Set auto validate + elseif ($action == 'setauto_validate' && $user->rights->facture->creer) + { + $object->setAutoValidate(GETPOST('auto_validate', 'int')); + } - // Delete line - if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) - { - $object->fetch($id); - $object->fetch_thirdparty(); + // Delete line + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); - $db->begin(); + $db->begin(); - $line=new FactureLigneRec($db); + $line=new FactureLigneRec($db); - // For triggers - $line->id = $lineid; + // For triggers + $line->id = $lineid; - if ($line->delete($user) > 0) - { - $result=$object->update_price(1); + if ($line->delete($user) > 0) + { + $result=$object->update_price(1); - if ($result > 0) - { - $db->commit(); - $object->fetch($object->id); // Reload lines - } - else - { - $db->rollback(); - setEventMessages($db->lasterror(), null, 'errors'); - } - } - else - { - $db->rollback(); - setEventMessages($line->error, $line->errors, 'errors'); - } - } - else if ($action == 'update_extras') - { - // Fill array 'array_options' with data from update form - $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($result > 0) + { + $db->commit(); + $object->fetch($object->id); // Reload lines + } + else + { + $db->rollback(); + setEventMessages($db->lasterror(), null, 'errors'); + } + } + else + { + $db->rollback(); + setEventMessages($line->error, $line->errors, 'errors'); + } + } + else if ($action == 'update_extras') + { + // Fill array 'array_options' with data from update form + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + if ($ret < 0) + $error ++; - if (! $error) { + if (! $error) { - $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; - } - } else if ($reshook < 0) - $error ++; + $result = $object->insertExtraFields(); + if ($result < 0) { + $error ++; + } + } else if ($reshook < 0) + $error ++; - if ($error) { - $action = 'edit_extras'; - setEventMessages($object->error, $object->errors, 'errors'); - } - } + if ($error) { + $action = 'edit_extras'; + setEventMessages($object->error, $object->errors, 'errors'); + } + } - // Add a new line - if ($action == 'addline' && $user->rights->facture->creer) - { - $langs->load('errors'); - $error = 0; + // Add a new line + if ($action == 'addline' && $user->rights->facture->creer) + { + $langs->load('errors'); + $error = 0; - // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $price_ht = GETPOST('price_ht'); - if (GETPOST('prod_entry_mode') == 'free') - { - $idprod=0; - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - } - else - { - $idprod=GETPOST('idprod', 'int'); - $tva_tx = ''; - } + // Set if we used free entry or predefined product + $predef=''; + $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $price_ht = GETPOST('price_ht'); + if (GETPOST('prod_entry_mode') == 'free') + { + $idprod=0; + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + } + else + { + $idprod=GETPOST('idprod', 'int'); + $tva_tx = ''; + } - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); + $qty = GETPOST('qty' . $predef); + $remise_percent = GETPOST('remise_percent' . $predef); - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) - { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key . $predef]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) + { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key . $predef]); + } + } - if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { - setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); - $error ++; - } - if ($qty == '') { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error ++; - } - if ($qty < 0) { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; - } + if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { + setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); + $error ++; + } + if ($qty == '') { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); + $error ++; + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); + $error ++; + } - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) - { - $ret = $object->fetch($id); - if ($ret < 0) { - dol_print_error($db, $object->error); - exit(); - } - $ret = $object->fetch_thirdparty(); + if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) + { + $ret = $object->fetch($id); + if ($ret < 0) { + dol_print_error($db, $object->error); + exit(); + } + $ret = $object->fetch_thirdparty(); - // Clean parameters - $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); - $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); - $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); + // Clean parameters + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); - // Define special_code for special lines - $special_code = 0; - // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices + // Define special_code for special lines + $special_code = 0; + // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $tva_tx par celui du produit - // Ecrase $base_price_type par celui du produit - // Replaces $fk_unit with the product's - if (! empty($idprod)) - { - $prod = new Product($db); - $prod->fetch($idprod); + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $tva_tx par celui du produit + // Ecrase $base_price_type par celui du produit + // Replaces $fk_unit with the product's + if (! empty($idprod)) + { + $prod = new Product($db); + $prod->fetch($idprod); - $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); + $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); - // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); - $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr=0; + // Update if prices fields are defined + $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); + $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); + if (empty($tva_tx)) $tva_npr=0; - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; - // We define price for product - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) - { - $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; - $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; - if (empty($tva_tx)) $tva_npr=0; - } - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + // We define price for product + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + { + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility + { + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (empty($tva_tx)) $tva_npr=0; + } + } + elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + { + require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; - $prodcustprice = new Productcustomerprice($db); + $prodcustprice = new Productcustomerprice($db); - $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); + $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); - $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result) - { - if (count($prodcustprice->lines) > 0) - { - $pu_ht = price($prodcustprice->lines[0]->price); - $pu_ttc = price($prodcustprice->lines[0]->price_ttc); - $price_base_type = $prodcustprice->lines[0]->price_base_type; - $tva_tx = $prodcustprice->lines[0]->tva_tx; - } - } - } + $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); + if ($result) + { + if (count($prodcustprice->lines) > 0) + { + $pu_ht = price($prodcustprice->lines[0]->price); + $pu_ttc = price($prodcustprice->lines[0]->price_ttc); + $price_base_type = $prodcustprice->lines[0]->price_base_type; + $tva_tx = $prodcustprice->lines[0]->tva_tx; + } + } + } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx)); $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); - // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - elseif ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - } + // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? + if (! empty($price_ht)) + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); + } + // On reevalue prix selon taux tva car taux tva transaction peut etre different + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). + elseif ($tmpvat != $tmpprodvat) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); + } + } - $desc = ''; + $desc = ''; - // Define output language - if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { - $outputlangs = $langs; - $newlang = ''; - if (empty($newlang) && GETPOST('lang_id','aZ09')) - $newlang = GETPOST('lang_id','aZ09'); - if (empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } + // Define output language + if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) + { + $outputlangs = $langs; + $newlang = ''; + if (empty($newlang) && GETPOST('lang_id','aZ09')) + $newlang = GETPOST('lang_id','aZ09'); + if (empty($newlang)) + $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) + { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } - $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; - } - else - { - $desc = $prod->description; - } + $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; + } + else + { + $desc = $prod->description; + } - $desc = dol_concatdesc($desc, $product_desc); + $desc = dol_concatdesc($desc, $product_desc); - // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) - { - $tmptxt = '('; - if (! empty($prod->customcode)) - $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) - $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); - $tmptxt .= ')'; - $desc = dol_concatdesc($desc, $tmptxt); + // Add custom code and origin country into description + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) + { + $tmptxt = '('; + if (! empty($prod->customcode)) + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; + if (! empty($prod->customcode) && ! empty($prod->country_code)) + $tmptxt .= ' - '; + if (! empty($prod->country_code)) + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + $tmptxt .= ')'; + $desc = dol_concatdesc($desc, $tmptxt); - } + } - $type = $prod->type; - $fk_unit = $prod->fk_unit; + $type = $prod->type; + $fk_unit = $prod->fk_unit; - } - else - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); - $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); - $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr=0; - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); - $fk_unit= GETPOST('units', 'alpha'); - } + } + else + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); + $tva_tx = str_replace('*', '', $tva_tx); + if (empty($tva_tx)) $tva_npr=0; + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); + $fk_unit= GETPOST('units', 'alpha'); + } - // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value + // Margin + $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); + $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value - // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); - $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); + // Local Taxes + $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); + $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); - $info_bits = 0; - if ($tva_npr) - $info_bits |= 0x01; + $info_bits = 0; + if ($tva_npr) + $info_bits |= 0x01; - if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) - { - $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); - setEventMessages($mesg, null, 'errors'); - } - else - { - // Insert line - $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); + if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) + { + $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); + setEventMessages($mesg, null, 'errors'); + } + else + { + // Insert line + $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); - if ($result > 0) - { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + if ($result > 0) + { + /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; @@ -665,114 +665,114 @@ if (empty($reshook)) $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines - unset($_POST['prod_entry_mode']); + unset($_POST['prod_entry_mode']); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['product_ref']); - unset($_POST['product_label']); - unset($_POST['product_desc']); - unset($_POST['fournprice']); - unset($_POST['buying_price']); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprod']); - unset($_POST['units']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); - unset($_POST['situations']); - unset($_POST['progress']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + unset($_POST['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } - $action = ''; - } - } - } + $action = ''; + } + } + } - elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel','alpha')) - { - if (! $object->fetch($id) > 0) dol_print_error($db); - $object->fetch_thirdparty(); + elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel','alpha')) + { + if (! $object->fetch($id) > 0) dol_print_error($db); + $object->fetch_thirdparty(); - // Clean parameters - $date_start = ''; - $date_end = ''; - //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - $description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none')); - $pu_ht = GETPOST('price_ht'); - $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - $qty = GETPOST('qty'); + // Clean parameters + $date_start = ''; + $date_end = ''; + //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none')); + $pu_ht = GETPOST('price_ht'); + $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $qty = GETPOST('qty'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); - $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); - // Add buying price - $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + // Add buying price + $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - $objectline = new FactureLigneRec($db); - if ($objectline->fetch(GETPOST('lineid'))) - { - $objectline->array_options=$array_options; - $result=$objectline->insertExtraFields(); - if ($result < 0) - { - setEventMessages($langs->trans('Error').$result, null, 'errors'); - } - } + $objectline = new FactureLigneRec($db); + if ($objectline->fetch(GETPOST('lineid'))) + { + $objectline->array_options=$array_options; + $result=$objectline->insertExtraFields(); + if ($result < 0) + { + setEventMessages($langs->trans('Error').$result, null, 'errors'); + } + } - // Unset extrafield - if (is_array($extralabelsline)) - { - // Get extra fields - foreach ($extralabelsline as $key => $value) - { - unset($_POST["options_" . $key]); - } - } + // Unset extrafield + if (is_array($extralabelsline)) + { + // Get extra fields + foreach ($extralabelsline as $key => $value) + { + unset($_POST["options_" . $key]); + } + } - // Define special_code for special lines - $special_code=GETPOST('special_code'); - if (! GETPOST('qty')) $special_code=3; + // Define special_code for special lines + $special_code=GETPOST('special_code'); + if (! GETPOST('qty')) $special_code=3; - /*$line = new FactureLigne($db); + /*$line = new FactureLigne($db); $line->fetch(GETPOST('lineid')); $percent = $line->get_prev_progress($object->id); @@ -784,69 +784,69 @@ if (empty($reshook)) $result = -1; }*/ - // Check minimum price - $productid = GETPOST('productid', 'int'); - if (! empty($productid)) - { - $product = new Product($db); - $product->fetch($productid); + // Check minimum price + $productid = GETPOST('productid', 'int'); + if (! empty($productid)) + { + $product = new Product($db); + $product->fetch($productid); - $type = $product->type; + $type = $product->type; - $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) - $price_min = $product->multiprices_min [$object->thirdparty->price_level]; + $price_min = $product->price_min; + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + $price_min = $product->multiprices_min [$object->thirdparty->price_level]; - $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); + $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); - // Check price is not lower than minimum (check is done only for standard or replacement invoices) - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) { - setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); - $error ++; - } - } else { - $type = GETPOST('type'); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + // Check price is not lower than minimum (check is done only for standard or replacement invoices) + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) { + setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); + $error ++; + } + } else { + $type = GETPOST('type'); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - // Check parameters - if (GETPOST('type') < 0) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error ++; - } - } - if ($qty < 0) { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; - } + // Check parameters + if (GETPOST('type') < 0) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error ++; + } + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); + $error ++; + } - // Update line - if (! $error) - { - $result = $object->updateline( - GETPOST('lineid'), - $description, - $pu_ht, - $qty, - $vat_rate, - $localtax1_rate, - $localtax1_rate, - GETPOST('productid'), - GETPOST('remise_percent'), - 'HT', - $info_bits, - 0, - 0, - $type, - 0, - $special_code, - $label, - GETPOST('units') - ); + // Update line + if (! $error) + { + $result = $object->updateline( + GETPOST('lineid'), + $description, + $pu_ht, + $qty, + $vat_rate, + $localtax1_rate, + $localtax1_rate, + GETPOST('productid'), + GETPOST('remise_percent'), + 'HT', + $info_bits, + 0, + 0, + $type, + 0, + $special_code, + $label, + GETPOST('units') + ); - if ($result >= 0) - { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + if ($result >= 0) + { + /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = ''; @@ -863,50 +863,50 @@ if (empty($reshook)) $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['productid']); - unset($_POST['remise_percent']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['product_ref']); - unset($_POST['product_label']); - unset($_POST['product_desc']); - unset($_POST['fournprice']); - unset($_POST['buying_price']); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['productid']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprod']); - unset($_POST['units']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); - unset($_POST['situations']); - unset($_POST['progress']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + unset($_POST['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } } @@ -987,7 +987,7 @@ if ($action == 'create') $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext.=$key.' = '.$langs->trans($val).'
'; } $htmltext.='
'; @@ -998,20 +998,20 @@ if ($action == 'create') print ''; print ''; $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); + print $doleditor->Create(1); // Private note if (empty($user->societe_id)) { - print ''; - print ''; - print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); - print ''; - print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - // print ' - print ''; + print ''; + print ''; + print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); + print ''; + print ''; + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + // print ' + print ''; } // Author @@ -1083,7 +1083,7 @@ if ($action == 'create') print ""; - dol_fiche_end(); + dol_fiche_end(); $title = $langs->trans("ProductsAndServices"); @@ -1102,10 +1102,10 @@ if ($action == 'create') // Show object lines if (! empty($object->lines)) { - $disableedit=1; - $disablemove=1; - $disableremove=1; - $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + $disableedit=1; + $disablemove=1; + $disableremove=1; + $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } print "\n"; @@ -1125,9 +1125,9 @@ if ($action == 'create') print "\n"; print '
'; - print '     '; - print ''; - print '
'; + print '     '; + print ''; + print '
'; print "\n"; } else @@ -1171,53 +1171,53 @@ else if ($action != 'editref') $morehtmlref.=$form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2); else $morehtmlref.= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string'); - $morehtmlref.='
'; - // Ref customer - //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); - //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
'; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
'; + $morehtmlref.='
'; + // Ref customer + //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); + //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->facture->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
'; - dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); + dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; print '"; @@ -1309,7 +1309,7 @@ else $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext.=$key.' = '.$langs->trans($val).'
'; } $htmltext.='
'; @@ -1337,16 +1337,16 @@ else print $langs->trans('RIB'); print ''; + print ''; print '
'.$langs->trans("Author").''.$author->getFullName($langs)."
'; if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; print ''; if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); } print ""; print ''; @@ -1356,12 +1356,12 @@ else $cols = 2; include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print ''; + print ''; - print '
'; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; + print '
'; /* @@ -1397,13 +1397,13 @@ else } else { - if ($object->frequency > 0) - { + if ($object->frequency > 0) + { print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); - } - else - { - print $langs->trans("NotARecurringInvoiceTemplate"); + } + else + { + print $langs->trans("NotARecurringInvoiceTemplate"); } } print ''; @@ -1412,16 +1412,16 @@ else print ''; if ($action == 'date_when' || $object->frequency > 0) { - print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); + print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); } else { - print $langs->trans("NextDateToExecution"); + print $langs->trans("NextDateToExecution"); } print ''; if ($action == 'date_when' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); + print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); } print ''; print ''; @@ -1430,20 +1430,20 @@ else print ''; if ($action == 'nb_gen_max' || $object->frequency > 0) { - print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); + print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); } else { - print $langs->trans("MaxPeriodNumber"); + print $langs->trans("MaxPeriodNumber"); } print ''; if ($action == 'nb_gen_max' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer); + print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer); } else { - print ''; + print ''; } print ''; print ''; @@ -1451,51 +1451,51 @@ else // Status of generated invoices print ''; if ($action == 'auto_validate' || $object->frequency > 0) - print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); + print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); else - print $langs->trans("StatusOfGeneratedInvoices"); + print $langs->trans("StatusOfGeneratedInvoices"); print ''; - $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); + $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); if ($action == 'auto_validate' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); + print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); } print ''; print ''; print ''; - // Frequencry/Recurring section - if ($object->frequency > 0) - { - print '
'; + // Frequencry/Recurring section + if ($object->frequency > 0) + { + print '
'; - if (empty($conf->cron->enabled)) - { - print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); - } + if (empty($conf->cron->enabled)) + { + print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); + } - print '
'; - print ''; + print '
'; + print '
'; - // Nb of generation already done - print ''; - print ''; - print ''; + // Nb of generation already done + print ''; + print ''; + print ''; - // Date last - print ''; - print ''; + // Date last + print ''; + print ''; - print '
'.$langs->trans("NbOfGenerationDone").''; - print $object->nb_gen_done?$object->nb_gen_done:'0'; - print '
'.$langs->trans("NbOfGenerationDone").''; + print $object->nb_gen_done?$object->nb_gen_done:'0'; + print '
'; - print $langs->trans("DateLastGeneration"); - print ''; - print dol_print_date($object->date_last_gen, 'dayhour'); - print '
'; + print $langs->trans("DateLastGeneration"); + print ''; + print dol_print_date($object->date_last_gen, 'dayhour'); + print '
'; + print ''; - print '
'; + print '
'; } print '
'; @@ -1514,7 +1514,7 @@ else '; if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } print '
'; @@ -1522,22 +1522,22 @@ else // Show object lines if (! empty($object->lines)) { - //$disableedit=1; - //$disablemove=1; - $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + //$disableedit=1; + //$disablemove=1; + $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } // Form to add new line if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') { - if ($action != 'editline') - { - // Add free products/services - $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice + if ($action != 'editline') + { + // Add free products/services + $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice - $parameters = array(); - $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - } + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + } } print "\n"; @@ -1570,13 +1570,13 @@ else else { print ''; - } - } + } + } } else { print ''; - } + } //} //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer) @@ -1594,12 +1594,12 @@ else // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); + $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; } } diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 9241726aaec..c0bf0233f89 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -1247,7 +1247,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->creer; print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 3d2daf5a53d..d85255fbf4e 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -84,7 +84,7 @@ dol_mkdir($dir); $stats = new FactureStats($db, $socid, $mode, ($userid>0?$userid:0)); if ($mode == 'customer') { - if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND f.fk_statut IN ('.$db->escape($object_status).')'; + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->escape($object_status).')'; } if ($mode == 'supplier') { @@ -227,12 +227,13 @@ complete_head_from_modules($conf,$langs,null,$head,$h,$type); dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1); -$tmp_companies = $form->select_thirdparty_list($socid,'socid',$filter,1, 0, 0, array(), '', 1); +// We use select_thirdparty_list instead of select_company so we can use $filter and share same code for customer and supplier. +$tmp_companies = $form->select_thirdparty_list($socid, 'socid', $filter, 1, 0, 0, array(), '', 1); //Array passed as an argument to Form::selectarray to build a proper select input $companies = array(); foreach ($tmp_companies as $value) { - $companies[$value['value']] = $value['label']; + $companies[$value['key']] = $value['label']; } print '
'; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index 398f70ad36a..e966eba4a47 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -169,6 +169,20 @@ if ($action == 'create') $charge->paiementtype=$charge->mode_reglement_id?$charge->mode_reglement_id:$charge->paiementtype; $total = $charge->amount; + if (! empty($conf->use_javascript_ajax)) + { + print "\n".''."\n"; + } print load_fiche_titre($langs->trans("DoPayment")); print "
\n"; @@ -188,14 +202,12 @@ if ($action == 'create') print ''; - print ""; - - print ''; + print ''; print '\n"; print '\n"; print '\n"; - print '\n"; - print ''; + /*print '\n"; + print '';*/ $sql = "SELECT sum(p.amount) as total"; $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; @@ -207,12 +219,8 @@ if ($action == 'create') $sumpaid = $obj->total; $db->free(); } - print ''; - print ''; - - print ''; - print "'; - print ''; + /*print ''; + print '';*/ print ''; + print ''; + print ''; + print ''; } print '\n"; diff --git a/htdocs/compta/sociales/document.php b/htdocs/compta/sociales/document.php index ce2f853c935..048d35d73f1 100644 --- a/htdocs/compta/sociales/document.php +++ b/htdocs/compta/sociales/document.php @@ -88,6 +88,7 @@ if ($action == 'setlib' && $user->rights->tax->charges->creer) setEventMessages($object->error, $object->errors, 'errors'); } + /* * View */ @@ -125,7 +126,7 @@ if ($object->id) } else { $morehtmlref.=''; } - } + } $morehtmlref.=''; $linkback = '' . $langs->trans("BackToList") . ''; @@ -153,9 +154,9 @@ if ($object->id) print '
".$langs->trans("SocialContribution")."
'.$langs->trans("Ref").''.$chid.'
'.$langs->trans("Ref").''.$chid.'
'.$langs->trans("Type")."".$charge->type_libelle."
'.$langs->trans("Period")."".dol_print_date($charge->periode,'day')."
'.$langs->trans("Label").''.$charge->lib."
'.$langs->trans("DateDue")."".dol_print_date($charge->date_ech,'day')."
'.$langs->trans("Amount")."".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("DateDue")."".dol_print_date($charge->date_ech,'day')."
'.$langs->trans("Amount")."".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
".$langs->trans("Payment").'
'.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("Date").''; $datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); @@ -294,7 +302,12 @@ if ($action == 'create') if ($sumpaid < $objp->amount) { $namef = "amount_".$objp->id; - print ''; + $nameRemain = "remain_".$objp->id; + if (!empty($conf->use_javascript_ajax)) + print img_picto("Auto fill",'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'"); + $remaintopay=$objp->amount - $sumpaid; + print ''; + print ''; } else { diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 13a2d29aff9..6149a2a92b1 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -654,7 +654,9 @@ if ($id > 0) else { - print '
'.$langs->trans("None").'
'.$langs->trans("None").'
'.$langs->trans("AlreadyPaid")." :".price($totalpaye)."
'; print '
'; - + print '
'; - + dol_fiche_end(); $modulepart = 'tax'; diff --git a/htdocs/compta/sociales/info.php b/htdocs/compta/sociales/info.php index b67c844a7b9..dfa6439a3f4 100644 --- a/htdocs/compta/sociales/info.php +++ b/htdocs/compta/sociales/info.php @@ -42,6 +42,8 @@ $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', $id, 'chargesociales','charges'); +$object = new ChargeSociales($db); + /* * Actions @@ -68,7 +70,6 @@ $title = $langs->trans("SocialContribution") . ' - ' . $langs->trans("Info"); $help_url = 'EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:Módulo Impuestos y cargas sociales (IVA, impuestos)'; llxHeader("",$title,$help_url); -$object = new ChargeSociales($db); $object->fetch($id); $object->info($id); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 8c8a3c2fc11..fd5898879ae 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -109,16 +109,16 @@ if (empty($reshook)) if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) { - $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); + $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) @@ -130,47 +130,47 @@ if (empty($reshook)) } if (! $error) { - $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } } // Si ajout champ produit predefini if (GETPOST('mode')=='predefined') { - $date_start=''; - $date_end=''; - if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) - { - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - } - if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) - { - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - } + $date_start=''; + $date_end=''; + if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) + { + $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + } + if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) + { + $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + } } // Si ajout champ produit libre if (GETPOST('mode')=='libre') { - $date_start_sl=''; - $date_end_sl=''; - if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear')) - { - $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear')); - } - if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear')) - { - $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear')); - } + $date_start_sl=''; + $date_end_sl=''; + if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear')) + { + $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear')); + } + if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear')) + { + $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear')); + } } // Param dates @@ -181,23 +181,23 @@ if (empty($reshook)) $date_end_real_update=''; if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) { - $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); + $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); } if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) { - $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); + $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); } if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) { - $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); + $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); } if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) { - $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); + $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); } if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) { - $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); } // Add contract @@ -228,74 +228,74 @@ if (empty($reshook)) if (! $error) { $object->socid = $socid; - $object->date_contrat = $datecontrat; + $object->date_contrat = $datecontrat; - $object->commercial_suivi_id = GETPOST('commercial_suivi_id','int'); - $object->commercial_signature_id = GETPOST('commercial_signature_id','int'); + $object->commercial_suivi_id = GETPOST('commercial_suivi_id','int'); + $object->commercial_signature_id = GETPOST('commercial_signature_id','int'); - $object->note_private = GETPOST('note_private','alpha'); - $object->note_public = GETPOST('note_public','alpha'); - $object->fk_project = GETPOST('projectid','int'); - $object->remise_percent = GETPOST('remise_percent','alpha'); - $object->ref = GETPOST('ref','alpha'); - $object->ref_customer = GETPOST('ref_customer','alpha'); - $object->ref_supplier = GETPOST('ref_supplier','alpha'); + $object->note_private = GETPOST('note_private','alpha'); + $object->note_public = GETPOST('note_public','alpha'); + $object->fk_project = GETPOST('projectid','int'); + $object->remise_percent = GETPOST('remise_percent','alpha'); + $object->ref = GETPOST('ref','alpha'); + $object->ref_customer = GETPOST('ref_customer','alpha'); + $object->ref_supplier = GETPOST('ref_supplier','alpha'); - // If creation from another object of another module (Example: origin=propal, originid=1) - if (! empty($origin) && ! empty($originid)) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = $origin; - if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - } + // If creation from another object of another module (Example: origin=propal, originid=1) + if (! empty($origin) && ! empty($originid)) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; + if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + } - // For compatibility - if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + // For compatibility + if ($element == 'order') { $element = $subelement = 'commande'; } + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } - $object->origin = $origin; - $object->origin_id = $originid; + $object->origin = $origin; + $object->origin_id = $originid; - // Possibility to add external linked objects with hooks - $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) - { - $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); - } + // Possibility to add external linked objects with hooks + $object->linked_objects[$object->origin] = $object->origin_id; + if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) + { + $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); + } - $id = $object->create($user); - if ($id < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $id = $object->create($user); + if ($id < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - if ($id > 0) - { - dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); + if ($id > 0) + { + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); - $classname = ucfirst($subelement); - $srcobject = new $classname($db); + $classname = ucfirst($subelement); + $srcobject = new $classname($db); - dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); - $result=$srcobject->fetch($object->origin_id); - if ($result > 0) - { - $srcobject->fetch_thirdparty(); + dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); + $result=$srcobject->fetch($object->origin_id); + if ($result > 0) + { + $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject,'fetch_lines')) - { - $srcobject->fetch_lines(); - $lines = $srcobject->lines; - } + if (empty($lines) && method_exists($srcobject,'fetch_lines')) + { + $srcobject->fetch_lines(); + $lines = $srcobject->lines; + } - $fk_parent_line=0; - $num=count($lines); + $fk_parent_line=0; + $num=count($lines); - for ($i=0;$i<$num;$i++) - { - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + for ($i=0;$i<$num;$i++) + { + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { // TODO Exclude also deee // service prĆ©dĆ©fini @@ -330,8 +330,8 @@ if (empty($reshook)) $desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):''; } else { - $desc = dol_htmlentitiesbr($lines[$i]->desc); - } + $desc = dol_htmlentitiesbr($lines[$i]->desc); + } $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx . ' (' . $lines[$i]->vat_src_code . ')' : $lines[$i]->tva_tx; @@ -339,72 +339,72 @@ if (empty($reshook)) $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty); $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty); - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $txtva, - $localtax1_tx, - $localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $lines[$i]->date_start, - $lines[$i]->date_end, - 'HT', - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - array(), - $lines[$i]->fk_unit - ); + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $txtva, + $localtax1_tx, + $localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $lines[$i]->date_start, + $lines[$i]->date_end, + 'HT', + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + array(), + $lines[$i]->fk_unit + ); - if ($result < 0) - { - $error++; - break; - } + if ($result < 0) + { + $error++; + break; + } } - } - } - else - { - setEventMessages($srcobject->error, $srcobject->errors, 'errors'); - $error++; - } + } + } + else + { + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + $error++; + } - // Hooks - $parameters = array('objFrom' => $srcobject); - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook - if ($reshook < 0) - $error++; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - else - { - $result = $object->create($user); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - setEventMessages($object->error, $object->errors, 'errors'); - } - $action='create'; + // Hooks + $parameters = array('objFrom' => $srcobject); + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if ($reshook < 0) + $error++; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } - } + else + { + $result = $object->create($user); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + } + $action='create'; + } + } } else if ($action == 'classin' && $user->rights->contrat->creer) { - $object->setProject(GETPOST('projectid')); + $object->setProject(GETPOST('projectid')); } // Add a new line @@ -429,72 +429,72 @@ if (empty($reshook)) $qty = GETPOST('qty'.$predef); $remise_percent = GETPOST('remise_percent'.$predef); - if ($qty == '') - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); - $error++; - } + if ($qty == '') + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); + $error++; + } - $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); - $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); - if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) - { - setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); - $error++; - } + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $error++; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } - if (! $error) - { + if (! $error) + { // Clean parameters $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT'); - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $tva_tx par celui du produit - // Ecrase $base_price_type par celui du produit - if ($idprod > 0) - { - $prod = new Product($db); - $prod->fetch($idprod); + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $tva_tx par celui du produit + // Ecrase $base_price_type par celui du produit + if ($idprod > 0) + { + $prod = new Product($db); + $prod->fetch($idprod); - // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id); - $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id); - if (empty($tva_tx)) $tva_npr=0; + // Update if prices fields are defined + $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id); + $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id); + if (empty($tva_tx)) $tva_npr=0; - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; - // On defini prix unitaire - if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) - { - $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; - $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + // On defini prix unitaire + if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) + { + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + } + elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; @@ -517,35 +517,35 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - if ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU'); - } - } + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). + if ($tmpvat != $tmpprodvat) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU'); + } + } - $desc=$prod->description; - $desc=dol_concatdesc($desc,$product_desc); - $fk_unit = $prod->fk_unit; - } - else + $desc=$prod->description; + $desc=dol_concatdesc($desc,$product_desc); + $fk_unit = $prod->fk_unit; + } + else { - $pu_ht=GETPOST('price_ht'); - $price_base_type = 'HT'; - $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0; // tva_tx field may be disabled, so we use vat rate 0 - $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0; - $desc=$product_desc; + $pu_ht=GETPOST('price_ht'); + $price_base_type = 'HT'; + $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0; // tva_tx field may be disabled, so we use vat rate 0 + $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0; + $desc=$product_desc; $fk_unit= GETPOST('units', 'alpha'); - } + } - $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr); - $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr); + $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr); + $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr); // ajout prix achat $fk_fournprice = $_POST['fournprice']; @@ -554,41 +554,41 @@ if (empty($reshook)) else $pa_ht = null; - $info_bits=0; - if ($tva_npr) $info_bits |= 0x01; + $info_bits=0; + if ($tva_npr) $info_bits |= 0x01; - if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))) - { - $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency)); - $result = -1 ; - } - else + if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))) { - // Insert line - $result = $object->addline( - $desc, - $pu_ht, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $idprod, - $remise_percent, - $date_start, - $date_end, - $price_base_type, - $pu_ttc, - $info_bits, - $fk_fournprice, - $pa_ht, - $array_options, - $fk_unit - ); - } + $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency)); + $result = -1 ; + } + else + { + // Insert line + $result = $object->addline( + $desc, + $pu_ht, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $idprod, + $remise_percent, + $date_start, + $date_end, + $price_base_type, + $pu_ttc, + $info_bits, + $fk_fournprice, + $pa_ht, + $array_options, + $fk_unit + ); + } - if ($result > 0) - { - // Define output language + if ($result > 0) + { + // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF)) // No generation if default type not defined { $outputlangs = $langs; @@ -624,159 +624,159 @@ if (empty($reshook)) unset($_POST['dp_desc']); unset($_POST['idprod']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha')) { - if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) - { - setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); - $action = 'editline'; - $_GET['rowid'] = GETPOST('elrowid'); - $error++; - } + if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $action = 'editline'; + $_GET['rowid'] = GETPOST('elrowid'); + $error++; + } - if (!$error) { - $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid'))) - { - $db->begin(); + if (!$error) { + $objectline = new ContratLigne($db); + if ($objectline->fetch(GETPOST('elrowid'))) + { + $db->begin(); - if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; + if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; + if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; - $vat_rate = GETPOST('eltva_tx'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + $vat_rate = GETPOST('eltva_tx'); + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); - $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); + $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); - $txtva = $vat_rate; + $txtva = $vat_rate; - // Clean vat code - $vat_src_code=''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code=''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - // ajout prix d'achat - $fk_fournprice = $_POST['fournprice']; - if ( ! empty($_POST['buying_price']) ) - $pa_ht = $_POST['buying_price']; - else - $pa_ht = null; + // ajout prix d'achat + $fk_fournprice = $_POST['fournprice']; + if ( ! empty($_POST['buying_price']) ) + $pa_ht = $_POST['buying_price']; + else + $pa_ht = null; - $fk_unit = GETPOST('unit', 'alpha'); + $fk_unit = GETPOST('unit', 'alpha'); - $objectline->description=GETPOST('product_desc','none'); - $objectline->price_ht=GETPOST('elprice'); - $objectline->subprice=GETPOST('elprice'); - $objectline->qty=GETPOST('elqty'); - $objectline->remise_percent=GETPOST('elremise_percent'); - $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 - $objectline->vat_src_code=$vat_src_code; - $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; - $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; - $objectline->date_ouverture_prevue=$date_start_update; - $objectline->date_ouverture=$date_start_real_update; - $objectline->date_fin_validite=$date_end_update; - $objectline->date_cloture=$date_end_real_update; - $objectline->fk_user_cloture=$user->id; - $objectline->fk_fournprice=$fk_fournprice; - $objectline->pa_ht=$pa_ht; + $objectline->description=GETPOST('product_desc','none'); + $objectline->price_ht=GETPOST('elprice'); + $objectline->subprice=GETPOST('elprice'); + $objectline->qty=GETPOST('elqty'); + $objectline->remise_percent=GETPOST('elremise_percent'); + $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 + $objectline->vat_src_code=$vat_src_code; + $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; + $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; + $objectline->date_ouverture_prevue=$date_start_update; + $objectline->date_ouverture=$date_start_real_update; + $objectline->date_fin_validite=$date_end_update; + $objectline->date_cloture=$date_end_real_update; + $objectline->fk_user_cloture=$user->id; + $objectline->fk_fournprice=$fk_fournprice; + $objectline->pa_ht=$pa_ht; - if ($fk_unit > 0) { - $objectline->fk_unit = GETPOST('unit'); - } else { - $objectline->fk_unit = null; - } + if ($fk_unit > 0) { + $objectline->fk_unit = GETPOST('unit'); + } else { + $objectline->fk_unit = null; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - $objectline->array_options=$array_options; + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + $objectline->array_options=$array_options; - // TODO verifier price_min si fk_product et multiprix + // TODO verifier price_min si fk_product et multiprix - $result=$objectline->update($user); - if ($result > 0) - { - $db->commit(); - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - $db->rollback(); - } - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - } - } + $result=$objectline->update($user); + if ($result > 0) + { + $db->commit(); + } + else + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + $db->rollback(); + } + } + else + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + } + } } else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) { - $result = $object->deleteline(GETPOST('lineid'),$user); + $result = $object->deleteline(GETPOST('lineid'),$user); - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($result >= 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) { - $result = $object->validate($user); + $result = $object->validate($user); } else if ($action == 'reopen' && $user->rights->contrat->creer) { - $result = $object->reopen($user); + $result = $object->reopen($user); } // Close all lines else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->closeAll($user); + $object->closeAll($user); } // Close all lines else if ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->activateAll($user); + $object->activateAll($user); } else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) @@ -848,7 +848,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref_supplier'; @@ -857,10 +857,10 @@ if (empty($reshook)) exit; } } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setref_customer') { @@ -873,8 +873,8 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { + $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref_customer'; } else { @@ -882,58 +882,58 @@ if (empty($reshook)) exit; } } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setref') { - $cancelbutton = GETPOST('cancel','alpha'); + $cancelbutton = GETPOST('cancel','alpha'); - if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$cancelbutton) { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editref'; - } else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); - exit; - } - } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editref'; + } else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + exit; + } + } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setdate_contrat') { - $cancelbutton = GETPOST('cancel','alpha'); + $cancelbutton = GETPOST('cancel','alpha'); - if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$cancelbutton) { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $datacontrat=dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear')); - $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editdate_contrat'; - } else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); - exit; - } - } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editdate_contrat'; + } else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + exit; + } + } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } @@ -1051,74 +1051,74 @@ if ($action == 'create') { print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png'); - $soc = new Societe($db); - if ($socid>0) $soc->fetch($socid); + $soc = new Societe($db); + if ($socid>0) $soc->fetch($socid); - if (GETPOST('origin') && GETPOST('originid')) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = GETPOST('origin'); - if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - } + if (GETPOST('origin') && GETPOST('originid')) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = GETPOST('origin'); + if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + } - if ($element == 'project') - { - $projectid=GETPOST('originid'); - } - else - { - // For compatibility - if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'project') + { + $projectid=GETPOST('originid'); + } + else + { + // For compatibility + if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } - dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); - $classname = ucfirst($subelement); - $objectsrc = new $classname($db); - $objectsrc->fetch(GETPOST('originid')); - if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) $objectsrc->fetch_lines(); - $objectsrc->fetch_thirdparty(); + $classname = ucfirst($subelement); + $objectsrc = new $classname($db); + $objectsrc->fetch(GETPOST('originid')); + if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) $objectsrc->fetch_lines(); + $objectsrc->fetch_thirdparty(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); - $soc = $objectsrc->thirdparty; + $soc = $objectsrc->thirdparty; - $note_private = (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''); - $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : ''); + $note_private = (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''); + $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : ''); - // Object source contacts list - $srccontactslist = $objectsrc->liste_contact(-1,'external',1); - } - } - else { + // Object source contacts list + $srccontactslist = $objectsrc->liste_contact(-1,'external',1); + } + } + else { $projectid = GETPOST('projectid','int'); $note_private = GETPOST("note_private"); $note_public = GETPOST("note_public"); } - $object->date_contrat = dol_now(); + $object->date_contrat = dol_now(); - print '
'; - print ''; + print ''; + print ''; - print ''; - print ''."\n"; - print ''; + print ''; + print ''."\n"; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - // Ref + // Ref print ''; @@ -1130,7 +1130,7 @@ if ($action == 'create') print ''; print ''; - // Thirdparty + // Thirdparty print ''; print ''; if ($socid>0) @@ -1144,7 +1144,7 @@ if ($action == 'create') { print ''; } print ''."\n"; @@ -1163,75 +1163,75 @@ if ($action == 'create') print ''; } - // Commercial suivi - print ''; + // Commercial suivi + print ''; - // Commercial signature - print ''; + // Commercial signature + print ''; - print '"; + print '"; - // Project - if (! empty($conf->projet->enabled)) - { - $formproject=new FormProjets($db); + // Project + if (! empty($conf->projet->enabled)) + { + $formproject=new FormProjets($db); - print '"; - } - - print ''; - - if (empty($user->societe_id)) - { - print ''; - } - - // Other attributes - $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - // Other attributes - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $object->showOptionals($extrafields, 'edit'); - } - - print "
'.$langs->trans('Ref').''; - if (! empty($modCodeContract->code_auto)) { - $tmpcode=$langs->trans("Draft"); - } else { - $tmpcode=''; - } + if (! empty($modCodeContract->code_auto)) { + $tmpcode=$langs->trans("Draft"); + } else { + $tmpcode=''; + } print $tmpcode; print '
'.$langs->trans('RefSupplier').'
'.$langs->trans('ThirdParty').''; print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300'); - print ' '.$langs->trans("AddThirdParty").''; + print ' '.$langs->trans("AddThirdParty").''; print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").''; - print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,''); - print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").''; + print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,''); + print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").''; - print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,''); - print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").''; + print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,''); + print '
'.$langs->trans("Date").''; - $form->select_date($datecontrat,'',0,0,'',"contrat"); - print "
'.$langs->trans("Date").''; + $form->select_date($datecontrat,'',0,0,'',"contrat"); + print "
'.$langs->trans("Project").''; - $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1); - print "
'.$langs->trans("NotePublic").''; - $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
'.$langs->trans("NotePrivate").''; - $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
\n"; - - dol_fiche_end(); - - print '
'; - print ''; - print '     '; - print ''; - print '
'; - - if (is_object($objectsrc)) - { - print ''; - print ''; - - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) - { - print '
'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); - } + print ''.$langs->trans("Project").''; + $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1); + print ""; } - print "
\n"; + print ''.$langs->trans("NotePublic").''; + $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print ''; + + if (empty($user->societe_id)) + { + print ''.$langs->trans("NotePrivate").''; + $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print ''; + } + + // Other attributes + $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + // Other attributes + if (empty($reshook) && ! empty($extrafields->attribute_label)) { + print $object->showOptionals($extrafields, 'edit'); + } + + print "\n"; + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + if (is_object($objectsrc)) + { + print ''; + print ''; + + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) + { + print '
'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); + } + } + + print "\n"; } else /* *************************************************************************** */ @@ -1240,105 +1240,105 @@ else /* */ /* *************************************************************************** */ { - $now=dol_now(); + $now=dol_now(); - if ($object->id > 0) - { - $object->fetch_thirdparty(); + if ($object->id > 0) + { + $object->fetch_thirdparty(); - $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed - if ($result < 0) dol_print_error($db,$object->error); + $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed + if ($result < 0) dol_print_error($db,$object->error); - $nbofservices=count($object->lines); + $nbofservices=count($object->lines); - $author = new User($db); - $author->fetch($object->user_author_id); + $author = new User($db); + $author->fetch($object->user_author_id); - $commercial_signature = new User($db); - $commercial_signature->fetch($object->commercial_signature_id); + $commercial_signature = new User($db); + $commercial_signature->fetch($object->commercial_signature_id); - $commercial_suivi = new User($db); - $commercial_suivi->fetch($object->commercial_suivi_id); + $commercial_suivi = new User($db); + $commercial_suivi->fetch($object->commercial_suivi_id); - $head = contract_prepare_head($object); + $head = contract_prepare_head($object); - $hselected = 0; + $hselected = 0; - dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract'); + dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract'); - /* + /* * Confirmation de la suppression du contrat */ - if ($action == 'delete') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1); + if ($action == 'delete') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1); - } + } - /* + /* * Confirmation de la validation */ - if ($action == 'valid') - { - $ref = substr($object->ref, 1, 4); - if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) - { - $numref = $object->getNextNumRef($object->thirdparty); - } - else - { - $numref = $object->ref; - } + if ($action == 'valid') + { + $ref = substr($object->ref, 1, 4); + if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) + { + $numref = $object->getNextNumRef($object->thirdparty); + } + else + { + $numref = $object->ref; + } - $text=$langs->trans('ConfirmValidateContract',$numref); + $text=$langs->trans('ConfirmValidateContract',$numref); - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1); + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1); - } + } - /* + /* * Confirmation de la fermeture */ - if ($action == 'close') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1); + if ($action == 'close') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1); - } - if ($action == 'activate') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ActivateAllOnContract"),$langs->trans("ConfirmActivateAllOnContract"),"confirm_activate",'',0,1); + } + if ($action == 'activate') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ActivateAllOnContract"),$langs->trans("ConfirmActivateAllOnContract"),"confirm_activate",'',0,1); - } + } - /* + /* * Contrat */ - if (! empty($object->brouillon) && $user->rights->contrat->creer) - { - print '
'; - print ''; - print ''; - } + if (! empty($object->brouillon) && $user->rights->contrat->creer) + { + print ''; + print ''; + print ''; + } - // Clone confirmation - if ($action == 'clone') { - $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); - print $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); - } + // Clone confirmation + if ($action == 'clone') { + $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); + print $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref=''; - if (! empty($modCodeContract->code_auto)) { - $morehtmlref.=$object->ref; - } else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2); - } + $morehtmlref=''; + if (! empty($modCodeContract->code_auto)) { + $morehtmlref.=$object->ref; + } else { + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2); + } $morehtmlref.='
'; // Ref customer @@ -1349,64 +1349,64 @@ else $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->contrat->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $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->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
'; + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->contrat->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $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->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
'; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref); - print '
'; - print '
'; + print '
'; + print '
'; - print ''; + print '
'; - // Ligne info remises tiers - print ''; + // Ligne info remises tiers + print ''; - // Date - print ''; + // Date + print ''; print ''; print ''; - // Other attributes - $cols = 3; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print "
'.$langs->trans('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - $absolute_discount=$object->thirdparty->getAvailableDiscounts(); - print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; - print '
'.$langs->trans('Discount').''; + if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); + else print $langs->trans("CompanyHasNoRelativeDiscount"); + $absolute_discount=$object->thirdparty->getAvailableDiscounts(); + print '. '; + if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency)); + else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print '.'; + print '
'; print $form->editfieldkey("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer); print ''; @@ -1414,577 +1414,577 @@ else print '
"; + print ""; - print '
'; + print '
'; - if (! empty($object->brouillon) && $user->rights->contrat->creer) - { - print ''; - } + if (! empty($object->brouillon) && $user->rights->contrat->creer) + { + print ''; + } - echo '
'; + echo '
'; - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { - $blocname = 'contacts'; - $title = $langs->trans('ContactsAddresses'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) + { + $blocname = 'contacts'; + $title = $langs->trans('ContactsAddresses'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - $colorb='666666'; + $colorb='666666'; - $arrayothercontracts=$object->getListOfContracts('others'); + $arrayothercontracts=$object->getListOfContracts('others'); - /* + /* * Lines of contracts */ $productstatic=new Product($db); - $usemargins=0; + $usemargins=0; if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1; - $var=false; + $var=false; // Title line for service - $cursorline=1; - while ($cursorline <= $nbofservices) - { - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; + $cursorline=1; + while ($cursorline <= $nbofservices) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - // Area with common detail of line - print ''; + // Area with common detail of line + print '
'; - $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; - $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,"; - $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,"; - $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,"; - $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,"; - $sql.= " cd.fk_unit,"; - $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; - $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id; + $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; + $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,"; + $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,"; + $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,"; + $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,"; + $sql.= " cd.fk_unit,"; + $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; + $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; + $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id; - $result = $db->query($sql); - if ($result) - { - $total = 0; + $result = $db->query($sql); + if ($result) + { + $total = 0; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - print ''; - if ($conf->global->PRODUCT_USE_UNITS) print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + if (!empty($conf->multicurrency->enabled)) { + print ''; + } + print ''; + if ($conf->global->PRODUCT_USE_UNITS) print ''; + print ''; if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; - print ''; - print "\n"; + print ''; + print "\n"; - $objp = $db->fetch_object($result); + $objp = $db->fetch_object($result); - // + // - if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) - { - print ''; - // Label - if ($objp->fk_product > 0) - { - print ''; + // Label + if ($objp->fk_product > 0) + { + print ''; - } - else + print ''; + } + else { - print '\n"; - } - // TVA - print ''; - // Price - print '\n"; - // Price multicurrency - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - // Quantite - print ''; - // Unit - if($conf->global->PRODUCT_USE_UNITS) print ''; - // Remise - if ($objp->remise_percent > 0) - { - print '\n"; - } - else - { - print ''; - } + print '\n"; + } + // TVA + print ''; + // Price + print '\n"; + // Price multicurrency + if (!empty($conf->multicurrency->enabled)) { + print ''; + } + // Quantite + print ''; + // Unit + if($conf->global->PRODUCT_USE_UNITS) print ''; + // Remise + if ($objp->remise_percent > 0) + { + print '\n"; + } + else + { + print ''; + } // Margin if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; - // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) - print ''; + // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) + print ''; - print "\n"; + print "\n"; - // Dates of service planed and real - if ($objp->subprice >= 0) - { - $colspan = 6; + // Dates of service planed and real + if ($objp->subprice >= 0) + { + $colspan = 6; - if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { - $colspan = 8; - } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) { - $colspan = 7; - } + if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { + $colspan = 8; + } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) { + $colspan = 7; + } - print ''; - print ''; + print ''; - print ''; - } + print ''; + print ''; + } - // Display lines extrafields - if (is_array($extralabelslines) && count($extralabelslines)>0) { - print ''; - $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); - print ''; - } - } - // Ligne en mode update - else - { - // Ligne carac - print ""; - print ''; + $line = new ContratLigne($db); + $line->fetch_optionals($objp->rowid,$extralabelslines); + print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); + print ''; + } + } + // Ligne en mode update + else + { + // Ligne carac + print ""; + print ''; - print ''; - print ''; - print ''; - if ($conf->global->PRODUCT_USE_UNITS) - { - print ''; - } - print ''; + print ''; + print ''; + print ''; + print ''; + if ($conf->global->PRODUCT_USE_UNITS) + { + print ''; + } + print ''; if (! empty($usemargins)) { - print ''; } - print ''; + print ''; - $colspan=6; - if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; - if($conf->global->PRODUCT_USE_UNITS) $colspan++; + $colspan=6; + if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; + if($conf->global->PRODUCT_USE_UNITS) $colspan++; - // Ligne dates prevues - print ""; - print ''; + // Ligne dates prevues + print ""; + print ''; - if (is_array($extralabelslines) && count($extralabelslines)>0) { - print ''; - $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); - print ''; - } + if (is_array($extralabelslines) && count($extralabelslines)>0) { + print ''; + $line = new ContratLigne($db); + $line->fetch_optionals($objp->rowid,$extralabelslines); + print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); + print ''; + } - print ''; - } + print ''; + } - $db->free($result); - } - else + $db->free($result); + } + else { - dol_print_error($db); - } + dol_print_error($db); + } - if ($object->statut > 0) - { - print ''; - print ''; - print "\n"; - } + if ($object->statut > 0) + { + print ''; + print ''; + print "\n"; + } - print "
'.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").'
'.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").''.$langs->trans("BuyingPrice").' 
 
'; - $productstatic->id=$objp->fk_product; - $productstatic->type=$objp->ptype; - $productstatic->ref=$objp->pref; + if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) + { + print '
'; + $productstatic->id=$objp->fk_product; + $productstatic->type=$objp->ptype; + $productstatic->ref=$objp->pref; $productstatic->entity=$objp->pentity; $productstatic->label=$objp->plabel; $text = $productstatic->getNomUrl(1,'',20); - if ($objp->plabel) - { - $text .= ' - '; - //$productstatic->ref=$objp->label; - //$text .= $productstatic->getNomUrl(0,'',16); - $text .= $objp->plabel; - } - $description = $objp->description; + if ($objp->plabel) + { + $text .= ' - '; + //$productstatic->ref=$objp->label; + //$text .= $productstatic->getNomUrl(0,'',16); + $text .= $objp->plabel; + } + $description = $objp->description; - // Add description in form + // Add description in form if (! empty($conf->global->PRODUIT_DESC_IN_FORM)) { $text .= (! empty($objp->description) && $objp->description!=$objp->plabel)?'
'.dol_htmlentitiesbr($objp->description):''; $description = ''; // Already added into main visible desc } - echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):'')); + echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):'')); - print '
'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."'; - print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits); - print ''.($objp->subprice != '' ? price($objp->subprice) : '')."'.price($objp->multicurrency_subprice).''.$objp->qty.''.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).''.$objp->remise_percent."% '.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."'; + print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits); + print ''.($objp->subprice != '' ? price($objp->subprice) : '')."'.price($objp->multicurrency_subprice).''.$objp->qty.''.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).''.$objp->remise_percent."% '.price($objp->pa_ht).''; - if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) - { - print ''; - print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); - print ''; - } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { - print ''; - print img_edit(); - print ''; - } - if ( $user->rights->contrat->creer && ($object->statut >= 0)) - { - print ''; - print img_delete(); - print ''; - } - print ''; + if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) + { + print ''; + print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); + print ''; + } + if ($user->rights->contrat->creer && ($object->statut >= 0)) + { + print ''; + print img_edit(); + print ''; + } + if ( $user->rights->contrat->creer && ($object->statut >= 0)) + { + print ''; + print img_delete(); + print ''; + } + print '
'; + print '
'; - // Date planned - print $langs->trans("DateStartPlanned").': '; - if ($objp->date_debut) - { - print dol_print_date($db->jdate($objp->date_debut), 'day'); - // Warning si date prevu passee et pas en service - if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { - $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print " ".img_warning($textlate); - } - } - else print $langs->trans("Unknown"); - print '  -  '; - print $langs->trans("DateEndPlanned").': '; - if ($objp->date_fin) - { - print dol_print_date($db->jdate($objp->date_fin), 'day'); - if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { - $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print " ".img_warning($textlate); - } - } - else print $langs->trans("Unknown"); + // Date planned + print $langs->trans("DateStartPlanned").': '; + if ($objp->date_debut) + { + print dol_print_date($db->jdate($objp->date_debut), 'day'); + // Warning si date prevu passee et pas en service + if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { + $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print " ".img_warning($textlate); + } + } + else print $langs->trans("Unknown"); + print '  -  '; + print $langs->trans("DateEndPlanned").': '; + if ($objp->date_fin) + { + print dol_print_date($db->jdate($objp->date_fin), 'day'); + if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { + $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print " ".img_warning($textlate); + } + } + else print $langs->trans("Unknown"); - print '
'; - if ($objp->fk_product) - { - $productstatic->id=$objp->fk_product; - $productstatic->type=$objp->ptype; - $productstatic->ref=$objp->pref; + // Display lines extrafields + if (is_array($extralabelslines) && count($extralabelslines)>0) { + print '
'; + if ($objp->fk_product) + { + $productstatic->id=$objp->fk_product; + $productstatic->type=$objp->ptype; + $productstatic->ref=$objp->pref; $productstatic->entity=$objp->pentity; - print $productstatic->getNomUrl(1,'',20); - print $objp->label?' - '.dol_trunc($objp->label,16):''; - print '
'; - } - else - { - print $objp->label?$objp->label.'
':''; - } + print $productstatic->getNomUrl(1,'',20); + print $objp->label?' - '.dol_trunc($objp->label,16):''; + print '
'; + } + else + { + print $objp->label?$objp->label.'
':''; + } - // editeur wysiwyg - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $nbrows=ROWS_2; - if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; - $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0); - $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%'); - $doleditor->Create(); + // editeur wysiwyg + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $nbrows=ROWS_2; + if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; + $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0); + $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%'); + $doleditor->Create(); - print '
'; - print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1); - print ''; - print $form->selectUnits($objp->fk_unit, "unit"); - print '%'; + print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1); + print ''; + print $form->selectUnits($objp->fk_unit, "unit"); + print '%'; - if ($objp->fk_product) print ''; + print ''; + if ($objp->fk_product) print ''; print ''; - print ''; - print '
'; - print '
'; + print ''; + print '
'; + print '
'; - print $langs->trans("DateStartPlanned").' '; - $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); - print '   '.$langs->trans("DateEndPlanned").' '; - $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update"); - print '
'; + print $langs->trans("DateStartPlanned").' '; + $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); + print '   '.$langs->trans("DateEndPlanned").' '; + $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update"); + print '


"; + print ""; - print "
\n"; + print "\n"; - /* + /* * Confirmation to delete service line of contract */ - if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1); - if ($ret == 'html') print '
'; - } + if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1); + if ($ret == 'html') print '
'; + } - /* + /* * Confirmation to move service toward another contract */ - if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) - { - $arraycontractid=array(); - foreach($arrayothercontracts as $contractcursor) - { - $arraycontractid[$contractcursor->id]=$contractcursor->ref; - } - //var_dump($arraycontractid); - // Cree un tableau formulaire - $formquestion=array( + if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) + { + $arraycontractid=array(); + foreach($arrayothercontracts as $contractcursor) + { + $arraycontractid[$contractcursor->id]=$contractcursor->ref; + } + //var_dump($arraycontractid); + // Cree un tableau formulaire + $formquestion=array( 'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"), - array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid)); + array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid)); - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion); - print '
'; - } + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion); + print '
'; + } - /* + /* * Confirmation de la validation activation */ - if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - $comment = GETPOST('comment','alpha'); - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1); - print '
'; - } + if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + $comment = GETPOST('comment','alpha'); + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1); + print '
'; + } - /* + /* * Confirmation de la validation fermeture */ - if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - $comment = GETPOST('comment','alpha'); + if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + $comment = GETPOST('comment','alpha'); - if (empty($dateactend)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); - } - else - { - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1); - } - print '
'; - } + if (empty($dateactend)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); + } + else + { + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1); + } + print '
'; + } - // Area with status and activation info of line - if ($object->statut > 0) - { - print ''; + // Area with status and activation info of line + if ($object->statut > 0) + { + print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; - print "\n"; + } + } + print ''; + print "\n"; - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print ''; - print '
'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; - if ($user->societe_id == 0) - { - if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') - { - $tmpaction='activateline'; - $tmpactionpicto='play'; - $tmpactiontext=$langs->trans("Activate"); - if ($objp->statut == 4) - { - $tmpaction='unactivateline'; - $tmpactionpicto='playstop'; - $tmpactiontext=$langs->trans("Unactivate"); - } + print '
'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; + if ($user->societe_id == 0) + { + if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') + { + $tmpaction='activateline'; + $tmpactionpicto='play'; + $tmpactiontext=$langs->trans("Activate"); + if ($objp->statut == 4) + { + $tmpaction='unactivateline'; + $tmpactionpicto='playstop'; + $tmpactiontext=$langs->trans("Unactivate"); + } if (($tmpaction=='activateline' && $user->rights->contrat->activer) || ($tmpaction=='unactivateline' && $user->rights->contrat->desactiver)) { print ''; print img_picto($tmpactiontext, $tmpactionpicto); print ''; } - } - } - print '
'; - // Si pas encore active - if (! $objp->date_debut_reelle) { - print $langs->trans("DateStartReal").': '; - if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day'); - else print $langs->trans("ContractStatusNotRunning"); - } - // Si active et en cours - if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) { - print $langs->trans("DateStartReal").': '; - print dol_print_date($objp->date_debut_reelle, 'day'); - } - // Si desactive - if ($objp->date_debut_reelle && $objp->date_fin_reelle) { - print $langs->trans("DateStartReal").': '; - print dol_print_date($objp->date_debut_reelle, 'day'); - print '  -  '; - print $langs->trans("DateEndReal").': '; - print dol_print_date($objp->date_fin_reelle, 'day'); - } - if (! empty($objp->comment)) print "
".$objp->comment; - print '
'; + // Si pas encore active + if (! $objp->date_debut_reelle) { + print $langs->trans("DateStartReal").': '; + if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day'); + else print $langs->trans("ContractStatusNotRunning"); + } + // Si active et en cours + if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) { + print $langs->trans("DateStartReal").': '; + print dol_print_date($objp->date_debut_reelle, 'day'); + } + // Si desactive + if ($objp->date_debut_reelle && $objp->date_fin_reelle) { + print $langs->trans("DateStartReal").': '; + print dol_print_date($objp->date_debut_reelle, 'day'); + print '  -  '; + print $langs->trans("DateEndReal").': '; + print dol_print_date($objp->date_fin_reelle, 'day'); + } + if (! empty($objp->comment)) print "
".$objp->comment; + print '
  
'; - } + print ''; + print ''; + } - // Form to activate line - if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - print '
'; - print ''; + // Form to activate line + if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + print ''; + print ''; - print ''; + print '
'; - // Definie date debut et fin par defaut - $dateactstart = $objp->date_debut; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (! $dateactstart) $dateactstart = time(); + // Definie date debut et fin par defaut + $dateactstart = $objp->date_debut; + if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + elseif (! $dateactstart) $dateactstart = time(); - $dateactend = $objp->date_fin; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (! $dateactend) - { - if ($objp->fk_product > 0) - { - $product=new Product($db); - $product->fetch($objp->fk_product); - $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); - } - } + $dateactend = $objp->date_fin; + if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + elseif (! $dateactend) + { + if ($objp->fk_product > 0) + { + $product=new Product($db); + $product->fetch($objp->fk_product); + $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); + } + } - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
'.$langs->trans("DateServiceActivate").''; - print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); - print ''.$langs->trans("DateEndPlanned").''; - print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active",1,0,1); - print ''; - print '
'.$langs->trans("DateServiceActivate").''; + print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); + print ''.$langs->trans("DateEndPlanned").''; + print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active",1,0,1); + print ''; + print '
'.$langs->trans("Comment").''; - print '   '; - print ''; - print '
'.$langs->trans("Comment").''; + print '   '; + print ''; + print '
'; + print ''; - print '
'; - } + print ''; + } - if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - /** - * Disable a contract line - */ - print ''."\n"; - print '
'; + if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + /** + * Disable a contract line + */ + print ''."\n"; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + print '
'; - // Definie date debut et fin par defaut - $dateactstart = $objp->date_debut_reelle; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (! $dateactstart) $dateactstart = time(); + // Definie date debut et fin par defaut + $dateactstart = $objp->date_debut_reelle; + if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + elseif (! $dateactstart) $dateactstart = time(); - $dateactend = $objp->date_fin_reelle; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (! $dateactend) - { - if ($objp->fk_product > 0) - { - $product=new Product($db); - $product->fetch($objp->fk_product); - $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); - } - } - $now=dol_now(); - if ($dateactend > $now) $dateactend=$now; + $dateactend = $objp->date_fin_reelle; + if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + elseif (! $dateactend) + { + if ($objp->fk_product > 0) + { + $product=new Product($db); + $product->fetch($objp->fk_product); + $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); + } + } + $now=dol_now(); + if ($dateactend > $now) $dateactend=$now; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
'; - if ($objp->statut >= 4) - { - if ($objp->statut == 4) - { - print $langs->trans("DateEndReal").' '; - print $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1,1); - } - } - print ''; - print '
'; + if ($objp->statut >= 4) + { + if ($objp->statut == 4) + { + print $langs->trans("DateEndReal").' '; + print $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1,1); + } + } + print ''; + print '
'.$langs->trans("Comment").''; - print '   '; - print ''; - print '
'.$langs->trans("Comment").''; + print '   '; + print ''; + print '
'; + print ''; - print '
'; - } + print ''; + } - $cursorline++; - } + $cursorline++; + } // Form to add new line - if ($user->rights->contrat->creer && ($object->statut == 0)) - { - $dateSelector=1; + if ($user->rights->contrat->creer && ($object->statut == 0)) + { + $dateSelector=1; print "\n"; print '
@@ -1994,15 +1994,15 @@ else '; - print '
'; + print '
'; print ''; // Array with (n*2)+1 lines - // Trick to not show product entries - $savproductenabled=$conf->product->enabled; - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0; + // Trick to not show product entries + $savproductenabled=$conf->product->enabled; + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0; - // Form to add new line - if ($action != 'editline') + // Form to add new line + if ($action != 'editline') { $var = true; @@ -2015,129 +2015,129 @@ else $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - // Restore correct setup - $conf->product->enabled = $savproductenabled; + // Restore correct setup + $conf->product->enabled = $savproductenabled; - print '
'; - print '
'; - print ''; - } + print ''; + print '
'; + print ''; + } dol_fiche_end(); - /* + /* * Buttons */ - if ($user->societe_id == 0) - { - print '
'; + if ($user->societe_id == 0) + { + print '
'; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - // Send - if ($object->statut == 1) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { - print ''; - } else - print ''; - } + if (empty($reshook)) + { + // Send + if ($object->statut == 1) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { + print ''; + } else + print ''; + } - if ($object->statut == 0 && $nbofservices) - { - if ($user->rights->contrat->creer) print ''; - else print ''; - } - if ($object->statut == 1) - { - if ($user->rights->contrat->creer) print ''; - else print ''; - } + if ($object->statut == 0 && $nbofservices) + { + if ($user->rights->contrat->creer) print ''; + else print ''; + } + if ($object->statut == 1) + { + if ($user->rights->contrat->creer) print ''; + else print ''; + } - if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { - $langs->load("bills"); - if ($user->rights->facture->creer) print ''; - else print ''; - } + if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + { + $langs->load("bills"); + if ($user->rights->facture->creer) print ''; + else print ''; + } - if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { - $langs->load("orders"); - if ($user->rights->commande->creer) print ''; - else print ''; - } + if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + { + $langs->load("orders"); + if ($user->rights->commande->creer) print ''; + else print ''; + } - // Clone - if ($user->rights->contrat->creer) { - print ''; - } + // Clone + if ($user->rights->contrat->creer) { + print ''; + } - if ($object->nbofservicesclosed > 0) - { - print ''; - } - if ($object->nbofservicesclosed < $nbofservices) - { - //if (! $numactive) - //{ - print ''; - //} - //else - //{ - // print ''; - //} - } + if ($object->nbofservicesclosed > 0) + { + print ''; + } + if ($object->nbofservicesclosed < $nbofservices) + { + //if (! $numactive) + //{ + print ''; + //} + //else + //{ + // print ''; + //} + } - // On peut supprimer entite si - // - Droit de creer + mode brouillon (erreur creation) - // - Droit de supprimer - if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer) - { - print ''; - } - else - { - print ''; - } - } + // On peut supprimer entite si + // - Droit de creer + mode brouillon (erreur creation) + // - Droit de supprimer + if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer) + { + print ''; + } + else + { + print ''; + } + } - print "
"; - } + print "
"; + } - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } - if ($action != 'presend') - { - print '
'; + if ($action != 'presend') + { + print '
'; - /* + /* * Documents generes */ - $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->contrat->creer; - $delallowed = $user->rights->contrat->supprimer; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->contrat->lire; + $delallowed = $user->rights->contrat->creer; - $var = true; + $var = true; - print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; @@ -2145,8 +2145,8 @@ else $somethingshown = $formactions->showactions($object, 'contract', $socid, 1); - print '
'; - } + print '
'; + } // Presend form $modelmail='contract'; @@ -2155,7 +2155,7 @@ else $trackid = 'con'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - } + } } diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php new file mode 100644 index 00000000000..69f1d541988 --- /dev/null +++ b/htdocs/contrat/class/api_contracts.class.php @@ -0,0 +1,532 @@ + + * Copyright (C) 2016 Laurent Destailleur + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + use Luracast\Restler\RestException; + + require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + +/** + * API class for contracts + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Contracts extends DolibarrApi +{ + + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + 'date_contrat', + 'commercial_signature_id', + 'commercial_suivi_id' + ); + + /** + * @var Contract $contract {@type Contrat} + */ + public $contract; + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + $this->contract = new Contrat($this->db); + } + + /** + * Get properties of a contrat object + * + * Return an array with contrat informations + * + * @param int $id ID of contract + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->contrat->lire) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->contract->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->contract); + } + + + + /** + * List contracts + * + * Get a list of contracts + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter contracts of. {@example '1' or '1,2,3'} {@pattern /^[0-9,]*$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of contract objects + * + * @throws RestException + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $thirdparty_ids; + + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql.= " FROM ".MAIN_DB_PREFIX."contrat as t"; + + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + + $sql.= ' WHERE t.entity IN ('.getEntity('contrat').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + + dol_syslog("API Rest request"); + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $db->fetch_object($result); + $contrat_static = new Contrat($db); + if($contrat_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($contrat_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve contrat list : '.$db->lasterror()); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No contract found'); + } + return $obj_ret; + } + + /** + * Create contract object + * + * @param array $request_data Request data + * @return int ID of contrat + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach($request_data as $field => $value) { + $this->contract->$field = $value; + } + /*if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->contract->lines = $lines; + }*/ + if ($this->contract->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors)); + } + + return $this->contract->id; + } + + /** + * Get lines of a contract + * + * @param int $id Id of contract + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->contrat->lire) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->contract->getLinesArray(); + $result = array(); + foreach ($this->contract->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Add a line to given contract + * + * @param int $id Id of contrat to update + * @param array $request_data Contractline data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->contract->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->date_start, // date ouverture = date_start_real + $request_data->date_end, // date_cloture = date_end_real + $request_data->HT, + $request_data->subprice_excl_tax, + $request_data->info_bits, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->array_options, + $request_data->fk_unit, + $request_data->rang + ); + + if ($updateRes > 0) { + return $updateRes; + + } + return false; + } + + /** + * Update a line to given contract + * + * @param int $id Id of contrat to update + * @param int $lineid Id of line to update + * @param array $request_data Contractline data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + + $updateRes = $this->contract->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_ouveture_prevue, + $request_data->date_fin_validite, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->date_ouverture, + $request_data->date_cloture, + 'HT', + $request_data->info_bits, + $request_data->fk_fourn_price, + $request_data->pa_ht, + $request_data->array_options, + $request_data->fk_unit + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + + return false; + } + + /** + * Delete a line to given contract + * + * + * @param int $id Id of contract to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + * @throws 401 + * @throws 404 + */ + function deleteLine($id, $lineid) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + $updateRes = $this->contract->deleteline($lineid, DolibarrApiAccess::$user); + if ($updateRes > 0) { + return $this->get($id); + } + return false; + } + + /** + * Update contract general fields (won't touch lines of contract) + * + * @param int $id Id of contrat to update + * @param array $request_data Datas + * + * @return int + */ + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach($request_data as $field => $value) { + if ($field == 'id') continue; + $this->contract->$field = $value; + } + + if($this->contract->update(DolibarrApiAccess::$user, 0)) + return $this->get($id); + + return false; + } + + /** + * Delete contract + * + * @param int $id Contract ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->contrat->supprimer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if( ! $this->contract->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete contract : '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract deleted' + ) + ); + + } + + /** + * Validate an contract + * + * @param int $id Contract ID + * @param int $idwarehouse Warehouse ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "idwarehouse": 0, + * "notrigger": 0 + * } + */ + /* + function validate($id, $idwarehouse=0, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->contract->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Contract: '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract validated (Ref='.$this->contract->ref.')' + ) + ); + } + */ + + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + function _cleanObjectDatas($object) { + + $object = parent::_cleanObjectDatas($object); + + unset($object->address); + + return $object; + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $contrat = array(); + foreach (Contracts::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $contrat[$field] = $data[$field]; + + } + return $contrat; + } +} diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 071ae75e5b7..5ff8dd182bb 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -691,8 +691,8 @@ class Contrat extends CommonObject $sql.= " d.fk_user_ouverture,"; $sql.= " d.fk_user_cloture,"; $sql.= " d.fk_unit"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d, ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE d.fk_contrat = ".$this->id ." AND d.fk_product = p.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; + $sql.= " WHERE d.fk_contrat = ".$this->id; $sql.= " ORDER by d.rowid ASC"; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); @@ -728,7 +728,7 @@ class Contrat extends CommonObject $line->total_localtax1 = $objp->total_localtax1; $line->total_localtax2 = $objp->total_localtax2; $line->total_ttc = $objp->total_ttc; - $line->fk_product = $objp->fk_product; + $line->fk_product = (($objp->fk_product > 0)?$objp->fk_product:0); $line->info_bits = $objp->info_bits; $line->fk_fournprice = $objp->fk_fournprice; @@ -740,9 +740,17 @@ class Contrat extends CommonObject $line->fk_user_cloture = $objp->fk_user_cloture; $line->fk_unit = $objp->fk_unit; - $line->ref = $objp->product_ref; // deprecated - $line->label = $objp->product_label; // deprecated - $line->libelle = $objp->product_label; // deprecated + $line->ref = $objp->product_ref; // deprecated + if (empty($objp->fk_product)) + { + $line->label = ''; // deprecated + $line->libelle = $objp->description; // deprecated + } + else + { + $line->label = $objp->product_label; // deprecated + $line->libelle = $objp->product_label; // deprecated + } $line->product_ref = $objp->product_ref; // Ref product $line->product_desc = $objp->product_desc; // Description product $line->product_label = $objp->product_label; // Label product @@ -759,7 +767,7 @@ class Contrat extends CommonObject $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite); $line->date_fin_reel = $this->db->jdate($objp->date_cloture); - // Retreive all extrafield for propal + // Retreive all extrafield for contract // fetch optionals attributes and labels $line->fetch_optionals($line->id,$extralabelsline); @@ -789,108 +797,6 @@ class Contrat extends CommonObject return -3; } - // Selectionne les lignes contrat liees a aucun produit - $sql = "SELECT d.rowid, d.fk_contrat, d.statut, d.qty, d.description, d.price_ht, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.rowid, d.remise_percent, d.subprice,"; - $sql.= " d.total_ht,"; - $sql.= " d.total_tva,"; - $sql.= " d.total_localtax1,"; - $sql.= " d.total_localtax2,"; - $sql.= " d.total_ttc,"; - $sql.= " d.info_bits, d.fk_product,"; - $sql.= " d.date_ouverture_prevue, d.date_ouverture,"; - $sql.= " d.date_fin_validite, d.date_cloture,"; - $sql.= " d.fk_user_author,"; - $sql.= " d.fk_user_ouverture,"; - $sql.= " d.fk_user_cloture,"; - $sql.= " d.fk_unit"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d"; - $sql.= " WHERE d.fk_contrat = ".$this->id; - $sql.= " AND (d.fk_product IS NULL OR d.fk_product = 0)"; // fk_product = 0 gardee pour compatibilitee - - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - - while ($i < $num) - { - $objp = $this->db->fetch_object($result); - - $line = new ContratLigne($this->db); - $line->id = $objp->rowid; - $line->fk_contrat = $objp->fk_contrat; - $line->libelle = $objp->description; - $line->desc = $objp->description; - $line->qty = $objp->qty; - $line->statut = $objp->statut; - $line->ref = ''; - $line->tva_tx = $objp->tva_tx; - $line->localtax1_tx = $objp->localtax1_tx; - $line->localtax2_tx = $objp->localtax2_tx; - $line->localtax1_type = $objp->localtax1_type; - $line->localtax2_type = $objp->localtax2_type; - $line->subprice = $objp->subprice; - $line->remise_percent = $objp->remise_percent; - $line->price_ht = $objp->price_ht; - $line->price = (isset($objp->price)?$objp->price:null); // For backward compatibility - $line->total_ht = $objp->total_ht; - $line->total_tva = $objp->total_tva; - $line->total_localtax1= $objp->total_localtax1; - $line->total_localtax2= $objp->total_localtax2; - $line->total_ttc = $objp->total_ttc; - $line->fk_product = 0; - $line->info_bits = $objp->info_bits; - - $line->fk_user_author = $objp->fk_user_author; - $line->fk_user_ouverture= $objp->fk_user_ouverture; - $line->fk_user_cloture = $objp->fk_user_cloture; - - $line->description = $objp->description; - - $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue); - $line->date_ouverture = $this->db->jdate($objp->date_ouverture); - $line->date_fin_validite = $this->db->jdate($objp->date_fin_validite); - $line->date_cloture = $this->db->jdate($objp->date_cloture); - // For backward compatibility - $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue); - $line->date_debut_reel = $this->db->jdate($objp->date_ouverture); - $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite); - $line->date_fin_reel = $this->db->jdate($objp->date_cloture); - $line->fk_unit = $objp->fk_unit; - - if ($line->statut == 0) $this->nbofserviceswait++; - if ($line->statut == 4 && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; - if ($line->statut == 4 && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; - if ($line->statut == 5) $this->nbofservicesclosed++; - - - // Retreive all extrafield for propal - // fetch optionals attributes and labels - - $line->fetch_optionals($line->id,$extralabelsline); - - - $this->lines[$pos] = $line; - $this->lines_id_index_mapper[$line->id] = $pos; - - $total_ttc+=$objp->total_ttc; - $total_vat+=$objp->total_tva; - $total_ht+=$objp->total_ht; - - $i++; - $pos++; - } - - $this->db->free($result); - } - else - { - dol_syslog(get_class($this)."::Fetch Erreur lecture des lignes de contrat non liees aux produits"); - $this->error=$this->db->error(); - return -2; - } - $this->nbofservices=count($this->lines); $this->total_ttc = price2num($total_ttc); // TODO For the moment value is false as value is not stored in database for line linked to products $this->total_vat = price2num($total_vat); // TODO For the moment value is false as value is not stored in database for line linked to products @@ -1008,7 +914,12 @@ class Contrat extends CommonObject if (! $error) { - // Add object linked + if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects + { + $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds + } + + // Add object linked if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) { foreach($this->linked_objects as $origin => $tmp_origin_id) @@ -1020,7 +931,7 @@ class Contrat extends CommonObject $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -1031,7 +942,7 @@ class Contrat extends CommonObject $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -1400,13 +1311,14 @@ class Contrat extends CommonObject * @param int $pa_ht Buying price HT * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @return int <0 si erreur, >0 si ok + * @param string $rang Position + * @return int <0 if KO, >0 if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0) { global $user, $langs, $conf, $mysoc; - dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits"); + dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); if ($this->statut >= 0) { @@ -1616,7 +1528,7 @@ class Contrat extends CommonObject { global $user, $conf, $langs, $mysoc; - // Nettoyage parametres + // Clean parameters $qty=trim($qty); $desc=trim($desc); $desc=trim($desc); @@ -1625,6 +1537,7 @@ class Contrat extends CommonObject $localtax1tx = price2num($localtax1tx); $localtax2tx = price2num($localtax2tx); $pa_ht=price2num($pa_ht); + if (empty($fk_fournprice)) $fk_fournprice=0; $subprice = $price; $remise = 0; @@ -1701,7 +1614,7 @@ class Contrat extends CommonObject $sql.= ", total_localtax1='".price2num($total_localtax1)."'"; $sql.= ", total_localtax2='".price2num($total_localtax2)."'"; $sql.= ", total_ttc='". price2num($total_ttc)."'"; - $sql.= ", fk_product_fournisseur_price='".$fk_fournprice."'"; + $sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null"); $sql.= ", buy_price_ht='".price2num($pa_ht)."'"; if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; } else { $sql.=",date_ouverture_prevue=null"; } @@ -1772,7 +1685,7 @@ class Contrat extends CommonObject * @param User $user User that delete * @return int >0 if OK, <0 if KO */ - function deleteline($idline,$user) + function deleteline($idline, User $user) { global $conf, $langs; @@ -2343,7 +2256,17 @@ class Contrat extends CommonObject } } - /** + /** + * Create an array of order lines + * + * @return int >0 if OK, <0 if KO + */ + function getLinesArray() + { + return $this->fetch_lines(); + } + + /** * Create a document onto disk according to template module. * * @param string $modele Force model to use ('' to not force) @@ -3033,7 +2956,7 @@ class ContratLigne extends CommonObjectLine $sql.= " info_bits,"; $sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; if ($this->date_ouverture_prevue > 0) { $sql.= ",date_ouverture_prevue"; } - if ($this->date_fin_validite > 0) { $sql.= ",date_fin_validite"; } + if ($this->date_fin_validite > 0) { $sql.= ",date_fin_validite"; } $sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',"; $sql.= ($this->fk_product>0 ? $this->fk_product : "null").","; $sql.= " '".$this->db->escape($this->qty)."',"; @@ -3051,8 +2974,8 @@ class ContratLigne extends CommonObjectLine else $sql.= ' null,'; if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht); else $sql.= ' null'; - if ($this->date_ouverture_prevue > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture_prevue)."'"; } - if ($this->date_fin_validite > 0) { $sql.= ",'".$this->db->idate($this->date_fin_validite)."'"; } + if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; } + if ($this->date_cloture > 0) { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; } $sql.= ")"; dol_syslog(get_class($this)."::insert", LOG_DEBUG); diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index bd86c5cb80c..dd996f83f57 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -91,11 +91,13 @@ if ($action == 'builddoc' && $permissioncreate) } else { - if (empty($donotredirect)) // This is se when include is done by bulk action "Bill Orders" + if (empty($donotredirect)) // This is use when include is done by bulk action "Bill Orders" { setEventMessages($langs->trans("FileGenerated"), null); - header('Location: '.$_SERVER['REQUEST_URI'].'#builddoc'); + $redirecturl = $_SERVER['REQUEST_URI']; + $redirecturl = preg_replace('/&?action=builddoc/', '', $redirecturl); // Remove action=builddoc parameter to avoid infinite loop + header('Location: '.$redirecturl.'#builddoc'); exit; } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 4aec6179365..0e9d405d44c 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -322,14 +322,14 @@ if (! $error && $massaction == 'confirm_presend') $replyto = $from; $subject = GETPOST('subject','none'); $message = GETPOST('message','none'); - $sendtocc = GETPOST('sentocc'); - $sendtobcc = ''; - if ($objectclass == 'Propale') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO); - if ($objectclass == 'Commande') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO); - if ($objectclass == 'Facture') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); - if ($objectclass == 'Supplier_Proposal') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO); - if ($objectclass == 'CommandeFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO); - if ($objectclass == 'FactureFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO); + + $sendtobcc = GETPOST('sendtoccc'); + if ($objectclass == 'Propale') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); + if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); + if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); + if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); + if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); + if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); diff --git a/htdocs/core/ajax/ajaxdirtree.php b/htdocs/core/ajax/ajaxdirtree.php index c376bee9da3..ea4bf830e21 100644 --- a/htdocs/core/ajax/ajaxdirtree.php +++ b/htdocs/core/ajax/ajaxdirtree.php @@ -211,15 +211,26 @@ if (file_exists($fullpathselecteddir)) } // Enable jquery handlers on new generated HTML objects - print ''; + }); + }); + '; echo "\n"; diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index f04e2e95b18..0861ef160b6 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -49,35 +49,35 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; //global $hookmanager; $hookmanager->initHooks(array('searchform')); -$search_boxvalue=GETPOST('q'); +$search_boxvalue=GETPOST('q', 'none'); $arrayresult=array(); // Define $searchform if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && empty($conf->global->MAIN_SEARCHFORM_SOCIETE_DISABLED) && $user->rights->societe->lire) { - $arrayresult['searchintothirdparty']=array('position'=>10, 'img'=>'object_company', 'label'=>$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintothirdparty']=array('position'=>10, 'shortcut'=>'T', 'img'=>'object_company', 'label'=>$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->societe->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTACT_DISABLED) && $user->rights->societe->lire) { - $arrayresult['searchintocontact']=array('position'=>15, 'img'=>'object_contact', 'label'=>$langs->trans("SearchIntoContacts", $search_boxvalue), 'text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontact']=array('position'=>15, 'shortcut'=>'A', 'img'=>'object_contact', 'label'=>$langs->trans("SearchIntoContacts", $search_boxvalue), 'text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->adherent->enabled) && empty($conf->global->MAIN_SEARCHFORM_ADHERENT_DISABLED) && $user->rights->adherent->lire) { - $arrayresult['searchintomember']=array('position'=>20, 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoMembers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintomember']=array('position'=>20, 'shortcut'=>'M', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoMembers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); } if (((! empty($conf->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire)) && empty($conf->global->MAIN_SEARCHFORM_PRODUITSERVICE_DISABLED)) { - $arrayresult['searchintoproduct']=array('position'=>30, 'img'=>'object_product', 'label'=>$langs->trans("SearchIntoProductsOrServices", $search_boxvalue),'text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoproduct']=array('position'=>30, 'shortcut'=>'P', 'img'=>'object_product', 'label'=>$langs->trans("SearchIntoProductsOrServices", $search_boxvalue),'text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->projet->enabled) && empty($conf->global->MAIN_SEARCHFORM_PROJECT_DISABLED) && $user->rights->projet->lire) { - $arrayresult['searchintoprojects']=array('position'=>40, 'img'=>'object_projectpub', 'label'=>$langs->trans("SearchIntoProjects", $search_boxvalue), 'text'=>img_picto('','object_projectpub').' '.$langs->trans("SearchIntoProjects", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintoprojects']=array('position'=>40, 'shortcut'=>'Q', 'img'=>'object_projectpub', 'label'=>$langs->trans("SearchIntoProjects", $search_boxvalue), 'text'=>img_picto('','object_projectpub').' '.$langs->trans("SearchIntoProjects", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->projet->enabled) && empty($conf->global->MAIN_SEARCHFORM_TASK_DISABLED) && $user->rights->projet->lire) { @@ -126,7 +126,7 @@ if (! empty($conf->ficheinter->enabled) && empty($conf->global->MAIN_SEARCHFORM_ // HR if (! empty($conf->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) { - $arrayresult['searchintouser']=array('position'=>200, 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintouser']=array('position'=>200, 'shortcut'=>'U', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->expensereport->enabled) && empty($conf->global->MAIN_SEARCHFORM_EXPENSEREPORT_DISABLED) && $user->rights->expensereport->lire) { diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index 639db28637d..677fcc17ad2 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -111,7 +111,7 @@ class box_graph_invoices_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php index ca26f1392a8..d1a6d2d5436 100644 --- a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php @@ -110,7 +110,7 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index d192805782e..179501e9bf0 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -113,7 +113,7 @@ class box_graph_orders_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 18b85b2ae80..4979ea6f993 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -112,7 +112,7 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index a0a15cae59a..868ddf60268 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -111,7 +111,7 @@ class box_graph_propales_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index e382f5c8198..39487cf6fea 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -275,7 +275,8 @@ class CMailFile // comme des injections mail par les serveurs de messagerie. $this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers); - $this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; + //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; + $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol; $this->message.= $text_body . $files_encoded; $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol; } @@ -961,8 +962,8 @@ class CMailFile //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol; - $out.= "Content-Type: multipart/mixed; boundary=\"".$this->mixed_boundary."\"".$this->eol2; - $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; + $out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2; + $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received. dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out); return $out; @@ -1014,23 +1015,23 @@ class CMailFile if ($this->atleastoneimage) { - $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; } // Make RFC821 Compliant, replace bare linefeeds - $strContent = preg_replace("/(?global->MAIN_FIX_FOR_BUGGED_MTA)) { - $strContent = preg_replace("/\r\n/si", "\n", $strContent); + $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars } $strContentAltText = ''; if ($this->msgishtml) { $strContentAltText = html_entity_decode(strip_tags($strContent)); - $strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n")); + $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // Check if html header already in message, if not complete the message $strContent = $this->checkIfHTML($strContent); @@ -1038,31 +1039,35 @@ class CMailFile // Make RFC2045 Compliant, split lines //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content - $strContent = rtrim(wordwrap($strContent)); // TODO Using this method creates unexpected line break on text/plain content. + // TODO Encode main content into base64 and use the chunk_split, or quoted-printable + $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // TODO Using this method creates unexpected line break on text/plain content. if ($this->msgishtml) { if ($this->atleastoneimage) { $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message $out.= "--" . $this->alternative_boundary . $this->eol; - $out.= "Content-Type: multipart/related; boundary=\"".$this->related_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->related_boundary . $this->eol; } if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part { - $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.$strContentAltText.$this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; } $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64 $out.= $this->eol.$strContent.$this->eol; if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part @@ -1073,6 +1078,7 @@ class CMailFile else { $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.$strContent.$this->eol; } diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 937634de5d4..666011b3f4a 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -510,6 +510,13 @@ abstract class CommonDocGenerator 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); + + // Units + if ($conf->global->PRODUCT_USE_UNITS) + { + $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short')); + } // Retrieve extrafields $extrafieldkey=$line->element; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 3631a6509ee..aa3fb034e32 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -340,6 +340,15 @@ abstract class CommonObject // No constructor as it is an abstract class + /** + * Return if an object manage the multicompany field and how. + * + * @return int 0=No entity field managed, 1=Test with field entity, 2=Test with link to thirdparty (and sales representative) + */ + function getIsmultientitymanaged() + { + return $this->ismultientitymanaged; + } /** * Check an object id/ref exists @@ -1338,16 +1347,16 @@ abstract class CommonObject $sql = "SELECT MAX(te.".$fieldid.")"; $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && empty($user->rights->societe->client->voir))) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; if (! empty($filter)) { if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility $sql.=$filter; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; //print $filter.' '.$sql."
"; @@ -1363,16 +1372,16 @@ abstract class CommonObject $sql = "SELECT MIN(te.".$fieldid.")"; $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; if (! empty($filter)) { if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility $sql.=$filter; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null @@ -3648,11 +3657,12 @@ abstract class CommonObject * Return HTML table table of source object lines * TODO Move this and previous function into output html class file (htmlline.class.php). * If lines are into a template, title must also be into a template - * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. + * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects. * + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only * @return void */ - function printOriginLinesList() + function printOriginLinesList($restrictlist='') { global $langs, $hookmanager, $conf; @@ -3674,8 +3684,6 @@ abstract class CommonObject foreach ($this->lines as $line) { - - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) { if (empty($line->fk_parent_line)) @@ -3687,7 +3695,7 @@ abstract class CommonObject } else { - $this->printOriginLine($line,$var); + $this->printOriginLine($line, $var, $restrictlist); } $i++; @@ -3700,11 +3708,12 @@ abstract class CommonObject * If lines are into a template, title must also be into a template * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. * - * @param CommonObjectLine $line Line - * @param string $var Var + * @param CommonObjectLine $line Line + * @param string $var Var + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not) * @return void */ - function printOriginLine($line,$var) + function printOriginLine($line, $var, $restrictlist='') { global $langs, $conf; @@ -3803,9 +3812,13 @@ abstract class CommonObject $this->tpl['price'] = price($line->subprice); $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; - if($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $line->getLabelOfUnit('long'); + if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long')); $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; + // Is the line strike or not + $this->tpl['strike']=0; + if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1; + // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); @@ -4043,13 +4056,14 @@ abstract class CommonObject if (in_array(get_class($this), array('Adherent'))) { - $arrayofrecords = array(); // The write_file of templates of adherent class need this + $arrayofrecords = array(); // The write_file of templates of adherent class need this var $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); } else { $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); } + // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. if ($resultwritefile > 0) { @@ -4076,9 +4090,19 @@ abstract class CommonObject include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile=new EcmFiles($this->db); $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename); + + if (! empty($conf->global->PROPOSAL_USE_ONLINE_SIGN)) + { + if (empty($ecmfile->share)) // Because object not found or share not set yet + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } + if ($result > 0) { - $ecmfile->label = md5_file(dol_osencode($destfull)); + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content $ecmfile->fullpath_orig = ''; $ecmfile->gen_or_uploaded = 'generated'; $ecmfile->description = ''; // indexed content @@ -4093,7 +4117,7 @@ abstract class CommonObject { $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content $ecmfile->fullpath_orig = ''; $ecmfile->gen_or_uploaded = 'generated'; $ecmfile->description = ''; // indexed content @@ -4104,6 +4128,21 @@ abstract class CommonObject setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } } + + /*$this->result['fullname']=$destfull; + $this->result['filepath']=$ecmfile->filepath; + $this->result['filename']=$ecmfile->filename;*/ + + // Update the last_main_doc field into main object + $update_main_doc_field=0; + if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1; + if ($update_main_doc_field && ! empty($this->table_element)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'"; + $sql.= ' WHERE rowid = '.$this->id; + $resql = $this->db->query($sql); + if (! $resql) dol_print_error($this->db); + } } } else @@ -4592,17 +4631,18 @@ abstract class CommonObject else return 0; } - /** - * Function to show lines of extrafields with output datas - * - * @param Extrafields $extrafields Extrafield Object - * @param string $mode Show output (view) or input (edit) for extrafield - * @param array $params Optional parameters - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * - * @return string - */ - function showOptionals($extrafields, $mode='view', $params=null, $keyprefix='') + /** + * Function to show lines of extrafields with output datas + * + * @param Extrafields $extrafields Extrafield Object + * @param string $mode Show output (view) or input (edit) for extrafield + * @param array $params Optional parameters + * @param string $keysuffix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * + * @return string + */ + function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='') { global $_POST, $conf, $langs, $action; @@ -4630,12 +4670,12 @@ abstract class CommonObject switch($mode) { case "view": - $value=$this->array_options["options_".$key]; + $value=$this->array_options["options_".$key.$keysuffix]; break; case "edit": - $getposttemp = GETPOST('options_'.$key, 'none'); // GETPOST can get value from GET, POST or setup of default values. + $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc') - if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET('options_'.$key)) + if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) { if (is_array($getposttemp)) { // $getposttemp is an array but following code expects a comma separated string @@ -4675,12 +4715,12 @@ abstract class CommonObject // Convert date into timestamp format (value in memory must be a timestamp) if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) { - $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$this->db->jdate($this->array_options['options_'.$key]); + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$this->db->jdate($this->array_options['options_'.$key]); } // Convert float submited string into real php numeric (value in memory must be a php numeric) if (in_array($extrafields->attribute_type[$key],array('price','double'))) { - $value = isset($_POST["options_".$key])?price2num($_POST["options_".$key]):$this->array_options['options_'.$key]; + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix,'int',3)):$this->array_options['options_'.$key]; } $labeltoshow = $langs->trans($label); @@ -4699,7 +4739,7 @@ abstract class CommonObject $out .= $extrafields->showOutputField($key, $value); break; case "edit": - $out .= $extrafields->showInputField($key, $value, '', $keyprefix, '', 0, $this->id); + $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id); break; } @@ -4712,8 +4752,8 @@ abstract class CommonObject } $out .= "\n"; // Add code to manage list depending on others - if (! empty($conf->use_javascript_ajax)) - $out .= ' + if (! empty($conf->use_javascript_ajax)) { + $out .= ' '."\n"; - $out .= ' '."\n"; + $out .= ' '."\n"; + } } return $out; } + /** * Returns the rights used for this class * @return stdClass diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index 84c49f6392d..bed227eb408 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -51,8 +51,9 @@ abstract class CommonObjectLine extends CommonObject /** - * Returns the text label from units dictionary - * + * Returns the translation key from units dictionary. + * A langs->trans() must be called on result to get translated value. + * * @param string $type Label type (long or short) * @return string|int <0 if ko, label if ok */ diff --git a/htdocs/core/class/emailsenderprofile.class.php b/htdocs/core/class/emailsenderprofile.class.php index 66e37744cc7..e792a4c3f0a 100644 --- a/htdocs/core/class/emailsenderprofile.class.php +++ b/htdocs/core/class/emailsenderprofile.class.php @@ -43,11 +43,6 @@ class EmailSenderProfile extends CommonObject * @var string Name of table without prefix where object is stored */ public $table_element = 'c_email_senderprofile'; - - /** - * @var array Does this field is linked to a thirdparty ? - */ - protected $isnolinkedbythird = 1; /** * @var array Does emailsenderprofile support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe */ @@ -267,22 +262,24 @@ class EmailSenderProfile extends CommonObject function getNomUrl($withpicto=0) { global $db, $conf, $langs; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; - $result = ''; - $companylink = ''; + $result = ''; + $companylink = ''; - $url=''; - //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id; + $label=$this->label; + + $url=''; + //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id; $linkstart = ''; $linkend=''; - if ($withpicto) - { - $result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend); - if ($withpicto != 2) $result.=' '; + if ($withpicto) + { + $result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend); + if ($withpicto != 2) $result.=' '; } $result.= $linkstart . $this->label . $linkend; return $result; diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 43af66e51e7..7130287b6bd 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -806,13 +806,13 @@ class ExtraFields * @param string $key Key of attribute * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) * @param string $moreparam To add more parametes on html input tag - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * @param string $keysuffix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) * @param mixed $showsize Value for css to define size. May also be a numeric. * @param int $objectid Current object id * @return string */ - function showInputField($key, $value, $moreparam='', $keyprefix='', $keysuffix='', $showsize=0, $objectid=0) + function showInputField($key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0, $objectid=0) { global $conf,$langs; @@ -831,51 +831,51 @@ class ExtraFields if ($computed) { - if ($keysuffix != 'search_') return ''.$langs->trans("AutomaticallyCalculated").''; - else return ''; + if ($keyprefix != 'search_') return ''.$langs->trans("AutomaticallyCalculated").''; + else return ''; } if (empty($showsize)) { - if ($type == 'date') - { - //$showsize=10; - $showsize = 'minwidth100imp'; - } + if ($type == 'date') + { + //$showsize=10; + $showsize = 'minwidth100imp'; + } elseif ($type == 'datetime') - { - //$showsize=19; - $showsize = 'minwidth200imp'; - } - elseif (in_array($type,array('int','double','price'))) - { - //$showsize=10; - $showsize = 'maxwidth75'; - } - elseif ($type == 'url') - { - $showsize='minwidth400'; - } - elseif ($type == 'boolean') - { - $showsize=''; - } - else - { - if (round($size) < 12) - { - $showsize = 'minwidth100'; - } - else if (round($size) <= 48) - { - $showsize = 'minwidth200'; - } - else - { - //$showsize=48; - $showsize = 'minwidth400'; - } - } + { + //$showsize=19; + $showsize = 'minwidth200imp'; + } + elseif (in_array($type,array('int','double','price'))) + { + //$showsize=10; + $showsize = 'maxwidth75'; + } + elseif ($type == 'url') + { + $showsize='minwidth400'; + } + elseif ($type == 'boolean') + { + $showsize=''; + } + else + { + if (round($size) < 12) + { + $showsize = 'minwidth100'; + } + else if (round($size) <= 48) + { + $showsize = 'minwidth200'; + } + else + { + //$showsize=48; + $showsize = 'minwidth400'; + } + } } if (in_array($type,array('date','datetime'))) @@ -893,26 +893,26 @@ class ExtraFields if (! is_object($form)) $form=new Form($this->db); // TODO Must also support $moreparam - $out = $form->select_date($value, $keysuffix.'options_'.$key.$keyprefix, $showtime, $showtime, $required, '', 1, ($keysuffix != 'search_' ? 1 : 0), 1, 0, 1); + $out = $form->select_date($value, $keyprefix.'options_'.$key.$keysuffix, $showtime, $showtime, $required, '', 1, ($keyprefix != 'search_' ? 1 : 0), 1, 0, 1); } elseif (in_array($type,array('int'))) { $tmp=explode(',',$size); $newsize=$tmp[0]; - $out=''; + $out=''; } elseif ($type == 'varchar') { - $out=''; + $out=''; } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out=''; + $out=''; } elseif ($type == 'text') { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keysuffix.'options_'.$key.$keyprefix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); + $doleditor=new DolEditor($keyprefix.'options_'.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); $out=$doleditor->Create(1); } elseif ($type == 'boolean') @@ -923,21 +923,21 @@ class ExtraFields } else { $checked=' value="1" '; } - $out=''; + $out=''; } elseif ($type == 'price') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value=price($value); } - $out=' '.$langs->getCurrencySymbol($conf->currency); + $out=' '.$langs->getCurrencySymbol($conf->currency); } elseif ($type == 'double') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value=price($value); } - $out=' '; + $out=' '; } elseif ($type == 'select') { @@ -945,10 +945,10 @@ class ExtraFields if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keysuffix.'options_'.$key.$keyprefix, array(), 0); + $out.= ajax_combobox($keyprefix.'options_'.$key.$keysuffix, array(), 0); } - $out.=''; $out.=''; foreach ($param['options'] as $key => $val) { @@ -967,10 +967,10 @@ class ExtraFields if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keysuffix.'options_'.$key.$keyprefix, array(), 0); + $out.= ajax_combobox($keyprefix.'options_'.$key.$keysuffix, array(), 0); } - $out.=''; if (is_array($param['options'])) { $param_list=array_keys($param['options']); @@ -1132,7 +1132,7 @@ class ExtraFields $form = new Form($db); $value_arr=explode(',',$value); - $out=$form->multiselectarray($keysuffix.'options_'.$key.$keyprefix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); + $out=$form->multiselectarray($keyprefix.'options_'.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); } elseif ($type == 'radio') @@ -1140,11 +1140,11 @@ class ExtraFields $out=''; foreach ($param['options'] as $keyopt => $val) { - $out.=''.$val.'
'; + $out.='/>
'; } } elseif ($type == 'chkbxlst') @@ -1268,15 +1268,15 @@ class ExtraFields if (empty($labeltoshow)) $labeltoshow = '(not defined)'; - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + $data[$obj->rowid]=$labeltoshow; + } + + if (! empty($InfoFieldList[3])) { + $parent = $parentName . ':' . $obj->{$parentField}; + } + $data[$obj->rowid]=$labeltoshow; - } - - if (! empty($InfoFieldList[3])) { - $parent = $parentName . ':' . $obj->{$parentField}; - } - - $data[$obj->rowid]=$labeltoshow; } $i ++; @@ -1286,7 +1286,7 @@ class ExtraFields require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; $form = new Form($db); - $out=$form->multiselectarray($keysuffix.'options_'.$key.$keyprefix, $data, $value_arr, '', 0, '', 0, '100%'); + $out=$form->multiselectarray($keyprefix.'options_'.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); } else { print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
'; @@ -1305,40 +1305,41 @@ class ExtraFields dol_include_once($InfoFieldList[1]); if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) { - $valuetoshow=$value; - if (!empty($value)) - { - $object = new $InfoFieldList[0]($this->db); - $resfetch=$object->fetch($value); - if ($resfetch > 0) - { - $valuetoshow=$object->ref; - if ($object->element == 'societe') $valuetoshow=$object->name; // Special case for thirdparty because ->ref is not name but id (because name is not unique) - } - } - $out.=''; + $valuetoshow=$value; + if (!empty($value)) + { + $object = new $InfoFieldList[0]($this->db); + $resfetch=$object->fetch($value); + if ($resfetch > 0) + { + $valuetoshow=$object->ref; + if ($object->element == 'societe') $valuetoshow=$object->name; // Special case for thirdparty because ->ref is not name but id (because name is not unique) + } + } + $out.=''; } else { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - $out.='Error bad setup of extrafield'; + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + $out.='Error bad setup of extrafield'; } } elseif ($type == 'password') { // If prefix is 'search_', field is used as a filter, we use a common text field. - $out=''; + $out=''; } if (!empty($hidden)) { - $out=''; + $out=''; } /* Add comments if ($type == 'date') $out.=' (YYYY-MM-DD)'; - elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; - */ + elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; + */ return $out; } + /** * Return HTML string to put an output field into a page * diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index faf26f7c111..aef8f98648f 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -438,8 +438,11 @@ class Form $s='';$textfordialog=''; - $htmltext=str_replace('"',""",$htmltext); - if ($tooltiptrigger != '') + if ($tooltiptrigger == '') + { + $htmltext=str_replace('"',""",$htmltext); + } + else { $classfortooltip='classfortooltiponclick'; $textfordialog.=''; @@ -4519,6 +4522,8 @@ class Form { global $langs,$conf,$mysoc; + $langs->load('errors'); + $return=''; // Define defaultnpr, defaultttx and defaultcode @@ -4687,7 +4692,7 @@ class Form * * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0). * @param string $prefix Prefix for fields name - * @param int $h 1=Show also hours + * @param int $h 1=Show also hours (-1 has same effect, but hour and minutes are prefilled with 23:59 if $set_time = -1) * @param int $m 1=Show also minutes * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only * @param string $form_name Not used @@ -4742,6 +4747,7 @@ class Form { $shour = dol_print_date($set_time, "%H"); $smin = dol_print_date($set_time, "%M"); + $ssec = dol_print_date($set_time, "%S"); } } else @@ -4750,8 +4756,9 @@ class Form $syear = ''; $smonth = ''; $sday = ''; - $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? '' : $conf->global->MAIN_DEFAULT_DATE_HOUR; - $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? '' : $conf->global->MAIN_DEFAULT_DATE_MIN; + $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR; + $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN; + $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC; } // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' @@ -4932,6 +4939,8 @@ class Form $retstring.=''; } $retstring.=''; + + $retstring.=''; } // Add a "Now" link @@ -5243,6 +5252,7 @@ class Form * @param string $placeholder String to use as placeholder * @param integer $acceptdelayedhtml 1 if caller request to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect) * @return string HTML select string + * @see ajax_combobox in ajax.lib.php */ static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0) { @@ -5252,7 +5262,7 @@ class Form // TODO Use an internal dolibarr component instead of select2 if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return ''; - $out=''; + $out=''; $tmpplugin='select2'; $outdelayed="\n".' @@ -5267,44 +5277,40 @@ class Form url: "'.$url.'", dataType: \'json\', delay: 250, - data: function (searchTerm, pageNumber, context) { + data: function (params) { return { - q: searchTerm, // search term - page: pageNumber + q: params.term, // search term + page: params.page }; }, - results: function (remoteData, pageNumber, query) { - console.log(remoteData); - saveRemoteData = remoteData; + processResults: function (data) { + // parse the results into the format expected by Select2. + // since we are using custom formatting functions we do not need to alter the remote JSON data + //console.log(data); + saveRemoteData = data; /* format json result for select2 */ result = [] - $.each( remoteData, function( key, value ) { + $.each( data, function( key, value ) { result.push({id: key, text: value.text}); }); //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false} - return {results: result, more:false} - }, - /*processResults: function (data, page) { - // parse the results into the format expected by Select2. - // since we are using custom formatting functions we do not need to - // alter the remote JSON data - console.log(data); - return { - results: data.items - }; - },*/ + //console.log(result); + return {results: result, more: false} + }, cache: true }, - dropdownCssClass: "css-'.$htmlname.'", + language: select2arrayoflanguage, + /* dropdownCssClass: "css-'.$htmlname.'", */ placeholder: "'.dol_escape_js($placeholder).'", - escapeMarkup: function (markup) { return markup; }, // let our custom formatter work + escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: '.$minimumInputLength.', formatResult: function(result, container, query, escapeMarkup) { return escapeMarkup(result.text); - } + }, }); '.($callurlonselect ? ' + /* Code to execute a GET when we select a value */ $(".'.$htmlname.'").change(function() { var selected = $(".'.$htmlname.'").select2("val"); $(".'.$htmlname.'").select2("val",""); /* reset visible combo value */ @@ -6442,7 +6448,7 @@ class Form */ function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array()) { - global $db,$conf,$langs; + global $db, $conf, $langs, $user; $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1'; $sql.= ' AND entity IN (0,'.getEntity('').')'; @@ -6453,13 +6459,14 @@ class Form if ($resql) { $out = ''; + if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); if (!empty($target)) { diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 7559179c87d..f105ef78263 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -34,289 +34,289 @@ */ class FormFile { - private $db; + private $db; - public $error; - public $numoffiles; - public $infofiles; // Used to return informations by function getDocumentsLink + public $error; + public $numoffiles; + public $infofiles; // Used to return informations by function getDocumentsLink - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - $this->numoffiles=0; - return 1; - } + */ + function __construct($db) + { + $this->db = $db; + $this->numoffiles=0; + return 1; + } - /** - * Show form to upload a new file + /** + * Show form to upload a new file * - * @param string $url Url - * @param string $title Title zone (Title or '' or 'none') - * @param int $addcancel 1=Add 'Cancel' button - * @param int $sectionid If upload must be done inside a particular ECM section - * @param int $perm Value of permission to allow upload - * @param int $size Length of input file area. Deprecated. - * @param Object $object Object to use (when attachment is done on an element) - * @param string $options Add an option column - * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used. - * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__' - * @param integer $linkfiles 1=Also add form to link files, 0=Do not show form to link files - * @param string $htmlname Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM) - * @param string $accept Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*') - * @return int <0 if KO, >0 if OK - */ - function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='') - { - global $conf,$langs, $hookmanager; - $hookmanager->initHooks(array('formfile')); + * @param string $url Url + * @param string $title Title zone (Title or '' or 'none') + * @param int $addcancel 1=Add 'Cancel' button + * @param int $sectionid If upload must be done inside a particular ECM section + * @param int $perm Value of permission to allow upload + * @param int $size Length of input file area. Deprecated. + * @param Object $object Object to use (when attachment is done on an element) + * @param string $options Add an option column + * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used. + * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__' + * @param integer $linkfiles 1=Also add form to link files, 0=Do not show form to link files + * @param string $htmlname Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM) + * @param string $accept Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*') + * @return int <0 if KO, >0 if OK + */ + function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='') + { + global $conf,$langs, $hookmanager; + $hookmanager->initHooks(array('formfile')); - if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0; + if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0; if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2)) - { - // TODO: Check this works with 2 forms on same page - // TODO: Check this works with GED module, otherwise, force useajax to 0 - // TODO: This does not support option savingdocmask - // TODO: This break feature to upload links too - return $this->_formAjaxFileUpload($object); - } - else - { - //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed - if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { - return 1; - } + { + // TODO: Check this works with 2 forms on same page + // TODO: Check this works with GED module, otherwise, force useajax to 0 + // TODO: This does not support option savingdocmask + // TODO: This break feature to upload links too + return $this->_formAjaxFileUpload($object); + } + else + { + //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed + if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { + return 1; + } - $maxlength=$size; + $maxlength=$size; - $out = "\n\n\n"; + $out = "\n\n\n"; - if (empty($title)) $title=$langs->trans("AttachANewFile"); - if ($title != 'none') $out.=load_fiche_titre($title, null, null); + if (empty($title)) $title=$langs->trans("AttachANewFile"); + if ($title != 'none') $out.=load_fiche_titre($title, null, null); - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; - $out .= ''; - $out .= ''; + $out .= '
'; + $out .= ''; - if (! empty($options)) $out .= ''; + if (! empty($options)) $out .= ''; - $out .= '"; + if (! empty($conf->global->MAIN_UPLOAD_DOC)) + { + if ($perm) + { + $langs->load('other'); + $out .= ' '; + $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1); + } + } + else + { + $out .= ' ('.$langs->trans("UploadDisabled").')'; + } + $out .= ""; - if ($savingdocmask) - { - $out .= ''; - if (! empty($options)) $out .= ''; - $out .= ''; + if (! empty($options)) $out .= ''; + $out .= ''; - $out .= ''; - } + $out .= ''; + $out .= ''; + } - $out .= "
'.$options.''.$options.''; + $out .= ''; - $max=$conf->global->MAIN_UPLOAD_DOC; // En Kb - $maxphp=@ini_get('upload_max_filesize'); // En inconnu - if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1; - if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024; - if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024; - if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024; - // Now $max and $maxphp are in Kb - if ($maxphp > 0) $max=min($max,$maxphp); + $max=$conf->global->MAIN_UPLOAD_DOC; // En Kb + $maxphp=@ini_get('upload_max_filesize'); // En inconnu + if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1; + if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024; + if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024; + if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024; + // Now $max and $maxphp are in Kb + if ($maxphp > 0) $max=min($max,$maxphp); - if ($max > 0) - { - $out .= ''; - } + if ($max > 0) + { + $out .= ''; + } - $out .= 'global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple'); - $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); - $out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""'); - $out .= '>'; - $out .= ' '; - $out .= 'global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); - $out .= '>'; + $out .= 'global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple'); + $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); + $out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""'); + $out .= '>'; + $out .= ' '; + $out .= 'global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); + $out .= '>'; - if ($addcancel) - { - $out .= '   '; - $out .= ''; - } + if ($addcancel) + { + $out .= '   '; + $out .= ''; + } - if (! empty($conf->global->MAIN_UPLOAD_DOC)) - { - if ($perm) - { - $langs->load('other'); - $out .= ' '; - $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1); - } - } - else - { - $out .= ' ('.$langs->trans("UploadDisabled").')'; - } - $out .= "
'.$options.''; + if ($savingdocmask) + { + $out .= '
'.$options.''; $out .= ' '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName")); - $out .= '
"; + $out .= ""; - $out .= '
'; - if (empty($sectionid)) $out .= '
'; + $out .= ''; + if (empty($sectionid)) $out .= '
'; - $out .= "\n\n"; + $out .= "\n\n"; - if ($linkfiles) - { - $out .= "\n\n"; - $langs->load('link'); - $title = $langs->trans("LinkANewFile"); - $out .= load_fiche_titre($title, null, null); - $out .= '
'; - $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm); - $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object); + $out .= '
'; + $out .= '
'; + if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= ' '; + $out .= ''; + $out .= '
'; + $out .= '
'; + if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= ' '; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= '
'; + $out .= '
'; + $out .= 'global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); + $out .= '>'; + $out .= '
'; + $out .= '
'; + $out .= '
'; + $out .= '
'; + $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm); + $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object); - $out .= "\n\n"; - } + $out .= "\n\n"; + } - if (empty($res)) - { - print '
'; - print $out; - print '
'; - } + if (empty($res)) + { + print '
'; + print $out; + print '
'; + } - print $hookmanager->resPrint; + print $hookmanager->resPrint; - return 1; - } - } + return 1; + } + } - /** - * Show the box with list of available documents for object - * - * @param string $modulepart propal, facture, facture_fourn, ... - * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. - * @param string $filedir Directory to scan - * @param string $urlsource Url of origin page (for return) - * @param int $genallowed Generation is allowed (1/0 or array of formats) - * @param int $delallowed Remove is allowed (1/0) - * @param string $modelselected Model to preselect by default - * @param integer $allowgenifempty Show warning if no model activated - * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) - * @param int $iconPDF Show only PDF icon with link (1/0) - * @param int $notused Not used - * @param integer $noform Do not output html form tags - * @param string $param More param on http links - * @param string $title Title to show on top of form - * @param string $buttonlabel Label on submit button - * @param string $codelang Default language code to use on lang combo box if multilang is enabled - * @return int <0 if KO, number of shown files if OK - * @deprecated Use print xxx->showdocuments() instead. - */ - function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='') - { - $this->numoffiles=0; - print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang); - return $this->numoffiles; - } + /** + * Show the box with list of available documents for object + * + * @param string $modulepart propal, facture, facture_fourn, ... + * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. + * @param string $filedir Directory to scan + * @param string $urlsource Url of origin page (for return) + * @param int $genallowed Generation is allowed (1/0 or array of formats) + * @param int $delallowed Remove is allowed (1/0) + * @param string $modelselected Model to preselect by default + * @param integer $allowgenifempty Show warning if no model activated + * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) + * @param int $iconPDF Show only PDF icon with link (1/0) + * @param int $notused Not used + * @param integer $noform Do not output html form tags + * @param string $param More param on http links + * @param string $title Title to show on top of form + * @param string $buttonlabel Label on submit button + * @param string $codelang Default language code to use on lang combo box if multilang is enabled + * @return int <0 if KO, number of shown files if OK + * @deprecated Use print xxx->showdocuments() instead. + */ + function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='') + { + $this->numoffiles=0; + print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang); + return $this->numoffiles; + } - /** - * Return a string to show the box with list of available documents for object. - * This also set the property $this->numoffiles - * - * @param string $modulepart Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...) - * @param string $modulesubdir Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. - * @param string $filedir Directory to scan - * @param string $urlsource Url of origin page (for return) - * @param int $genallowed Generation is allowed (1/0 or array list of templates) - * @param int $delallowed Remove is allowed (1/0) - * @param string $modelselected Model to preselect by default - * @param integer $allowgenifempty Allow generation even if list of template ($genallowed) is empty (show however a warning) - * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) - * @param int $iconPDF Deprecated, see getDocumentsLink - * @param int $notused Not used - * @param integer $noform Do not output html form tags - * @param string $param More param on http links - * @param string $title Title to show on top of form - * @param string $buttonlabel Label on submit button - * @param string $codelang Default language code to use on lang combo box if multilang is enabled - * @param string $morepicto Add more HTML content into cell with picto - * @param Object $object Object when method is called from an object card. - * @return string Output string with HTML array of documents (might be empty string) - */ - function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null) - { + /** + * Return a string to show the box with list of available documents for object. + * This also set the property $this->numoffiles + * + * @param string $modulepart Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...) + * @param string $modulesubdir Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. + * @param string $filedir Directory to scan + * @param string $urlsource Url of origin page (for return) + * @param int $genallowed Generation is allowed (1/0 or array list of templates) + * @param int $delallowed Remove is allowed (1/0) + * @param string $modelselected Model to preselect by default + * @param integer $allowgenifempty Allow generation even if list of template ($genallowed) is empty (show however a warning) + * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) + * @param int $iconPDF Deprecated, see getDocumentsLink + * @param int $notused Not used + * @param integer $noform Do not output html form tags + * @param string $param More param on http links + * @param string $title Title to show on top of form + * @param string $buttonlabel Label on submit button + * @param string $codelang Default language code to use on lang combo box if multilang is enabled + * @param string $morepicto Add more HTML content into cell with picto + * @param Object $object Object when method is called from an object card. + * @return string Output string with HTML array of documents (might be empty string) + */ + function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null) + { // Deprecation warning if (0 !== $iconPDF) { dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING); } - global $langs, $conf, $user, $hookmanager; - global $form, $bc; + global $langs, $conf, $user, $hookmanager; + global $form, $bc; - if (! is_object($form)) $form=new Form($this->db); + if (! is_object($form)) $form=new Form($this->db); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - // For backward compatibility - if (! empty($iconPDF)) { - return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir); - } + // For backward compatibility + if (! empty($iconPDF)) { + return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir); + } - $printer=0; - if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport'))) // The direct print feature is implemented only for such elements - { - $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false; - } + $printer=0; + if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport'))) // The direct print feature is implemented only for such elements + { + $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false; + } - $hookmanager->initHooks(array('formfile')); - $forname='builddoc'; - $out=''; + $hookmanager->initHooks(array('formfile')); + $forname='builddoc'; + $out=''; - $headershown=0; - $showempty=0; - $i=0; + $headershown=0; + $showempty=0; + $i=0; - $out.= "\n".''."\n"; - //print 'filedir='.$filedir; + $out.= "\n".''."\n"; + //print 'filedir='.$filedir; - if (preg_match('/massfilesarea_/', $modulepart)) - { - $out.='

'."\n"; + if (preg_match('/massfilesarea_/', $modulepart)) + { + $out.='

'."\n"; $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; $title.=''; - } + } - $titletoshow=$langs->trans("Documents"); - if (! empty($title)) $titletoshow=$title; + $titletoshow=$langs->trans("Documents"); + if (! empty($title)) $titletoshow=$title; - // Show table - if ($genallowed) - { - $modellist=array(); + // Show table + if ($genallowed) + { + $modellist=array(); - if ($modulepart == 'company') - { - $showempty=1; - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php'; - $modellist=ModeleThirdPartyDoc::liste_modeles($this->db); - } - } - else if ($modulepart == 'propal') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php'; - $modellist=ModelePDFPropales::liste_modeles($this->db); - } - } + if ($modulepart == 'company') + { + $showempty=1; + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php'; + $modellist=ModeleThirdPartyDoc::liste_modeles($this->db); + } + } + else if ($modulepart == 'propal') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php'; + $modellist=ModelePDFPropales::liste_modeles($this->db); + } + } else if ($modulepart == 'supplier_proposal') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php'; - $modellist=ModelePDFSupplierProposal::liste_modeles($this->db); - } - } - else if ($modulepart == 'commande') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; - $modellist=ModelePDFCommandes::liste_modeles($this->db); - } - } - elseif ($modulepart == 'expedition') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; - $modellist=ModelePDFExpedition::liste_modeles($this->db); - } - } - elseif ($modulepart == 'livraison') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php'; - $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db); - } - } - else if ($modulepart == 'ficheinter') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; - $modellist=ModelePDFFicheinter::liste_modeles($this->db); - } - } - elseif ($modulepart == 'facture') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; - $modellist=ModelePDFFactures::liste_modeles($this->db); - } - } - elseif ($modulepart == 'contract') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; - $modellist=ModelePDFContract::liste_modeles($this->db); - } - } - elseif ($modulepart == 'project') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; - $modellist=ModelePDFProjects::liste_modeles($this->db); - } - } - elseif ($modulepart == 'project_task') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php'; - $modellist=ModelePDFTask::liste_modeles($this->db); - } - } - elseif ($modulepart == 'product') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; - $modellist=ModelePDFProduct::liste_modeles($this->db); - } - } - elseif ($modulepart == 'export') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; - $modellist=ModeleExports::liste_modeles($this->db); - } - } - else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php'; - $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db); - } - } - else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; - $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db); - } - } + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php'; + $modellist=ModelePDFSupplierProposal::liste_modeles($this->db); + } + } + else if ($modulepart == 'commande') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; + $modellist=ModelePDFCommandes::liste_modeles($this->db); + } + } + elseif ($modulepart == 'expedition') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; + $modellist=ModelePDFExpedition::liste_modeles($this->db); + } + } + elseif ($modulepart == 'livraison') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php'; + $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db); + } + } + else if ($modulepart == 'ficheinter') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; + $modellist=ModelePDFFicheinter::liste_modeles($this->db); + } + } + elseif ($modulepart == 'facture') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; + $modellist=ModelePDFFactures::liste_modeles($this->db); + } + } + elseif ($modulepart == 'contract') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; + $modellist=ModelePDFContract::liste_modeles($this->db); + } + } + elseif ($modulepart == 'project') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; + $modellist=ModelePDFProjects::liste_modeles($this->db); + } + } + elseif ($modulepart == 'project_task') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php'; + $modellist=ModelePDFTask::liste_modeles($this->db); + } + } + elseif ($modulepart == 'product') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; + $modellist=ModelePDFProduct::liste_modeles($this->db); + } + } + elseif ($modulepart == 'export') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; + $modellist=ModeleExports::liste_modeles($this->db); + } + } + else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php'; + $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db); + } + } + else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; + $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db); + } + } else if ($modulepart == 'supplier_payment') { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; - $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db); - } - } - else if ($modulepart == 'remisecheque') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php'; - $modellist=ModeleChequeReceipts::liste_modeles($this->db); - } - } - elseif ($modulepart == 'donation') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php'; - $modellist=ModeleDon::liste_modeles($this->db); - } - } - elseif ($modulepart == 'member') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php'; - $modellist=ModelePDFCards::liste_modeles($this->db); - } - } - elseif ($modulepart == 'agenda') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php'; - $modellist=ModeleAction::liste_modeles($this->db); - } - } - else if ($modulepart == 'expensereport') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; - $modellist=ModeleExpenseReport::liste_modeles($this->db); - } - } - else if ($modulepart == 'unpaid') - { - $modellist=''; - } - elseif ($modulepart == 'user') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php'; - $modellist=ModelePDFUser::liste_modeles($this->db); - } - } - elseif ($modulepart == 'usergroup') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php'; - $modellist=ModelePDFUserGroup::liste_modeles($this->db); - } - } - else //if ($modulepart != 'agenda') - { - // For normalized standard modules - $file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); - if (file_exists($file)) - { - $res=include_once $file; - } - // For normalized external modules - else + if (is_array($genallowed)) $modellist=$genallowed; + else { - $file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); - $res=include_once $file; - } - $class='Modele'.ucfirst($modulepart); - if (class_exists($class)) - { - $modellist=call_user_func($class.'::liste_modeles',$this->db); - } - else - { - dol_print_error($this->db,'Bad value for modulepart'); - return -1; - } - } + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; + $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db); + } + } + else if ($modulepart == 'remisecheque') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php'; + $modellist=ModeleChequeReceipts::liste_modeles($this->db); + } + } + elseif ($modulepart == 'donation') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php'; + $modellist=ModeleDon::liste_modeles($this->db); + } + } + elseif ($modulepart == 'member') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php'; + $modellist=ModelePDFCards::liste_modeles($this->db); + } + } + elseif ($modulepart == 'agenda') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php'; + $modellist=ModeleAction::liste_modeles($this->db); + } + } + else if ($modulepart == 'expensereport') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; + $modellist=ModeleExpenseReport::liste_modeles($this->db); + } + } + else if ($modulepart == 'unpaid') + { + $modellist=''; + } + elseif ($modulepart == 'user') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php'; + $modellist=ModelePDFUser::liste_modeles($this->db); + } + } + elseif ($modulepart == 'usergroup') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php'; + $modellist=ModelePDFUserGroup::liste_modeles($this->db); + } + } + else //if ($modulepart != 'agenda') + { + // For normalized standard modules + $file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); + if (file_exists($file)) + { + $res=include_once $file; + } + // For normalized external modules + else + { + $file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); + $res=include_once $file; + } + $class='Modele'.ucfirst($modulepart); + if (class_exists($class)) + { + $modellist=call_user_func($class.'::liste_modeles',$this->db); + } + else + { + dol_print_error($this->db,'Bad value for modulepart'); + return -1; + } + } - // Set headershown to avoit to have table opened a second time later - $headershown=1; + // Set headershown to avoit to have table opened a second time later + $headershown=1; - $buttonlabeltoshow=$buttonlabel; - if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate'); + $buttonlabeltoshow=$buttonlabel; + if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate'); - if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form'; // So we switch to form after a generation - if (empty($noform)) $out.= '
'; - $out.= ''; - $out.= ''; + if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form'; // So we switch to form after a generation + if (empty($noform)) $out.= ''; + $out.= ''; + $out.= ''; - $out.= load_fiche_titre($titletoshow, '', ''); - $out.= '
'; - $out.= ''; + $out.= load_fiche_titre($titletoshow, '', ''); + $out.= '
'; + $out.= '
'; - $out.= ''; + $out.= ''; - $addcolumforpicto=($delallowed || $printer || $morepicto); - $out.= ''; + // Button + $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') + { + $langs->load("errors"); + $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); + } + if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; + if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; + $out.= $genbutton; + $out.= ''; - if (!empty($hookmanager->hooks['formfile'])) - { - foreach($hookmanager->hooks['formfile'] as $module) - { - if (method_exists($module, 'formBuilddocLineOptions')) $out .= ''; - } - } - $out.= ''; + if (!empty($hookmanager->hooks['formfile'])) + { + foreach($hookmanager->hooks['formfile'] as $module) + { + if (method_exists($module, 'formBuilddocLineOptions')) $out .= ''; + } + } + $out.= ''; - // Execute hooks - $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart); - if (is_object($hookmanager)) - { - $reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']); - $out.= $hookmanager->resPrint; - } + // Execute hooks + $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart); + if (is_object($hookmanager)) + { + $reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']); + $out.= $hookmanager->resPrint; + } - } + } - // Get list of files - if (! empty($filedir)) - { - $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC); + // Get list of files + if (! empty($filedir)) + { + $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC); - $link_list = array(); - if (is_object($object)) - { - require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; - $link = new Link($this->db); - $sortfield = $sortorder = null; - $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder); - } + $link_list = array(); + if (is_object($object)) + { + require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; + $link = new Link($this->db); + $sortfield = $sortorder = null; + $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder); + } - $out.= ''."\n"; + $out.= ''."\n"; - // Show title of array if not already shown - if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown) - { - $headershown=1; - $out.= '
'.$titletoshow.'
'."\n"; - $out.= '
'; - $out.= '
'; + $addcolumforpicto=($delallowed || $printer || $morepicto); + $out.= ''; - // Model - if (! empty($modellist)) - { - $out.= ''.$langs->trans('Model').' '; - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('model'); - } - else - { - $out.= '
'.$langs->trans("Files").'
'; - } + // Model + if (! empty($modellist)) + { + $out.= ''.$langs->trans('Model').' '; + if (is_array($modellist) && count($modellist) == 1) // If there is only one element + { + $arraykeys=array_keys($modellist); + $modelselected=$arraykeys[0]; + } + $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('model'); + } + else + { + $out.= '
'.$langs->trans("Files").'
'; + } - // Language code (if multilang) - if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; - $formadmin=new FormAdmin($this->db); - $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); - $morecss='maxwidth150'; - if (! empty($conf->browser->phone)) $morecss='maxwidth100'; - $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss); - } - else - { - $out.= ' '; - } + // Language code (if multilang) + if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin=new FormAdmin($this->db); + $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); + $morecss='maxwidth150'; + if (! empty($conf->browser->phone)) $morecss='maxwidth100'; + $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss); + } + else + { + $out.= ' '; + } - // Button - $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') - { - $langs->load("errors"); - $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); - } - if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; - if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; - $out.= $genbutton; - $out.= '
'."\n"; - } + // Show title of array if not already shown + if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown) + { + $headershown=1; + $out.= '
'.$titletoshow.'
'."\n"; + $out.= '
'; + $out.= '
'."\n"; + } - // Loop on each file found + // Loop on each file found if (is_array($file_list)) { foreach($file_list as $file) { // Define relative path for download link (depends on module) $relativepath=$file["name"]; // Cas general - if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"]; // Cas propal, facture... + if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"]; // Cas propal, facture... if ($modulepart == 'export') $relativepath = $file["name"]; // Other case $out.= ''; @@ -713,8 +713,8 @@ class FormFile // Show file name with link to download $out.= ''; - } + $out.=''; + } - if (is_object($hookmanager)) - { - $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath); - $res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file); - if (empty($res)) - { - $out .= $hookmanager->resPrint; // Complete line - $out.= ''; - } - else $out = $hookmanager->resPrint; // Replace line - } + if (is_object($hookmanager)) + { + $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath); + $res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file); + if (empty($res)) + { + $out .= $hookmanager->resPrint; // Complete line + $out.= ''; + } + else $out = $hookmanager->resPrint; // Replace line + } } - $this->numoffiles++; - } - // Loop on each file found - if (is_array($link_list)) - { - $colspan=2; + $this->numoffiles++; + } + // Loop on each file found + if (is_array($link_list)) + { + $colspan=2; - foreach($link_list as $file) - { - $out.=''; - $out.=''; - $out.=''; - if ($delallowed || $printer || $morepicto) $out.=''; - $out.=''."\n"; - } - $this->numoffiles++; - } + foreach($link_list as $file) + { + $out.=''; + $out.=''; + $out.=''; + if ($delallowed || $printer || $morepicto) $out.=''; + $out.=''."\n"; + } + $this->numoffiles++; + } if (count($file_list) == 0 && count($link_list) == 0 && $headershown) - { - $out.=''."\n"; - } + { + $out.=''."\n"; + } - } + } - if ($headershown) - { - // Affiche pied du tableau - $out.= "
'; - $tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param); - $out.= ($tmp?$tmp.' ':''); + $tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param); + $out.= ($tmp?$tmp.' ':''); $out.= 'trans("PrintFile", $relativepath),'printer.png').''; + $out.= ' '.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').''; } if ($morepicto) { $morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto); - $out.=$morepicto; + $out.=$morepicto; } - $out.='
'; - $out.=''; - $out.=$file->label; - $out.=''; - $out.=''; - $out.=dol_print_date($file->datea,'dayhour'); - $out.='
'; + $out.=''; + $out.=$file->label; + $out.=''; + $out.=''; + $out.=dol_print_date($file->datea,'dayhour'); + $out.='
'.$langs->trans("None").'
'.$langs->trans("None").'
\n"; - $out.= "
\n"; - if ($genallowed) - { - if (empty($noform)) $out.= '
'."\n"; - } - } - $out.= ''."\n"; - //return ($i?$i:$headershown); - return $out; - } + if ($headershown) + { + // Affiche pied du tableau + $out.= "\n"; + $out.= "
\n"; + if ($genallowed) + { + if (empty($noform)) $out.= ''."\n"; + } + } + $out.= ''."\n"; + //return ($i?$i:$headershown); + return $out; + } - /** - * Show a Document icon with link(s) - * You may want to call this into a div like this: - * print '
'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'
'; - * - * @param string $modulepart propal, facture, facture_fourn, ... - * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. - * @param string $filedir Full path to directory to scan - * @param string $filter Filter filenames on this regex string (Example: '\.pdf$') - * @return string Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles - */ - function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='') - { - global $conf, $langs; + /** + * Show a Document icon with link(s) + * You may want to call this into a div like this: + * print '
'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'
'; + * + * @param string $modulepart propal, facture, facture_fourn, ... + * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. + * @param string $filedir Full path to directory to scan + * @param string $filter Filter filenames on this regex string (Example: '\.pdf$') + * @return string Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles + */ + function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='') + { + global $conf, $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $out=''; - $this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array()); + $out=''; + $this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array()); - $filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+'; + $filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+'; - $file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files) + $file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files) - // For ajax treatment + // For ajax treatment $out.= ''."\n"; - if (! empty($file_list)) - { - $out='
'; - } - else - { - // TODO Add link to regenerate doc ? - //$out.= '
'.img_picto('', 'refresh').'
'."\n"; - } + } + else + { + // TODO Add link to regenerate doc ? + //$out.= '
'.img_picto('', 'refresh').'
'."\n"; + } - return $out; - } + return $out; + } - /** - * Show list of documents in $filearray (may be they are all in same directory but may not) - * This also sync database if $upload_dir is defined. - * - * @param array $filearray Array of files loaded by dol_dir_list('files') function before calling this. - * @param Object $object Object on which document is linked to. - * @param string $modulepart Value for modulepart used by download or viewimage wrapper. - * @param string $param Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd) - * @param int $forcedownload Force to open dialog box "Save As" when clicking on file. - * @param string $relativepath Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT. - * @param int $permonobject Permission on object (so permission to delete or crop document) - * @param int $useinecm Change output for use in ecm module - * @param string $textifempty Text to show if filearray is empty ('NoFileFound' if not defined) - * @param int $maxlength Maximum length of file name shown. - * @param string $title Title before list - * @param string $url Full url to use for click links ('' = autodetect) + /** + * Show list of documents in $filearray (may be they are all in same directory but may not) + * This also sync database if $upload_dir is defined. + * + * @param array $filearray Array of files loaded by dol_dir_list('files') function before calling this. + * @param Object $object Object on which document is linked to. + * @param string $modulepart Value for modulepart used by download or viewimage wrapper. + * @param string $param Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd) + * @param int $forcedownload Force to open dialog box "Save As" when clicking on file. + * @param string $relativepath Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT. + * @param int $permonobject Permission on object (so permission to delete or crop document) + * @param int $useinecm Change output for use in ecm module + * @param string $textifempty Text to show if filearray is empty ('NoFileFound' if not defined) + * @param int $maxlength Maximum length of file name shown. + * @param string $title Title before list + * @param string $url Full url to use for click links ('' = autodetect) * @param int $showrelpart 0=Show only filename (default), 1=Show first level 1 dir * @param int $permtoeditline Permission to edit document line (You must provide a value, -1 is deprecated and must not be used any more) - * @param string $upload_dir Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this if you want to complete file data with database indexes. - * @param string $sortfield Sort field ('name', 'size', 'position', ...) - * @param string $sortorder Sort order ('ASC' or 'DESC') - * @param int $disablemove 1=Disable move button, 0=Position move is possible. - * @param int $addfilterfields Add line with filters - * @return int <0 if KO, nb of files shown if OK - */ + * @param string $upload_dir Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this if you want to complete file data with database indexes. + * @param string $sortfield Sort field ('name', 'size', 'position', ...) + * @param string $sortorder Sort order ('ASC' or 'DESC') + * @param int $disablemove 1=Disable move button, 0=Position move is possible. + * @param int $addfilterfields Add line with filters + * @return int <0 if KO, nb of files shown if OK + */ function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0) { global $user, $conf, $langs, $hookmanager; @@ -937,21 +937,21 @@ class FormFile // Define relative path used to store the file if (empty($relativepath)) { - $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/'; - if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath - if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.'; + $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/'; + if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath + if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.'; } // For backward compatiblity, we detect file is stored into an old path if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $file['level1name'] == 'photos') { - $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/'; + $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/'; } // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; if ($upload_dir) { - $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); - $relativedir = preg_replace('/^[\\/]/','',$relativedir); + $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); + $relativedir = preg_replace('/^[\\/]/','',$relativedir); } $hookmanager->initHooks(array('formfile')); @@ -981,17 +981,17 @@ class FormFile if ($permtoeditline < 0) // Old behaviour for backward compatibility. New feature should call method with value 0 or 1 { - $permtoeditline=0; - if (in_array($modulepart, array('product','produit','service'))) - { - if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1; - if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1; - } + $permtoeditline=0; + if (in_array($modulepart, array('product','produit','service'))) + { + if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1; + if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1; + } } if (empty($conf->global->MAIN_UPLOAD_DOC)) { - $permtoeditline=0; - $permonobject=0; + $permtoeditline=0; + $permonobject=0; } // Show list of existing files @@ -1001,10 +1001,10 @@ class FormFile print ''."\n"; if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline) { - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; } print '
'; @@ -1038,11 +1038,11 @@ class FormFile /*var_dump($sortfield); var_dump($sortorder);*/ - if ($sortfield && $sortorder) - { - $filearray=dol_sort_array($filearray, $sortfield, $sortorder); - } - //var_dump($filearray); + if ($sortfield && $sortorder) + { + $filearray=dol_sort_array($filearray, $sortfield, $sortorder); + } + //var_dump($filearray); } $nboffiles=count($filearray); @@ -1059,9 +1059,9 @@ class FormFile $editline=0; $nboflines++; - print ''."\n"; - // Do we have entry into database ? - print ''."\n"; + print ''."\n"; + // Do we have entry into database ? + print ''."\n"; print ''; print ''; @@ -1081,15 +1081,15 @@ class FormFile //print dol_trunc($file['name'],$maxlength,'middle'); if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile'))) { - print ''; - print ''; - print ''; - $editline=1; + print ''; + print ''; + print ''; + $editline=1; } else { - print $file['name']; - print ''; + print $file['name']; + print ''; } print "\n"; @@ -1105,13 +1105,13 @@ class FormFile print ''; if (image_format_supported($file['name']) > 0) { - $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original - if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension - //print $file['path'].'/'.$minifile.'
'; + $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original + if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension + //print $file['path'].'/'.$minifile.'
'; - $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity)); - if (empty($urlforhref)) $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); - print ''; + $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity)); + if (empty($urlforhref)) $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])); + print ''; print ''; print ''; } @@ -1120,77 +1120,77 @@ class FormFile } if (! $editline) { - // Delete or view link - // ($param must start with &) - print ''; - if ($useinecm) - { - print ''.img_view('default', 0, 'class="paddingrightonly"').''; - } - else - { - $newmodulepart=$modulepart; - if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; + // Delete or view link + // ($param must start with &) + print ''; + if ($useinecm) + { + print ''.img_view('default', 0, 'class="paddingrightonly"').''; + } + else + { + $newmodulepart=$modulepart; + if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; - $disablecrop=1; - if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0; + $disablecrop=1; + if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0; - if (! $disablecrop && image_format_supported($file['name']) > 0) - { - if ($permtoeditline) - { - // Link to resize - print ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).''; - } - } + if (! $disablecrop && image_format_supported($file['name']) > 0) + { + if ($permtoeditline) + { + // Link to resize + print ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).''; + } + } - if ($permtoeditline) - { - print ''.img_edit('default',0,'class="paddingrightonly"').''; - } - } - if ($permonobject) - { - /* + if ($permtoeditline) + { + print ''.img_edit('default',0,'class="paddingrightonly"').''; + } + } + if ($permonobject) + { + /* if ($file['level1name'] <> $object->id) $filepath=$file['level1name'].'/'.$file['name']; else $filepath=$file['name']; */ - $useajax=1; - if (! empty($conf->dol_use_jmobile)) $useajax=0; - if (empty($conf->use_javascript_ajax)) $useajax=0; - if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0; + $useajax=1; + if (! empty($conf->dol_use_jmobile)) $useajax=0; + if (empty($conf->use_javascript_ajax)) $useajax=0; + if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0; - print ''.img_delete().''; - } - print ""; + print ''.img_delete().''; + } + print ""; - if (empty($disablemove)) - { - if ($nboffiles > 1 && empty($conf->browser->phone)) { - print ''; - if ($i > 0) { - print 'id.'">'.img_up('default',0,'imgupforline').''; - } - if ($i < $nboffiles-1) { - print 'id.'">'.img_down('default',0,'imgdownforline').''; - } - print ''; - } - else { - print 'browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>'; - print ''; - } + if (empty($disablemove)) + { + if ($nboffiles > 1 && empty($conf->browser->phone)) { + print ''; + if ($i > 0) { + print 'id.'">'.img_up('default',0,'imgupforline').''; + } + if ($i < $nboffiles-1) { + print 'id.'">'.img_down('default',0,'imgdownforline').''; + } + print ''; + } + else { + print 'browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>'; + print ''; + } } } else { - print ''; - print ''; - print ''; - print ''; - if (empty($disablemove)) print ''; + print ''; + print ''; + print ''; + print ''; + if (empty($disablemove)) print ''; } print "\n"; @@ -1199,8 +1199,8 @@ class FormFile } if ($nboffiles == 0) { - $colspan=(empty($useinecm)?'5':'5'); - if (empty($disablemove)) $colspan++; + $colspan=(empty($useinecm)?'5':'5'); + if (empty($disablemove)) $colspan++; print ''; if (empty($textifempty)) print $langs->trans("NoFileFound"); else print $textifempty; @@ -1211,14 +1211,14 @@ class FormFile if (! $editline && $nboflines > 1) { if (! empty($conf->use_javascript_ajax) && $permtoeditline) { - $table_element_line = 'ecm_files'; - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + $table_element_line = 'ecm_files'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } } if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline) { - print ''; + print ''; } return $nboffiles; @@ -1226,459 +1226,459 @@ class FormFile } - /** - * Show list of documents in a directory - * - * @param string $upload_dir Directory that was scanned - * @param array $filearray Array of files loaded by dol_dir_list function before calling this function - * @param string $modulepart Value for modulepart used by download wrapper - * @param string $param Parameters on sort links - * @param int $forcedownload Force to open dialog box "Save As" when clicking on file - * @param string $relativepath Relative path of docs (autodefined if not provided) - * @param int $permtodelete Permission to delete - * @param int $useinecm Change output for use in ecm module - * @param int $textifempty Text to show if filearray is empty - * @param int $maxlength Maximum length of file name shown - * @param string $url Full url to use for click links ('' = autodetect) - * @param int $addfilterfields Add line with filters - * @return int <0 if KO, nb of files shown if OK - */ - function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0) - { - global $user, $conf, $langs, $form; - global $bc; - global $sortfield, $sortorder; + /** + * Show list of documents in a directory + * + * @param string $upload_dir Directory that was scanned + * @param array $filearray Array of files loaded by dol_dir_list function before calling this function + * @param string $modulepart Value for modulepart used by download wrapper + * @param string $param Parameters on sort links + * @param int $forcedownload Force to open dialog box "Save As" when clicking on file + * @param string $relativepath Relative path of docs (autodefined if not provided) + * @param int $permtodelete Permission to delete + * @param int $useinecm Change output for use in ecm module + * @param int $textifempty Text to show if filearray is empty + * @param int $maxlength Maximum length of file name shown + * @param string $url Full url to use for click links ('' = autodetect) + * @param int $addfilterfields Add line with filters + * @return int <0 if KO, nb of files shown if OK + */ + function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0) + { + global $user, $conf, $langs, $form; + global $bc; + global $sortfield, $sortorder; global $search_doc_ref; - dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart); + dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart); - // Show list of documents - if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles")); - if (empty($url)) $url=$_SERVER["PHP_SELF"]; + // Show list of documents + if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles")); + if (empty($url)) $url=$_SERVER["PHP_SELF"]; - if (! empty($addfilterfields)) - { - print '
'; - print ''; - } + if (! empty($addfilterfields)) + { + print ''; + print ''; + } print '
'; - print ''."\n"; + print '
'."\n"; - if (! empty($addfilterfields)) - { - print ''; - print ''; - print ''; - print ''; - print ''; + if (! empty($addfilterfields)) + { + print ''; + print ''; + print ''; + print ''; + print ''; // Action column print ''; - print "\n"; - } + print "\n"; + } - print ''; - $sortref="fullname"; - if ($modulepart == 'invoice_supplier') $sortref='level1name'; - print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre('','',''); - print ''."\n"; + print ''; + $sortref="fullname"; + if ($modulepart == 'invoice_supplier') $sortref='level1name'; + print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre('','',''); + print ''."\n"; - // To show ref or specific information according to view to show (defined by $module) - if ($modulepart == 'company') - { - include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $object_instance=new Societe($this->db); - } - else if ($modulepart == 'invoice') - { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $object_instance=new Facture($this->db); - } - else if ($modulepart == 'invoice_supplier') - { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - $object_instance=new FactureFournisseur($this->db); - } - else if ($modulepart == 'propal') - { - include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $object_instance=new Propal($this->db); - } - else if ($modulepart == 'supplier_proposal') - { - include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; - $object_instance=new SupplierProposal($this->db); - } - else if ($modulepart == 'order') - { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $object_instance=new Commande($this->db); - } - else if ($modulepart == 'order_supplier') - { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; - $object_instance=new CommandeFournisseur($this->db); - } - else if ($modulepart == 'contract') - { - include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - $object_instance=new Contrat($this->db); - } - else if ($modulepart == 'product') - { - include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $object_instance=new Product($this->db); - } - else if ($modulepart == 'tax') - { - include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; - $object_instance=new ChargeSociales($this->db); - } - else if ($modulepart == 'project') - { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - $object_instance=new Project($this->db); - } - else if ($modulepart == 'fichinter') - { - include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; - $object_instance=new Fichinter($this->db); - } - else if ($modulepart == 'user') - { - include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - $object_instance=new User($this->db); - } - else if ($modulepart == 'expensereport') - { - include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $object_instance=new ExpenseReport($this->db); - } + // To show ref or specific information according to view to show (defined by $module) + if ($modulepart == 'company') + { + include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $object_instance=new Societe($this->db); + } + else if ($modulepart == 'invoice') + { + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $object_instance=new Facture($this->db); + } + else if ($modulepart == 'invoice_supplier') + { + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + $object_instance=new FactureFournisseur($this->db); + } + else if ($modulepart == 'propal') + { + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $object_instance=new Propal($this->db); + } + else if ($modulepart == 'supplier_proposal') + { + include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; + $object_instance=new SupplierProposal($this->db); + } + else if ($modulepart == 'order') + { + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + $object_instance=new Commande($this->db); + } + else if ($modulepart == 'order_supplier') + { + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; + $object_instance=new CommandeFournisseur($this->db); + } + else if ($modulepart == 'contract') + { + include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + $object_instance=new Contrat($this->db); + } + else if ($modulepart == 'product') + { + include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $object_instance=new Product($this->db); + } + else if ($modulepart == 'tax') + { + include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; + $object_instance=new ChargeSociales($this->db); + } + else if ($modulepart == 'project') + { + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + $object_instance=new Project($this->db); + } + else if ($modulepart == 'fichinter') + { + include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; + $object_instance=new Fichinter($this->db); + } + else if ($modulepart == 'user') + { + include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + $object_instance=new User($this->db); + } + else if ($modulepart == 'expensereport') + { + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $object_instance=new ExpenseReport($this->db); + } - $var=true; - foreach($filearray as $key => $file) - { - if (!is_dir($file['name']) - && $file['name'] != '.' - && $file['name'] != '..' - && $file['name'] != 'CVS' - && ! preg_match('/\.meta$/i',$file['name'])) - { - // Define relative path used to store the file - $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']); + $var=true; + foreach($filearray as $key => $file) + { + if (!is_dir($file['name']) + && $file['name'] != '.' + && $file['name'] != '..' + && $file['name'] != 'CVS' + && ! preg_match('/\.meta$/i',$file['name'])) + { + // Define relative path used to store the file + $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']); - //var_dump($file); - $id=0; $ref=''; $label=''; + //var_dump($file); + $id=0; $ref=''; $label=''; - // To show ref or specific information according to view to show (defined by $module) - if ($modulepart == 'company') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'invoice') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } } // $ref may be also id with old supplier invoices - if ($modulepart == 'propal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + // To show ref or specific information according to view to show (defined by $module) + if ($modulepart == 'company') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'invoice') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } } // $ref may be also id with old supplier invoices + if ($modulepart == 'propal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'order') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'order_supplier') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'contract') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'product') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'project') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} - if ($modulepart == 'fichinter') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} - if ($modulepart == 'user') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} - if ($modulepart == 'expensereport') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'order') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'order_supplier') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'contract') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'product') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'project') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'fichinter') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'user') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'expensereport') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} - if (! $id && ! $ref) continue; - $found=0; - if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) - { - $found=1; - } - else - { - //print 'Fetch '.$id." - ".$ref.'
'; + if (! $id && ! $ref) continue; + $found=0; + if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) + { + $found=1; + } + else + { + //print 'Fetch '.$id." - ".$ref.'
'; - if ($id) { - $result = $object_instance->fetch($id); - } else { - //fetchOneLike looks for objects with wildcards in its reference. - //It is useful for those masks who get underscores instead of their actual symbols - //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned - //that's why we look only look fetchOneLike when fetch returns 0 - if (!$result = $object_instance->fetch('', $ref)) { - $result = $object_instance->fetchOneLike($ref); - } - } + if ($id) { + $result = $object_instance->fetch($id); + } else { + //fetchOneLike looks for objects with wildcards in its reference. + //It is useful for those masks who get underscores instead of their actual symbols + //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned + //that's why we look only look fetchOneLike when fetch returns 0 + if (!$result = $object_instance->fetch('', $ref)) { + $result = $object_instance->fetchOneLike($ref); + } + } if ($result > 0) { // Save object into a cache $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance; } - if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); } - } + if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); } + } - if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files + if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files - print ''."\n"; - print ''; - print ''; + print ''; + print ''; - // File - print '\n"; - print ''; - print ''; - print '\n"; - } - } + print "\n"; + print ''; + print ''; + print '\n"; + } + } - if (count($filearray) == 0) - { - print ''; - } - print "
'; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
'; - if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document'); - else print $langs->trans("ObjectDeleted",($id?$id:$ref)); + print ''."\n"; + print '
'; + if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document'); + else print $langs->trans("ObjectDeleted",($id?$id:$ref)); - //$modulesubdir=dol_sanitizeFileName($ref); - $modulesubdir=dirname($relativefile); + //$modulesubdir=dol_sanitizeFileName($ref); + $modulesubdir=dirname($relativefile); - //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $filedir=$file['path']; - //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - //print $formfile->getDocumentsLink($modulepart, $filename, $filedir); + //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $filedir=$file['path']; + //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + //print $formfile->getDocumentsLink($modulepart, $filename, $filedir); - print ''; - //print "XX".$file['name']; //$file['name'] must be utf8 - print ''; - print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' '; - print dol_trunc($file['name'],$maxlength,'middle'); - print ''; + // File + print ''; + //print "XX".$file['name']; //$file['name'] must be utf8 + print ''; + print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' '; + print dol_trunc($file['name'],$maxlength,'middle'); + print ''; - print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$'); + print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$'); - print "'.dol_print_size($file['size'],1,1).''.dol_print_date($file['date'],"dayhour").''; - //if (! empty($useinecm)) print ''; - //print img_view().'   '; - //if ($permtodelete) print ''.img_delete().''; - //else print ' '; - print "
'.dol_print_size($file['size'],1,1).''.dol_print_date($file['date'],"dayhour").''; + //if (! empty($useinecm)) print ''; + //print img_view().'   '; + //if ($permtodelete) print ''.img_delete().''; + //else print ' '; + print "
'; - if (empty($textifempty)) print $langs->trans("NoFileFound"); - else print $textifempty; - print '
"; - print '
'; + if (count($filearray) == 0) + { + print ''; + if (empty($textifempty)) print $langs->trans("NoFileFound"); + else print $textifempty; + print ''; + } + print ""; + print '
'; - if (! empty($addfilterfields)) print ''; - // Fin de zone - } + if (! empty($addfilterfields)) print ''; + // Fin de zone + } - /** - * Show form to upload a new file with jquery fileupload. - * This form use the fileupload.php file. - * - * @param Object $object Object to use - * @return void - */ - private function _formAjaxFileUpload($object) - { - global $langs; + /** + * Show form to upload a new file with jquery fileupload. + * This form use the fileupload.php file. + * + * @param Object $object Object to use + * @return void + */ + private function _formAjaxFileUpload($object) + { + global $langs; - // PHP post_max_size - $post_max_size = ini_get('post_max_size'); - $mul_post_max_size = substr($post_max_size, -1); - $mul_post_max_size = ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1))); - $post_max_size = $mul_post_max_size * (int) $post_max_size; - // PHP upload_max_filesize - $upload_max_filesize = ini_get('upload_max_filesize'); - $mul_upload_max_filesize = substr($upload_max_filesize, -1); - $mul_upload_max_filesize = ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1))); - $upload_max_filesize = $mul_upload_max_filesize * (int) $upload_max_filesize; - // Max file size - $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize); + // PHP post_max_size + $post_max_size = ini_get('post_max_size'); + $mul_post_max_size = substr($post_max_size, -1); + $mul_post_max_size = ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1))); + $post_max_size = $mul_post_max_size * (int) $post_max_size; + // PHP upload_max_filesize + $upload_max_filesize = ini_get('upload_max_filesize'); + $mul_upload_max_filesize = substr($upload_max_filesize, -1); + $mul_upload_max_filesize = ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1))); + $upload_max_filesize = $mul_upload_max_filesize * (int) $upload_max_filesize; + // Max file size + $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize); - // Include main - include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php'; + // Include main + include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php'; - // Include template - include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php'; + // Include template + include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php'; - } + } - /** - * Show array with linked files - * - * @param Object $object Object - * @param int $permtodelete Deletion is allowed - * @param string $action Action - * @param string $selected ??? - * @param string $param More param to add into URL - * @return int Number of links - */ - public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='') - { - global $user, $conf, $langs, $user; - global $bc; - global $sortfield, $sortorder; + /** + * Show array with linked files + * + * @param Object $object Object + * @param int $permtodelete Deletion is allowed + * @param string $action Action + * @param string $selected ??? + * @param string $param More param to add into URL + * @return int Number of links + */ + public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='') + { + global $user, $conf, $langs, $user; + global $bc; + global $sortfield, $sortorder; - $langs->load("link"); + $langs->load("link"); - require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; - $link = new Link($this->db); - $links = array(); - if ($sortfield == "name") { - $sortfield = "label"; - } elseif ($sortfield == "date") { - $sortfield = "datea"; - } else { - $sortfield = null; - } - $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder); - $param .= (isset($object->id)?'&id=' . $object->id : ''); + require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; + $link = new Link($this->db); + $links = array(); + if ($sortfield == "name") { + $sortfield = "label"; + } elseif ($sortfield == "date") { + $sortfield = "datea"; + } else { + $sortfield = null; + } + $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder); + $param .= (isset($object->id)?'&id=' . $object->id : ''); - // Show list of associated links - print load_fiche_titre($langs->trans("LinkedFiles")); + // Show list of associated links + print load_fiche_titre($langs->trans("LinkedFiles")); - print '
'; + print ''; - print ''; - print ''; - print_liste_field_titre( - $langs->trans("Links"), - $_SERVER['PHP_SELF'], - "name", - "", - $param, - 'align="left"', - $sortfield, - $sortorder - ); - print_liste_field_titre( - "", - "", - "", - "", - "", - 'align="right"' - ); - print_liste_field_titre( - $langs->trans("Date"), - $_SERVER['PHP_SELF'], - "date", - "", - $param, - 'align="center"', - $sortfield, - $sortorder - ); - print_liste_field_titre( - '', - $_SERVER['PHP_SELF'], - "", - "", - $param, - 'align="center"' - ); - print_liste_field_titre('','',''); - print ''; - $nboflinks = count($links); - if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; + print '
'; + print ''; + print_liste_field_titre( + $langs->trans("Links"), + $_SERVER['PHP_SELF'], + "name", + "", + $param, + 'align="left"', + $sortfield, + $sortorder + ); + print_liste_field_titre( + "", + "", + "", + "", + "", + 'align="right"' + ); + print_liste_field_titre( + $langs->trans("Date"), + $_SERVER['PHP_SELF'], + "date", + "", + $param, + 'align="center"', + $sortfield, + $sortorder + ); + print_liste_field_titre( + '', + $_SERVER['PHP_SELF'], + "", + "", + $param, + 'align="center"' + ); + print_liste_field_titre('','',''); + print ''; + $nboflinks = count($links); + if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - $var = true; - foreach ($links as $link) - { - $var =! $var; - print ''; - //edit mode - if ($action == 'update' && $selected === $link->id) - { - print ''; - print ''; - print ''; - print ''; - print ''; - } - else + $var = true; + foreach ($links as $link) + { + $var =! $var; + print ''; + //edit mode + if ($action == 'update' && $selected === $link->id) { - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - } - print "\n"; - } - if ($nboflinks == 0) - { - print ''; - } - print "
'; - print ''; - print ''; - print ''; - print $langs->trans('Link') . ': '; - print ''; - print $langs->trans('Label') . ': '; - print '' . dol_print_date(dol_now(), "dayhour", "tzuser") . ''; - print ''; - print ''; - print '
'; - print img_picto('', 'object_globe').' '; - print ''; - print $link->label; - print ''; - print '' . dol_print_date($link->datea, "dayhour", "tzuser") . ''; - print '' . img_edit() . ''; // id= is included into $param - if ($permtodelete) { - print '   ' . img_delete() . ''; // id= is included into $param - } else { - print ' '; - } - print '
'; - print $langs->trans("NoLinkFound"); - print '
"; + print ''; + print ''; + print ''; + print ''; + print $langs->trans('Link') . ': '; + print ''; + print ''; + print $langs->trans('Label') . ': '; + print ''; + print '' . dol_print_date(dol_now(), "dayhour", "tzuser") . ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + else + { + print ''; + print img_picto('', 'object_globe').' '; + print ''; + print $link->label; + print ''; + print ''."\n"; + print ''; + print '' . dol_print_date($link->datea, "dayhour", "tzuser") . ''; + print ''; + print ''; + print '' . img_edit() . ''; // id= is included into $param + if ($permtodelete) { + print '   ' . img_delete() . ''; // id= is included into $param + } else { + print ' '; + } + print ''; + } + print "\n"; + } + if ($nboflinks == 0) + { + print ''; + print $langs->trans("NoLinkFound"); + print ''; + } + print ""; - print '
'; + print ''; - return $nboflinks; - } + return $nboflinks; + } - /** - * Show detail icon with link for preview - * - * @param array $file File - * @param string $modulepart propal, facture, facture_fourn, ... - * @param string $relativepath Relative path of docs - * @param string $ruleforpicto Rule for picto: 0=Preview picto, 1=Use picto of mime type of file) - * @param string $param More param on http links - * @return string $out Output string with HTML - */ - public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='') - { - global $langs, $conf; + /** + * Show detail icon with link for preview + * + * @param array $file File + * @param string $modulepart propal, facture, facture_fourn, ... + * @param string $relativepath Relative path of docs + * @param string $ruleforpicto Rule for picto: 0=Preview picto, 1=Use picto of mime type of file) + * @param string $param More param on http links + * @return string $out Output string with HTML + */ + public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='') + { + global $langs, $conf; - $out=''; - if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax)) - { - $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview. - if (count($urladvancedpreview)) - { - $out.= ''; - //$out.= ''; - if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); - else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); - $out.= ''; - } - } - return $out; - } + $out=''; + if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax)) + { + $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview. + if (count($urladvancedpreview)) + { + $out.= ''; + //$out.= ''; + if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); + else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); + $out.= ''; + } + } + return $out; + } } diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index cc09b8bb521..a9ebafc4769 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -282,578 +282,578 @@ class FormMail extends Form $outputlangs->load('other'); } - // Get message template for $this->param["models"] into c_email_templates + // Get message template for $this->param["models"] into c_email_templates $arraydefaultmessage=array(); if ($this->param['models'] != 'none') { $model_id=0; - if (array_key_exists('models_id',$this->param)) - { - $model_id=$this->param["models_id"]; - } - $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1)); // we set -1 if model_id empty - } - //var_dump($this->param["models"]); - //var_dump($model_id); - //var_dump($arraydefaultmessage); - - - // Define list of attached files - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - - if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1')) - { - $this->clear_attached_files(); - if (! empty($arraydefaultmessage['joinfiles']) && is_array($this->param['fileinit'])) - { - foreach($this->param['fileinit'] as $file) - { - $this->add_attached_files($file, basename($file), dol_mimetype($file)); - } - } - } - - if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); - if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); - if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); - - - $out.= "\n".'
'."\n"; - if ($this->withform == 1) - { - $out.= '
'."\n"; - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; - } - if (! empty($this->withfrom)) - { - if (! empty($this->withfromreadonly)) - { - $out.= ''; - $out.= ''; - } - } - foreach ($this->param as $key=>$value) - { - $out.= ''."\n"; - } - - $modelmail_array=array(); - if ($this->param['models'] != 'none') - { - $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); - if ($result < 0) - { - setEventMessages($this->error, $this->errors, 'errors'); - } - foreach($this->lines_model as $line) - { - $langs->trans("members"); - if (preg_match('/\((.*)\)/', $line->label, $reg)) - { - $modelmail_array[$line->id]=$langs->trans($reg[1]); // langs->trans when label is __(xxx)__ - } - else - { - $modelmail_array[$line->id]=$line->label; - } - if ($line->lang) $modelmail_array[$line->id].=' ('.$line->lang.')'; - if ($line->private) $modelmail_array[$line->id].=' - '.$langs->trans("Private"); - //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' '; - } - } - - // Zone to select email template - if (count($modelmail_array)>0) - { - // If list of template is filled - $out.= '
'."\n"; - $out.= ''.$langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); - $out.= '   '; - $out.= ''; - $out.= '   '; - $out.= '
'; - } - elseif (! empty($this->param['models']) && in_array($this->param['models'], array( - 'propal_send','order_send','facture_send', - 'shipping_send','fichinter_send','supplier_proposal_send','order_supplier_send', - 'invoice_supplier_send','thirdparty','contract','user','all' - ))) - { - // If list of template is empty - $out.= '
'."\n"; - $out.= $langs->trans('SelectMailModel').': '; // Do not put 'disabled' on 'option' tag, it is already on 'select' and it makes chrome crazy. - if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); - $out.= '   '; - $out.= ''; - $out.= '   '; - $out.= '
'; - } - - - - $out.= ''."\n"; - - // Substitution array - if (! empty($this->withsubstit)) // Unset of set ->withsubstit=0 to disable this. - { - $out.= '\n"; - //$out.=''; - } - - // From - if (! empty($this->withfrom)) - { - if (! empty($this->withfromreadonly)) - { - $out.= '\n"; - } - else - { - $out.= '\n"; - } - } - - // To - if (! empty($this->withto) || is_array($this->withto)) - { - $out.= '\n"; - } - - // withoptiononeemailperrecipient - if (! empty($this->withoptiononeemailperrecipient)) - { - $out.= ''; - } - - // CC - if (! empty($this->withtocc) || is_array($this->withtocc)) - { - $out.= '\n"; - } - - // CCC - if (! empty($this->withtoccc) || is_array($this->withtoccc)) - { - $out.= '\n"; - } - - // Replyto - if (! empty($this->withreplyto)) - { - if ($this->withreplytoreadonly) - { - $out.= ''; - $out.= ''; - $out.= "\n"; - } - } - - // Errorsto - if (! empty($this->witherrorsto)) - { - //if (! $this->errorstomail) $this->errorstomail=$this->frommail; - $errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail); - if ($this->witherrorstoreadonly) - { - $out.= ''; - $out.= '\n"; - } - else - { - $out.= '\n"; - } - } - - // Ask delivery receipt - if (! empty($this->withdeliveryreceipt)) - { - $out.= '\n"; - } - - // Topic - if (! empty($this->withtopic)) - { - $defaulttopic=GETPOST('subject','none'); - if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') + if (array_key_exists('models_id',$this->param)) { - if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) $defaulttopic=$arraydefaultmessage['topic']; - elseif (! is_numeric($this->withtopic)) $defaulttopic=$this->withtopic; + $model_id=$this->param["models_id"]; + } + $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1)); // we set -1 if model_id empty + } + //var_dump($this->param["models"]); + //var_dump($model_id); + //var_dump($arraydefaultmessage); + + + // Define list of attached files + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + + if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1')) + { + $this->clear_attached_files(); + if (! empty($arraydefaultmessage['joinfiles']) && is_array($this->param['fileinit'])) + { + foreach($this->param['fileinit'] as $file) + { + $this->add_attached_files($file, basename($file), dol_mimetype($file)); + } + } + } + + if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); + if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); + if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); + + + $out.= "\n".'
'."\n"; + if ($this->withform == 1) + { + $out.= ''."\n"; + $out.= ''; + $out.= ''; + $out.= ''; + $out.= ''; + } + if (! empty($this->withfrom)) + { + if (! empty($this->withfromreadonly)) + { + $out.= ''; + $out.= ''; + } + } + foreach ($this->param as $key=>$value) + { + $out.= ''."\n"; + } + + $modelmail_array=array(); + if ($this->param['models'] != 'none') + { + $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); + if ($result < 0) + { + setEventMessages($this->error, $this->errors, 'errors'); + } + foreach($this->lines_model as $line) + { + $langs->trans("members"); + if (preg_match('/\((.*)\)/', $line->label, $reg)) + { + $modelmail_array[$line->id]=$langs->trans($reg[1]); // langs->trans when label is __(xxx)__ + } + else + { + $modelmail_array[$line->id]=$line->label; + } + if ($line->lang) $modelmail_array[$line->id].=' ('.$line->lang.')'; + if ($line->private) $modelmail_array[$line->id].=' - '.$langs->trans("Private"); + //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' '; + } + } + + // Zone to select email template + if (count($modelmail_array)>0) + { + // If list of template is filled + $out.= '
'."\n"; + $out.= ''.$langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); + $out.= '   '; + $out.= ''; + $out.= '   '; + $out.= '
'; + } + elseif (! empty($this->param['models']) && in_array($this->param['models'], array( + 'propal_send','order_send','facture_send', + 'shipping_send','fichinter_send','supplier_proposal_send','order_supplier_send', + 'invoice_supplier_send','thirdparty','contract','user','all' + ))) + { + // If list of template is empty + $out.= '
'."\n"; + $out.= $langs->trans('SelectMailModel').': '; // Do not put 'disabled' on 'option' tag, it is already on 'select' and it makes chrome crazy. + if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); + $out.= '   '; + $out.= ''; + $out.= '   '; + $out.= '
'; + } + + + + $out.= '
'; - //$out.='
'; - $help=""; - foreach($this->substit as $key => $val) - { - $help.=$key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'
'; - } - if (is_numeric($this->withsubstit)) $out.= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $help, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage - else $out.= $form->textwithpicto($langs->trans('AvailableVariables'), $help, 1, 'help', '', 0, 2, 'substittooltip'); // New usage - $out.= "
'.$langs->trans("MailFrom").''; - - if (! ($this->fromtype === 'user' && $this->fromid > 0) - && ! ($this->fromtype === 'company') - && ! preg_match('/user_aliases/', $this->fromtype) - && ! preg_match('/global_aliases/', $this->fromtype) - && ! preg_match('/senderprofile/', $this->fromtype)) - { - // Use this->fromname and this->frommail or error if not defined - $out.= $this->fromname; - if ($this->frommail) - { - $out.= ' <'.$this->frommail.'>'; - } - else - { - if ($this->fromtype) - { - $langs->load('errors'); - $out.= ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'> '; - } - } - } else { - $liste = array(); - - // Add user email - if (empty($user->email)) - { - $langs->load('errors'); - $liste['user'] = $user->getFullName($langs) . ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'>'; - } - else - { - $liste['user'] = $user->getFullName($langs) .' <'.$user->email.'>'; - } - - // Add also company main email - $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; - - // Add also email aliases if there is some - $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); - - // Add also email aliases from the c_email_senderprofile table - $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1 ORDER BY position'; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i=0; - while($i < $num) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; - } - $i++; - } - } - else dol_print_error($this->db); - - foreach($listaliases as $typealias => $listalias) - { - $posalias=0; - $listaliasarray=explode(',', $listalias); - foreach ($listaliasarray as $listaliasval) - { - $posalias++; - $listaliasval=trim($listaliasval); - if ($listaliasval) - { - $listaliasval=preg_replace('//', '>', $listaliasval); - if (! preg_match('/</', $listaliasval)) $listaliasval='<'.$listaliasval.'>'; - $liste[$typealias.'_'.$posalias]=$listaliasval; - } - } - } - $out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', '', 0, '', $disablebademails); - //$out.= ajax_combobox('fromtype'); - } - - $out.= "
'.$langs->trans("MailFrom").""; - $out.= $langs->trans("Name").':'; - $out.= '    '; - $out.= $langs->trans("EMail").':<>'; - $out.= "
'; - if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); - else $out.= $langs->trans("MailTo"); - $out.= ''; - if ($this->withtoreadonly) - { - if (! empty($this->toname) && ! empty($this->tomail)) - { - $out.= ''; - $out.= ''; - if ($this->totype == 'thirdparty') - { - $soc=new Societe($this->db); - $soc->fetch($this->toid); - $out.= $soc->getNomUrl(1); - } - else if ($this->totype == 'contact') - { - $contact=new Contact($this->db); - $contact->fetch($this->toid); - $out.= $contact->getNomUrl(1); - } - else - { - $out.= $this->toname; - } - $out.= ' <'.$this->tomail.'>'; - if ($this->withtofree) - { - $out.= '
'.$langs->trans("and").' withto) :"").'" />'; - } - } - else - { - // Note withto may be a text like 'AllRecipientSelected' - $out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:""; - } - } - else - { - if (! empty($this->withtofree)) - { - $out.= 'withto) :"").'" />'; - } - if (! empty($this->withto) && is_array($this->withto)) - { - if (! empty($this->withtofree)) $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; - // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time - $tmparray = $this->withto; - foreach($tmparray as $key => $val) - { - $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); - } - $withtoselected=GETPOST("receiver",'none'); // Array of selected value - if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend') - { - $withtoselected = array_keys($tmparray); - } - $out.= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, ""); - } - } - $out.= "
'; - $out.= $langs->trans("GroupEmails"); - $out.= ''; - $out.=' withoptiononeemailperrecipient > 0?' checked="checked"':'').'> '; - $out.= $langs->trans("OneEmailPerRecipient").' - '; - $out.= $langs->trans("WarningIfYouCheckOneRecipientPerEmail"); - $out.= '
'; - $out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); - $out.= ''; - if ($this->withtoccreadonly) - { - $out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:""; - } - else - { - $out.= 'withtocc) : (isset($_POST["sendtocc"])?$_POST["sendtocc"]:"") ).'" />'; - if (! empty($this->withtocc) && is_array($this->withtocc)) - { - $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; - // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time - $tmparray = $this->withtocc; - foreach($tmparray as $key => $val) - { - $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); - } - $withtoccselected=GETPOST("receivercc"); // Array of selected value - $out.= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500',null, ""); - } - } - $out.= "
'; - $out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); - $out.= ''; - if (! empty($this->withtocccreadonly)) - { - $out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:""; - } - else - { - $out.= 'withtoccc) : (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:"") ).'" />'; - if (! empty($this->withtoccc) && is_array($this->withtoccc)) - { - $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; - // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time - $tmparray = $this->withtoccc; - foreach($tmparray as $key => $val) - { - $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); - } - $withtocccselected=GETPOST("receiverccc"); // Array of selected value - $out.= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null,null, "90%"); - } - } - - $showinfobcc=''; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO; - if ($showinfobcc) $out.=' + '.$showinfobcc; - $out.= "
".$langs->trans("MailReply")."".$this->replytoname.($this->replytomail?(" <".$this->replytomail.">"):""); - $out.= "
'.$langs->trans("MailErrorsTo").''; - $out.= $errorstomail; - $out.= "
'.$langs->trans("MailErrorsTo").''; - $out.= ''; - $out.= "
'.$langs->trans("DeliveryReceipt").''; - - if (! empty($this->withdeliveryreceiptreadonly)) - { - $out.= yn($this->withdeliveryreceipt); - } - else - { - $defaultvaluefordeliveryreceipt=0; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $defaultvaluefordeliveryreceipt=1; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt=1; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt=1; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt=1; - $out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:$defaultvaluefordeliveryreceipt), 1); - } - - $out.= "
'."\n"; + + // Substitution array + if (! empty($this->withsubstit)) // Unset of set ->withsubstit=0 to disable this. + { + $out.= '\n"; + //$out.=''; + } + + // From + if (! empty($this->withfrom)) + { + if (! empty($this->withfromreadonly)) + { + $out.= '\n"; + } + else + { + $out.= '\n"; + } + } + + // To + if (! empty($this->withto) || is_array($this->withto)) + { + $out.= '\n"; + } + + // withoptiononeemailperrecipient + if (! empty($this->withoptiononeemailperrecipient)) + { + $out.= ''; + } + + // CC + if (! empty($this->withtocc) || is_array($this->withtocc)) + { + $out.= '\n"; + } + + // CCC + if (! empty($this->withtoccc) || is_array($this->withtoccc)) + { + $out.= '\n"; + } - $out.= ''; - $out.= ''; - $out.= '\n"; - } + // Replyto + if (! empty($this->withreplyto)) + { + if ($this->withreplytoreadonly) + { + $out.= ''; + $out.= ''; + $out.= "\n"; + } + } - // Attached files - if (! empty($this->withfile)) - { - $out.= ''; - $out.= ''; + // Errorsto + if (! empty($this->witherrorsto)) + { + //if (! $this->errorstomail) $this->errorstomail=$this->frommail; + $errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail); + if ($this->witherrorstoreadonly) + { + $out.= ''; + $out.= '\n"; + } + else + { + $out.= '\n"; + } + } - $out.= '\n"; + } + + // Topic + if (! empty($this->withtopic)) + { + $defaulttopic=GETPOST('subject','none'); + if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') + { + if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) $defaulttopic=$arraydefaultmessage['topic']; + elseif (! is_numeric($this->withtopic)) $defaulttopic=$this->withtopic; + } + + $defaulttopic=make_substitutions($defaulttopic,$this->substit); + + $out.= ''; + $out.= ''; + $out.= '\n"; + } + + // Attached files + if (! empty($this->withfile)) + { + $out.= ''; + $out.= ''; + + $out.= '\n"; - } + $out.= "\n"; + } - // Message - if (! empty($this->withbody)) - { - $defaultmessage=GETPOST('message','none'); + // Message + if (! empty($this->withbody)) + { + $defaultmessage=GETPOST('message','none'); if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') { if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['content']) $defaultmessage=$arraydefaultmessage['content']; - elseif (! is_numeric($this->withbody)) $defaultmessage=$this->withbody; + elseif (! is_numeric($this->withbody)) $defaultmessage=$this->withbody; } - // Complete substitution array - $paymenturl=''; - if (! empty($conf->global->PAYMENT_ADD_PAYMENT_URL) // Option to enable to add online link into __PERSONALIZED__ - || (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_ADD_PAYMENT_URL)) - ) - { - if (empty($this->substit['__REF__'])) - { - //$paymenturl='LinkToPayOnlineNotAvailableInThisContext'; - $paymenturl=''; - } - else - { - // Set the online payment message and url link into __PERSONALIZED__ key - require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - $langs->load('paypal'); - $typeforonlinepayment='free'; - if ($this->param["models"]=='order_send') $typeforonlinepayment='order'; // TODO use detection on something else than template - if ($this->param["models"]=='facture_send') $typeforonlinepayment='invoice'; // TODO use detection on something else than template - if ($this->param["models"]=='member_send') $typeforonlinepayment='member'; // TODO use detection on something else than template - $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']); - //$paymenturl=str_replace('\n',"\n",$langs->transnoentitiesnoconv("PredefinedMailContentLink",$url)); - $paymenturl=$url; - } - } - $this->substit['__PERSONALIZED__']=$paymenturl; // deprecated - $this->substit['__ONLINE_PAYMENT_URL__']=$paymenturl; + // Complete substitution array + $paymenturl=''; + if (! empty($conf->global->PAYMENT_ADD_PAYMENT_URL) // Option to enable to add online link into __PERSONALIZED__ + || (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_ADD_PAYMENT_URL)) + ) + { + if (empty($this->substit['__REF__'])) + { + //$paymenturl='LinkToPayOnlineNotAvailableInThisContext'; + $paymenturl=''; + } + else + { + // Set the online payment message and url link into __PERSONALIZED__ key + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + $langs->load('paypal'); + $typeforonlinepayment='free'; + if ($this->param["models"]=='order_send') $typeforonlinepayment='order'; // TODO use detection on something else than template + if ($this->param["models"]=='facture_send') $typeforonlinepayment='invoice'; // TODO use detection on something else than template + if ($this->param["models"]=='member_send') $typeforonlinepayment='member'; // TODO use detection on something else than template + $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']); + //$paymenturl=str_replace('\n',"\n",$langs->transnoentitiesnoconv("PredefinedMailContentLink",$url)); + $paymenturl=$url; + } + } + $this->substit['__PERSONALIZED__']=$paymenturl; // deprecated + $this->substit['__ONLINE_PAYMENT_URL__']=$paymenturl; - //Add lines substitution key from each line - $lines = ''; - $defaultlines = $arraydefaultmessage['content_lines']; - if (isset($defaultlines)) - { - foreach ($this->substit_lines as $substit_line) - { - $lines .= make_substitutions($defaultlines,$substit_line)."\n"; - } - } - $this->substit['__LINES__']=$lines; + //Add lines substitution key from each line + $lines = ''; + $defaultlines = $arraydefaultmessage['content_lines']; + if (isset($defaultlines)) + { + foreach ($this->substit_lines as $substit_line) + { + $lines .= make_substitutions($defaultlines,$substit_line)."\n"; + } + } + $this->substit['__LINES__']=$lines; $defaultmessage=str_replace('\n',"\n",$defaultmessage); diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index 9fc1739334c..99b799d5d6e 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -59,7 +59,7 @@ abstract class DoliDB implements Database public $lastqueryerror; /** @var string Last error message */ public $lasterror; - /** @var int Last error number */ + /** @var string Last error number. For example: 'DB_ERROR_RECORD_ALREADY_EXISTS', '12345', ... */ public $lasterrno; /** @var bool Status */ @@ -238,16 +238,16 @@ abstract class DoliDB implements Database else $return.=', '; $return.=preg_replace('/[^0-9a-z_\.]/i','',$val); - + $tmpsortorder = trim($orders[$i]); - + // Only ASC and DESC values are valid SQL if (strtoupper($tmpsortorder) === 'ASC') { $return .= ' ASC'; } elseif (strtoupper($tmpsortorder) === 'DESC') { $return .= ' DESC'; } - + $i++; } return $return; diff --git a/htdocs/core/filemanagerdol/connectors/php/config.php b/htdocs/core/filemanagerdol/connectors/php/config.php index de8b4d7e8bf..8df350ef150 100644 --- a/htdocs/core/filemanagerdol/connectors/php/config.php +++ b/htdocs/core/filemanagerdol/connectors/php/config.php @@ -48,7 +48,7 @@ $Config['Enabled'] = true ; $extEntity=(empty($entity) ? 1 : $entity); // For multicompany with external access $Config['UserFilesPath'] = DOL_URL_ROOT.'/viewimage.php?modulepart=medias'.(empty($website)?'':'_'.$website).'&entity='.$extEntity.'&file=' ; -$Config['UserFilesAbsolutePathRelative'] = (empty($website) ? ((!empty($entity) ? '/' . $entity : '') . '/medias/') : ('/websites/'.$website)); +$Config['UserFilesAbsolutePathRelative'] = (empty($website) ? ((!empty($entity) ? '/' . $entity : '') . '/medias/') : ('/website/'.$website)); // Fill the following value it you prefer to specify the absolute path for the diff --git a/htdocs/core/get_menudiv.php b/htdocs/core/get_menudiv.php index 4ffee2caad9..451747b4a6e 100644 --- a/htdocs/core/get_menudiv.php +++ b/htdocs/core/get_menudiv.php @@ -34,7 +34,6 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML',1); if (! defined('DISABLE_JQUERY_TABLEDND')) define('DISABLE_JQUERY_TABLEDND',1); -if (! defined('DISABLE_JQUERY_TIPTIP')) define('DISABLE_JQUERY_TIPTIP',1); if (! defined('DISABLE_JQUERY_JNOTIFY')) define('DISABLE_JQUERY_JNOTIFY',1); if (! defined('DISABLE_JQUERY_FLOT')) define('DISABLE_JQUERY_FLOT',1); if (! defined('DISABLE_JQUERY_JEDITABLE')) define('DISABLE_JQUERY_JEDITABLE',1); diff --git a/htdocs/core/js/lib_head.js.php b/htdocs/core/js/lib_head.js.php index a68995e5eeb..ddfe5d257e1 100644 --- a/htdocs/core/js/lib_head.js.php +++ b/htdocs/core/js/lib_head.js.php @@ -152,237 +152,27 @@ jQuery(function($){ /** - * Set select2 translations (if module was loaded). + * Set array used for select2 translations */ -(function ($) { - "use strict"; - if (typeof $.fn.select2 != "undefined") { - /* console.log($.fn.select2); - console.log("ok"); */ - - $.fn.select2.locales['xx'] = { - formatMatches: function (matches) { return matches + " trans("Select2ResultFoundUseArrows")); ?>"; }, - formatNoMatches: function () { return "trans("Select2NotFound")); ?>"; }, - formatInputTooShort: function (input, min) { var n = min - input.length; - if (n > 1) return "trans("Select2Enter")); ?> " + n + " trans("Select2MoreCharacters")); ?>"; - else return "trans("Select2Enter")); ?> " + n + " trans("Select2MoreCharacter")); ?>" - }, - formatLoadMore: function (pageNumber) { return "trans("Select2LoadingMoreResults")); ?>"; }, - formatSearching: function () { return "trans("Select2SearchInProgress")); ?>"; } - }; - - $.extend($.fn.select2.defaults, $.fn.select2.locales['xx']); - - } -})(jQuery); +var select2arrayoflanguage = { + matches: function (matches) { return matches + " transnoentitiesnoconv("Select2ResultFoundUseArrows")); ?>"; }, + noResults: function () { return "transnoentitiesnoconv("Select2NotFound")); ?>"; }, + inputTooShort: function (input) { + var n = input.minimum; + console.log(input); + console.log(input.minimum); + if (n > 1) return "transnoentitiesnoconv("Select2Enter")); ?> " + n + " transnoentitiesnoconv("Select2MoreCharacters")); ?>"; + else return "transnoentitiesnoconv("Select2Enter")); ?> " + n + " transnoentitiesnoconv("Select2MoreCharacter")); ?>" + }, + loadMore: function (pageNumber) { return "transnoentitiesnoconv("Select2LoadingMoreResults")); ?>"; }, + searching: function () { return "transnoentitiesnoconv("Select2SearchInProgress")); ?>"; } +}; -/* - * ================================================================= - * Purpose: - * Pour la saisie des dates par calendrier Input: base "/theme/eldy" dateFieldID - * "dateo" Nom du champ format "dd/MM/yyyy" Format issu de Dolibarr de - * SimpleDateFormat a utiliser pour retour - * ================================================================== +/** + * For calendar input */ - /* -function showDP(base,dateFieldID,format,codelang) -{ - // check to see if another box is already showing - var alreadybox=getObjectFromID("DPCancel"); - if (alreadybox) closeDPBox(); // This erase value of showDP.datefieldID - - // alert("showDP "+codelang); - showDP.datefieldID=dateFieldID; // Must be after the close - - var dateField=getObjectFromID(dateFieldID); - - // get positioning - var thetop=getTop(dateField)+dateField.offsetHeight; - -// var xxx=getObjectFromID('bottompage'); -// alert(xxx.style.pixelTop); -// alert(document.body.clientHeight); -// alert(document.body.style.offsetTop); -// alert(thetop); -// alert(window.innerHeight); - if (thetop+160 > window.innerHeight) - thetop=thetop-160-20; - var theleft=getLeft(dateField); - if (theleft+140 > window.innerWidth) - theleft= theleft-140+dateField.offsetWidth-15; - - showDP.box=document.createElement("div"); - showDP.box.className="bodyline"; - showDP.box.style.display="block"; - showDP.box.style.zIndex="1000"; - showDP.box.style.position="absolute"; - showDP.box.style.top=thetop + "px"; - showDP.box.style.left=theleft + "px"; - - if (dateField.value) // Si il y avait valeur initiale dans champ - { - selDate=getDateFromFormat(dateField.value,format); - if (selDate) - { - // Success to parse value in field according to format - year=selDate.getFullYear(); - month=selDate.getMonth()+1; - day=selDate.getDate(); - datetime=selDate.getTime(); - ymd=formatDate(selDate,'yyyyMMdd'); - } - else - { - // Failed to parse value in field according to format - selDate=new Date(); - year=selDate.getFullYear(); - month=selDate.getUTCMonth()+1; - day=selDate.getDate(); - datetime=selDate.getTime(); - ymd=formatDate(selDate,'yyyyMMdd'); - } - } - else - { - selDate=new Date(); - year=selDate.getFullYear(); - month=selDate.getUTCMonth()+1; - day=selDate.getDate(); - datetime=selDate.getTime(); - ymd=formatDate(selDate,'yyyyMMdd'); - } - loadMonth(base,month,year,ymd,codelang); - hideSelectBoxes(); - document.body.appendChild(showDP.box); -} - -function resetDP(base,dateFieldID,format,codelang) -{ - var dateField=getObjectFromID(dateFieldID); - dateField.value = formatDate(new Date(), format); - dpChangeDay(dateFieldID,format); - - var alreadybox=getObjectFromID("DPCancel"); - if (alreadybox) showDP(base,dateFieldID,format,codelang); -} - -function loadMonth(base,month,year,ymd,codelang) -{ - // showDP.box.innerHTML="Loading..."; - // alert(codelang); - var theURL=base+"datepicker.php?cm=shw&lang="+codelang; - theURL+="&m="+encodeURIComponent(month); - theURL+="&y="+encodeURIComponent(year); - if (selDate) - { - theURL+="&sd="+ymd; - } - - var req=null; - - req=loadXMLDoc(theURL,null,false); - if (req.responseText == '') alert('Failed to get URL '.theURL); - // alert(theURL+' - '+req.responseText); // L'url doit avoir la meme racine - // que la pages et elements sinon pb de securite. - showDP.box.innerHTML=req.responseText; -} - -function closeDPBox() -{ - document.body.removeChild(showDP.box); - displaySelectBoxes(); - showDP.box=null; - showDP.datefieldID=null; -} - -function dpClickDay(year,month,day,format) -{ - var thefield=getObjectFromID(showDP.datefieldID); - var thefieldday=getObjectFromID(showDP.datefieldID+"day"); - var thefieldmonth=getObjectFromID(showDP.datefieldID+"month"); - var thefieldyear=getObjectFromID(showDP.datefieldID+"year"); - - var dt = new Date(year, month-1, day); - - thefield.value=formatDate(dt,format); - if(thefield.onchange) thefield.onchange.call(thefield); - - thefieldday.value=day; - if(thefieldday.onchange) thefieldday.onchange.call(thefieldday); - thefieldmonth.value=month; - if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth); - thefieldyear.value=year; - if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear); - - closeDPBox(); -} - -function dpHighlightDay(year,month,day,months){ - var displayinfo=getObjectFromID("dpExp"); - displayinfo.innerHTML=months[month-1]+" "+day+", "+year; -} - -// This Function returns the top position of an object -function getTop(theitem){ - var offsetTrail = theitem; - var offsetTop = 0; - while (offsetTrail) { - offsetTop += offsetTrail.offsetTop; - offsetTrail = offsetTrail.offsetParent; - } - if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") - offsetTop += document.body.TopMargin; - return offsetTop; -} - -// This Function returns the left position of an object -function getLeft(theitem){ - var offsetTrail = theitem; - var offsetLeft = 0; - while (offsetTrail) { - offsetLeft += offsetTrail.offsetLeft; - offsetTrail = offsetTrail.offsetParent; - } - if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") - offsetLeft += document.body.leftMargin; - return offsetLeft; -} - -// To hide/show select Boxes with IE6 (and only IE6 because IE6 has a bug and -// not put popup completely on the front) -// Used only bu popup calendar -function hideSelectBoxes() { - var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10); - if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE 6") > -1) - { - for(var i = 0; i < document.all.length; i++) - { - if(document.all[i].tagName) - if(document.all[i].tagName == "SELECT") - document.all[i].style.visibility="hidden"; - } - } -} -// To hide/show select Boxes with IE6 (and only IE6 because IE6 has a bug and -// not put popup completely on the front) -// Used only bu popup calendar -function displaySelectBoxes() { - var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10); - if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE 6") > -1) - { - for(var i = 0; i < document.all.length; i++) - { - if(document.all[i].tagName) - if(document.all[i].tagName == "SELECT") - document.all[i].style.visibility="visible"; - } - } -} - -*/ - // Returns an object given an id function getObjectFromID(id){ @@ -426,69 +216,6 @@ function dpChangeDay(dateFieldID,format) } } - - - - -// Create XMLHttpRequest object and load url -// Used by calendar or other ajax processes -// Return req built or false if error -function loadXMLDoc(url,readyStateFunction,async) -{ - // req must be defined by caller with - // var req = false; - - // branch for native XMLHttpRequest object (Mozilla, Safari...) - if (window.XMLHttpRequest) - { - req = new XMLHttpRequest(); - -// if (req.overrideMimeType) { -// req.overrideMimeType('text/xml'); -// } - } - // branch for IE/Windows ActiveX version - else if (window.ActiveXObject) - { - try - { - req = new ActiveXObject("Msxml2.XMLHTTP"); - } - catch (e) - { - try { - req = new ActiveXObject("Microsoft.XMLHTTP"); - } catch (e) {} - } - } - - // If XMLHttpRequestObject req is ok, call URL - if (! req) - { - alert('Cannot create XMLHTTP instance'); - return false; - } - - if (readyStateFunction) req.onreadystatechange = readyStateFunction; - // Exemple of function for readyStateFuncyion: - // function () - // { - // if ( (req.readyState == 4) && (req.status == 200) ) { - // if (req.responseText == 1) { newStatus = 'AAA'; } - // if (req.responseText == 0) { newStatus = 'BBB'; } - // if (currentStatus != newStatus) { - // if (newStatus == "AAA") { obj.innerHTML = 'AAA'; } - // else { obj.innerHTML = 'BBB'; } - // currentStatus = newStatus; - // } - // } - // } - req.open("GET", url, async); - req.send(null); - return req; -} - - /* * ================================================================= * Function: @@ -552,9 +279,9 @@ function formatDate(date,format) /* * ================================================================= - * Function: - * getDateFromFormat(date_string, format_string) Purpose: This function takes a - * date string and a format string. It parses the date string with format and it + * Function: getDateFromFormat(date_string, format_string) + * Purpose: This function takes a date string and a format string. + * It parses the date string with format and it * returns the date as a javascript Date() object. If date does not match * format, it returns 0. The format string can use the following tags: * Field | Tags @@ -650,9 +377,8 @@ function getDateFromFormat(val,format) /* * ================================================================= - * Function: - * stringIsInteger(string) - * Purpose: Return true if string is an integer + * Function: stringIsInteger(string) + * Purpose: Return true if string is an integer * ================================================================== */ function stringIsInteger(str) @@ -670,9 +396,8 @@ function stringIsInteger(str) /* * ================================================================= - * Function: - * getIntegerInString(string,pos,minlength,maxlength) - * Purpose: Return part of string from position i that is integer + * Function: getIntegerInString(string,pos,minlength,maxlength) + * Purpose: Return part of string from position i that is integer * ================================================================== */ function getIntegerInString(str,i,minlength,maxlength) @@ -689,10 +414,9 @@ function getIntegerInString(str,i,minlength,maxlength) /* * ================================================================= - * Purpose: - * Clean string to have it url encoded - * Input: s - * Author: Laurent Destailleur + * Purpose: Clean string to have it url encoded + * Input: s + * Author: Laurent Destailleur * Licence: GPL * ================================================================== */ @@ -706,8 +430,7 @@ function urlencode(s) { /* * ================================================================= - * Purpose: - * Applique un delai avant execution. Used for autocompletion of companies. + * Purpose: Applique un delai avant execution. Used for autocompletion of companies. * Input: funct, delay * Author: Regis Houssin * Licence: GPL @@ -955,6 +678,7 @@ function confirmConstantAction(action, url, code, input, box, entity, yesButton, } } + /* * ================================================================= * This is to allow to transform all select box into ajax autocomplete box @@ -1070,6 +794,7 @@ function confirmConstantAction(action, url, code, input, box, entity, yesButton, })( jQuery ); + /** * Function to output a dialog bog for copy/paste * @@ -1303,7 +1028,7 @@ function price2numjs(amount) { // If rounding higher than max shown if (rounding > main_max_dec_shown) rounding = main_max_dec_shown; if (thousand != ',' && thousand != '.') amount = amount.replace(',', '.'); - amount = amount.replace(' ', ''); // To avoid spaces + amount = amount.replace(' ', ''); // To avoid spaces amount = amount.replace(thousand, ''); // Replace of thousand before replace of dec to avoid pb if thousand is . amount = amount.replace(dec, '.'); //console.log("amount before="+amount+" rouding="+rounding) diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index 500bbbb3ffb..0ee1ea98a5b 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -387,6 +387,7 @@ function ajax_autoselect($htmlname, $addlink='') * @param int $forcefocus Force focus on field * @param string $widthTypeOfAutocomplete 'resolve' or 'off' * @return string Return html string to convert a select field into a combo, or '' if feature has been disabled for some reason. + * @see selectArrayAjax of html.form.class */ function ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve') { @@ -404,10 +405,23 @@ function ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $ $msg="\n".''; - } - print ' '.$langs->trans("AddThirdParty").''; + } + print ' '.$langs->trans("AddThirdParty").''; } print ''; @@ -1504,14 +1504,14 @@ if ($action=='create') $form->select_date($datelivraison?$datelivraison:-1,'liv_',$usehourmin,$usehourmin,'',"set"); print ''; - // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) - { - $langs->load("bank"); - print ''; - } + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) + { + $langs->load("bank"); + print ''; + } // Project if (! empty($conf->projet->enabled)) @@ -1524,13 +1524,13 @@ if ($action=='create') print ''; } - // Incoterms + // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; print ''; - print ''; } @@ -1539,8 +1539,8 @@ if ($action=='create') { print ''; print ''; - print ''; } @@ -1595,19 +1595,19 @@ if ($action=='create') } // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) - { + { print $object->showOptionals($extrafields,'edit'); - } + } // Bouton "Create Draft" - print "
'; + //$out.='
'; + $help=""; + foreach($this->substit as $key => $val) + { + $help.=$key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'
'; + } + if (is_numeric($this->withsubstit)) $out.= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $help, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage + else $out.= $form->textwithpicto($langs->trans('AvailableVariables'), $help, 1, 'help', '', 0, 2, 'substittooltip'); // New usage + $out.= "
'.$langs->trans("MailFrom").''; + + if (! ($this->fromtype === 'user' && $this->fromid > 0) + && ! ($this->fromtype === 'company') + && ! preg_match('/user_aliases/', $this->fromtype) + && ! preg_match('/global_aliases/', $this->fromtype) + && ! preg_match('/senderprofile/', $this->fromtype)) + { + // Use this->fromname and this->frommail or error if not defined + $out.= $this->fromname; + if ($this->frommail) + { + $out.= ' <'.$this->frommail.'>'; + } + else + { + if ($this->fromtype) + { + $langs->load('errors'); + $out.= ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'> '; + } + } + } else { + $liste = array(); + + // Add user email + if (empty($user->email)) + { + $langs->load('errors'); + $liste['user'] = $user->getFullName($langs) . ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'>'; + } + else + { + $liste['user'] = $user->getFullName($langs) .' <'.$user->email.'>'; + } + + // Add also company main email + $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + + // Add also email aliases if there is some + $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + + // Add also email aliases from the c_email_senderprofile table + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1 ORDER BY position'; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i=0; + while($i < $num) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; + } + $i++; + } + } + else dol_print_error($this->db); + + foreach($listaliases as $typealias => $listalias) + { + $posalias=0; + $listaliasarray=explode(',', $listalias); + foreach ($listaliasarray as $listaliasval) + { + $posalias++; + $listaliasval=trim($listaliasval); + if ($listaliasval) + { + $listaliasval=preg_replace('//', '>', $listaliasval); + if (! preg_match('/</', $listaliasval)) $listaliasval='<'.$listaliasval.'>'; + $liste[$typealias.'_'.$posalias]=$listaliasval; + } + } + } + $out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', '', 0, '', $disablebademails); + //$out.= ajax_combobox('fromtype'); + } + + $out.= "
'.$langs->trans("MailFrom").""; + $out.= $langs->trans("Name").':'; + $out.= '    '; + $out.= $langs->trans("EMail").':<>'; + $out.= "
'; + if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); + else $out.= $langs->trans("MailTo"); + $out.= ''; + if ($this->withtoreadonly) + { + if (! empty($this->toname) && ! empty($this->tomail)) + { + $out.= ''; + $out.= ''; + if ($this->totype == 'thirdparty') + { + $soc=new Societe($this->db); + $soc->fetch($this->toid); + $out.= $soc->getNomUrl(1); + } + else if ($this->totype == 'contact') + { + $contact=new Contact($this->db); + $contact->fetch($this->toid); + $out.= $contact->getNomUrl(1); + } + else + { + $out.= $this->toname; + } + $out.= ' <'.$this->tomail.'>'; + if ($this->withtofree) + { + $out.= '
'.$langs->trans("and").' withto) :"").'" />'; + } + } + else + { + // Note withto may be a text like 'AllRecipientSelected' + $out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:""; + } + } + else + { + if (! empty($this->withtofree)) + { + $out.= 'withto) :"").'" />'; + } + if (! empty($this->withto) && is_array($this->withto)) + { + if (! empty($this->withtofree)) $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; + // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time + $tmparray = $this->withto; + foreach($tmparray as $key => $val) + { + $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); + } + $withtoselected=GETPOST("receiver",'none'); // Array of selected value + if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend') + { + $withtoselected = array_keys($tmparray); + } + $out.= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, ""); + } + } + $out.= "
'; + $out.= $langs->trans("GroupEmails"); + $out.= ''; + $out.=' withoptiononeemailperrecipient > 0?' checked="checked"':'').'> '; + $out.= $langs->trans("OneEmailPerRecipient").' - '; + $out.= $langs->trans("WarningIfYouCheckOneRecipientPerEmail"); + $out.= '
'; + $out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); + $out.= ''; + if ($this->withtoccreadonly) + { + $out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:""; + } + else + { + $out.= 'withtocc) : (isset($_POST["sendtocc"])?$_POST["sendtocc"]:"") ).'" />'; + if (! empty($this->withtocc) && is_array($this->withtocc)) + { + $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; + // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time + $tmparray = $this->withtocc; + foreach($tmparray as $key => $val) + { + $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); + } + $withtoccselected=GETPOST("receivercc"); // Array of selected value + $out.= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500',null, ""); + } + } + $out.= "
'; + $out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); + $out.= ''; + if (! empty($this->withtocccreadonly)) + { + $out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:""; + } + else + { + $out.= 'withtoccc) : (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:"") ).'" />'; + if (! empty($this->withtoccc) && is_array($this->withtoccc)) + { + $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; + // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time + $tmparray = $this->withtoccc; + foreach($tmparray as $key => $val) + { + $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); + } + $withtocccselected=GETPOST("receiverccc"); // Array of selected value + $out.= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null,null, "90%"); + } } - $defaulttopic=make_substitutions($defaulttopic,$this->substit); + $showinfobcc=''; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO; + if ($showinfobcc) $out.=' + '.$showinfobcc; + $out.= "
'.$langs->trans("MailTopic").''; - if ($this->withtopicreadonly) - { - $out.= $defaulttopic; - $out.= ''; - } - else - { - $out.= ''; - } - $out.= "
".$langs->trans("MailReply")."".$this->replytoname.($this->replytomail?(" <".$this->replytomail.">"):""); + $out.= "
'.$langs->trans("MailFile").'
'.$langs->trans("MailErrorsTo").''; + $out.= $errorstomail; + $out.= "
'.$langs->trans("MailErrorsTo").''; + $out.= ''; + $out.= "
'; - if (! empty($this->withmaindocfile)) - { - if ($this->withmaindocfile == 1) - { - $out.=''; - } - if ($this->withmaindocfile == -1) - { - $out.=''; - } - $out.=' '.$langs->trans("JoinMainDoc").'.
'; - } + // Ask delivery receipt + if (! empty($this->withdeliveryreceipt)) + { + $out.= '
'.$langs->trans("DeliveryReceipt").''; - if (is_numeric($this->withfile)) - { + if (! empty($this->withdeliveryreceiptreadonly)) + { + $out.= yn($this->withdeliveryreceipt); + } + else + { + $defaultvaluefordeliveryreceipt=0; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $defaultvaluefordeliveryreceipt=1; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt=1; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt=1; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt=1; + $out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:$defaultvaluefordeliveryreceipt), 1); + } + + $out.= "
'.$langs->trans("MailTopic").''; + if ($this->withtopicreadonly) + { + $out.= $defaulttopic; + $out.= ''; + } + else + { + $out.= ''; + } + $out.= "
'.$langs->trans("MailFile").''; + if (! empty($this->withmaindocfile)) + { + if ($this->withmaindocfile == 1) + { + $out.=''; + } + if ($this->withmaindocfile == -1) + { + $out.=''; + } + $out.=' '.$langs->trans("JoinMainDoc").'.
'; + } + + if (is_numeric($this->withfile)) + { // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript - $out.= ''."\n"; - $out.= ''."\n"; - if (count($listofpaths)) - { - foreach($listofpaths as $key => $val) - { - $out.= '
'; - $out.= img_mime($listofnames[$key]).' '.$listofnames[$key]; - if (! $this->withfilereadonly) - { - $out.= ' '; - //$out.= ' '.img_delete($langs->trans("Delete").''; - } - $out.= '
'; - } - } - else if (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox - { - $out.= $langs->trans("NoAttachedFiles").'
'; - } - if ($this->withfile == 2) // Can add other files - { - if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) $out.= ''; + $out.= ''."\n"; + $out.= ''."\n"; + if (count($listofpaths)) + { + foreach($listofpaths as $key => $val) + { + $out.= '
'; + $out.= img_mime($listofnames[$key]).' '.$listofnames[$key]; + if (! $this->withfilereadonly) + { + $out.= ' '; + //$out.= ' '.img_delete($langs->trans("Delete").''; + } + $out.= '
'; + } + } + else if (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox + { + $out.= $langs->trans("NoAttachedFiles").'
'; + } + if ($this->withfile == 2) // Can add other files + { + if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) $out.= ''; else $out.= ''; - $out.= ' '; - $out.= ''; - } - } - else - { - $out.=$this->withfile; - } + $out.= ' '; + $out.= ''; + } + } + else + { + $out.=$this->withfile; + } - $out.= "
' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
'; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); print '
'.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
\n"; + print "\n"; - dol_fiche_end(); + dol_fiche_end(); print '
'; print ''; @@ -1634,9 +1634,9 @@ elseif (! empty($object->id)) { $result = $object->fetch($id, $ref); - $societe = new Fournisseur($db); - $result=$societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + $societe = new Fournisseur($db); + $result=$societe->fetch($object->socid); + if ($result < 0) dol_print_error($db); $author = new User($db); $author->fetch($object->user_author_id); @@ -1679,7 +1679,7 @@ elseif (! empty($object->id)) // We check if number is temporary number if (preg_match('/^[\(]?PROV/i',$object->ref) || empty($object->ref)) // empty should not happened, but when it occurs, the test save life { - $newref = $object->getNextNumRef($object->thirdparty); + $newref = $object->getNextNumRef($object->thirdparty); } else $newref = $object->ref; @@ -1706,15 +1706,15 @@ elseif (! empty($object->id)) // Confirm approval if ($action == 'approve' || $action == 'approve2') { - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } $formquestion=array(); if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) @@ -1794,34 +1794,34 @@ elseif (! empty($object->id)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->fournisseur->commande->creer) - { - if ($action != 'classify') - $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->fournisseur->commande->creer) + { + if ($action != 'classify') + $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
'; @@ -1941,24 +1941,24 @@ elseif (! empty($object->id)) print ''; } - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) { - print ''; - print ''; - print '
'; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->fournisseur->commande->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ''; - print ''; + print ''; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->fournisseur->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ''; + print ''; } // Delivery date planed @@ -1986,7 +1986,7 @@ elseif (! empty($object->id)) if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour'; print $object->date_livraison ? dol_print_date($object->date_livraison, $usehourmin) : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; @@ -2001,14 +2001,14 @@ elseif (! empty($object->id)) if (!empty($conf->incoterm->enabled)) { print ''; - print '
'; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->fournisseur->commande->creer) print ''.img_edit().''; - else print ' '; - print '
'; - print ''; - print ''; + print '
'; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->fournisseur->commande->creer) print ''.img_edit().''; + else print ' '; + print '
'; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2017,7 +2017,7 @@ elseif (! empty($object->id)) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } // Other attributes @@ -2034,20 +2034,20 @@ elseif (! empty($object->id)) if (!empty($conf->multicurrency->enabled)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Total @@ -2123,7 +2123,7 @@ elseif (! empty($object->id)) include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
'; + print '
'; print ''; // Add free products/services form @@ -2153,7 +2153,7 @@ elseif (! empty($object->id)) } } print '
'; - print '
'; + print '
'; print ''; dol_fiche_end(); @@ -2175,8 +2175,8 @@ elseif (! empty($object->id)) // Validate if ($object->statut == 0 && $num > 0) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate))) + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate))) { $tmpbuttonlabel=$langs->trans('Validate'); if ($user->rights->fournisseur->commande->approuver && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); @@ -2269,24 +2269,24 @@ elseif (! empty($object->id)) // Reopen if (in_array($object->statut, array(2))) { - $buttonshown=0; - if (! $buttonshown && $user->rights->fournisseur->commande->approuver) - { - if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) - || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) - { - print ''.$langs->trans("Disapprove").''; - $buttonshown++; - } - } - if (! $buttonshown && $user->rights->fournisseur->commande->approve2 && ! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) - { - if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) - || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) - { - print ''.$langs->trans("Disapprove").''; - } - } + $buttonshown=0; + if (! $buttonshown && $user->rights->fournisseur->commande->approuver) + { + if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) + || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) + { + print ''.$langs->trans("Disapprove").''; + $buttonshown++; + } + } + if (! $buttonshown && $user->rights->fournisseur->commande->approve2 && ! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) + { + if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) + || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) + { + print ''.$langs->trans("Disapprove").''; + } + } } if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) { @@ -2310,14 +2310,14 @@ elseif (! empty($object->id)) if ($object->statut == 2) { - if ($user->rights->fournisseur->commande->commander) - { - print ''; - } - else - { - print ''; - } + if ($user->rights->fournisseur->commande->commander) + { + print ''; + } + else + { + print ''; + } } // Create bill @@ -2335,17 +2335,17 @@ elseif (! empty($object->id)) // Classify billed manually (need one invoice if module invoice is on, no condition on invoice if not) if ($user->rights->fournisseur->commande->creer && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) // statut 2 means approved { - if (empty($conf->facture->enabled)) - { - print ''.$langs->trans("ClassifyBilled").''; - } - else if (!empty($object->linkedObjectsIds['invoice_supplier'])) - { + if (empty($conf->facture->enabled)) + { + print ''.$langs->trans("ClassifyBilled").''; + } + else if (!empty($object->linkedObjectsIds['invoice_supplier'])) + { if ($user->rights->fournisseur->facture->creer) { - print ''.$langs->trans("ClassifyBilled").''; + print ''.$langs->trans("ClassifyBilled").''; } - } + } } // Create a remote order using WebService only if module is activated @@ -2383,57 +2383,59 @@ elseif (! empty($object->id)) if ($user->rights->fournisseur->commande->commander && $object->statut == 2 && $action == 'makeorder') { - // Set status to ordered (action=commande) - print ''."\n"; - print '
'; - print ''; - print ''; - print load_fiche_titre($langs->trans("ToOrder"),'',''); - print ''; - //print ''; - print ''; + // Set status to ordered (action=commande) + print ''."\n"; + print ''; - print ''; + print ''; + print ''; + print load_fiche_titre($langs->trans("ToOrder"),'',''); + print '
'.$langs->trans("ToOrder").'
'.$langs->trans("OrderDate").''; - $date_com = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - print $form->select_date($date_com,'',1,1,'',"commande",1,1,1); - print '
'.$langs->trans("OrderMode").''; - $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); - print '
'; + //print ''; + print ''; - print ''; - print ''; - print '
'.$langs->trans("ToOrder").'
'.$langs->trans("OrderDate").''; + $date_com = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + print $form->select_date($date_com,'',1,1,'',"commande",1,1,1); + print '
'.$langs->trans("Comment").'
'; - print ''; - print '     '; - print ''; - print '
'; - print '
'; - print "
"; + print ''.$langs->trans("OrderMode").''; + $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); + print ''; + + print ''.$langs->trans("Comment").''; + print ''; + print ''; + print '     '; + print ''; + print ''; + print ''; + + print ''; + print "
"; } if ($action != 'makeorder') { - print '
'; + print '
'; - /* + /* * Documents generes */ - $comfournref = dol_sanitizeFileName($object->ref); - $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; - $relativepath = $comfournref.'/'.$comfournref.'.pdf'; - $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->fournisseur->commande->creer; - $delallowed=$user->rights->fournisseur->commande->supprimer; + $comfournref = dol_sanitizeFileName($object->ref); + $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; + $relativepath = $comfournref.'/'.$comfournref.'.pdf'; + $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; + $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed=$user->rights->fournisseur->commande->lire; + $delallowed=$user->rights->fournisseur->commande->creer; - print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang); - $somethingshown=$formfile->numoffiles; + print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang); + $somethingshown=$formfile->numoffiles; - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order','order_supplier')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order','order_supplier')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; if ($user->rights->fournisseur->commande->receptionner && ($object->statut == 3 || $object->statut == 4)) { @@ -2468,10 +2470,10 @@ elseif (! empty($object->id)) print "
"; } - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object,'order_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown = $formactions->showactions($object,'order_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); print '
'; } diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index 3894cf28cc4..f1bd5738cc8 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -1233,7 +1233,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->fournisseur->commande->lire; - $delallowed=$user->rights->fournisseur->commande->lire; + $delallowed=$user->rights->fournisseur->commande->creer; print $formfile->showdocuments('massfilesarea_supplier_order','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 6241a80aec1..60191f0d2a6 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -133,9 +133,9 @@ if (empty($reshook)) // Link invoice to order if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) { - $object->fetch($id); - $object->fetch_thirdparty(); - $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); + $object->fetch($id); + $object->fetch_thirdparty(); + $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } // Action clone object @@ -147,95 +147,95 @@ if (empty($reshook)) // } // else // { - $result=$object->createFromClone($id); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result); - exit; - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans($object->error), null, 'errors'); - $action=''; - } + $result=$object->createFromClone($id); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result); + exit; + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans($object->error), null, 'errors'); + $action=''; + } // } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) ) { - $idwarehouse=GETPOST('idwarehouse'); + $idwarehouse=GETPOST('idwarehouse'); - $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch($id); + $object->fetch_thirdparty(); - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } - // Check parameters - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - if (! $idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; - } - } + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (! $idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action=''; + } + } - if (! $error) - { - $result = $object->validate($user,'',$idwarehouse); - if ($result < 0) - { - setEventMessages($object->error,$object->errors,'errors'); - }else{ - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + if (! $error) + { + $result = $object->validate($user,'',$idwarehouse); + if ($result < 0) + { + setEventMessages($object->error,$object->errors,'errors'); + }else{ + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - } - } + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + } } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) { - $object->fetch($id); - $object->fetch_thirdparty(); - $result=$object->delete($user); - if ($result > 0) - { - header('Location: list.php'); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $object->fetch_thirdparty(); + $result=$object->delete($user); + if ($result > 0) + { + header('Location: list.php'); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Remove a product line @@ -273,12 +273,12 @@ if (empty($reshook)) elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $result=$object->set_paid($user); - if ($result<0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $result=$object->set_paid($user); + if ($result<0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set supplier ref @@ -291,34 +291,34 @@ if (empty($reshook)) } else { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) - $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $ret = $object->fetch($object->id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) + $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $ret = $object->fetch($object->id); // Reload to get new records + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } } // payments conditions if ($action == 'setconditions' && $user->rights->fournisseur->facture->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); } // payment mode else if ($action == 'setmode' && $user->rights->fournisseur->facture->creer) { - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); } // Multicurrency Code @@ -333,71 +333,71 @@ if (empty($reshook)) // bank account else if ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } // Set label elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $object->label=GETPOST('label'); - $result=$object->update($user); - if ($result < 0) dol_print_error($db); + $object->fetch($id); + $object->label=GETPOST('label'); + $result=$object->update($user); + if ($result < 0) dol_print_error($db); } elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer) { - $newdate=dol_mktime(0,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']); - if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)?0:$conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) - { - if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); - else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); - } + $newdate=dol_mktime(0,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']); + if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)?0:$conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) + { + if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); + else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); + } - $object->fetch($id); + $object->fetch($id); - $object->date=$newdate; - $date_echence_calc=$object->calculate_date_lim_reglement(); - if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) - { - $object->date_echeance = $date_echence_calc; - } - if ($object->date_echeance && $object->date_echeance < $object->date) - { - $object->date_echeance=$object->date; - } + $object->date=$newdate; + $date_echence_calc=$object->calculate_date_lim_reglement(); + if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) + { + $object->date_echeance = $date_echence_calc; + } + if ($object->date_echeance && $object->date_echeance < $object->date) + { + $object->date_echeance=$object->date; + } - $result=$object->update($user); - if ($result < 0) dol_print_error($db,$object->error); + $result=$object->update($user); + if ($result < 0) dol_print_error($db,$object->error); } elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']); - if (! empty($object->date_echeance) && $object->date_echeance < $object->date) - { - $object->date_echeance=$object->date; - setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); - } - $result=$object->update($user); - if ($result < 0) dol_print_error($db,$object->error); + $object->fetch($id); + $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']); + if (! empty($object->date_echeance) && $object->date_echeance < $object->date) + { + $object->date_echeance=$object->date; + setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); + } + $result=$object->update($user); + if ($result < 0) dol_print_error($db,$object->error); } // Delete payment elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) - { - $paiementfourn = new PaiementFourn($db); - $result=$paiementfourn->fetch(GETPOST('paiement_id')); - if ($result > 0) { - $result=$paiementfourn->delete(); // If fetch ok and found - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) + { + $paiementfourn = new PaiementFourn($db); + $result=$paiementfourn->fetch(GETPOST('paiement_id')); + if ($result > 0) { + $result=$paiementfourn->delete(); // If fetch ok and found + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); } - if ($result < 0) { - setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors'); - } - } + if ($result < 0) { + setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors'); + } + } } // Create @@ -460,7 +460,7 @@ if (empty($reshook)) $id = $object->createFromCurrent($user); if ($id <= 0) { - $error++; + $error++; setEventMessages($object->error, $object->errors, 'errors'); } } @@ -555,7 +555,7 @@ if (empty($reshook)) // Defined the new fk_parent_line if ($result > 0 && $line->product_type == 9) { - $fk_parent_line = $result; + $fk_parent_line = $result; } } @@ -746,38 +746,6 @@ if (empty($reshook)) { $error++; } - - if (! $error) - { - // If some invoice's lines already known - for ($i = 1 ; $i < 9 ; $i++) - { - $label = $_POST['label'.$i]; - $amountht = price2num($_POST['amount'.$i]); - $amountttc = price2num($_POST['amountttc'.$i]); - $tauxtva = price2num($_POST['tauxtva'.$i]); - $qty = $_POST['qty'.$i]; - $fk_product = $_POST['fk_product'.$i]; - if ($label) - { - if ($amountht) - { - $price_base='HT'; $amount=$amountht; - } - else - { - $price_base='TTC'; $amount=$amountttc; - } - $atleastoneline=1; - - $product=new Product($db); - $product->fetch($_POST['idprod'.$i]); - - $ret=$object->addline($label, $amount, $tauxtva, $product->localtax1_tx, $product->localtax2_tx, $qty, $fk_product, $remise_percent, '', '', '', 0, $price_base, $_POST['rang'.$i], 1); - if ($ret < 0) $error++; - } - } - } } } } @@ -816,41 +784,49 @@ if (empty($reshook)) $db->begin(); $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $tva_tx = GETPOST('tva_tx'); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); if (GETPOST('price_ht') != '') - { - $up = price2num(GETPOST('price_ht')); - $price_base_type = 'HT'; - } - else - { - $up = price2num(GETPOST('price_ttc')); - $price_base_type = 'TTC'; - } + { + $up = price2num(GETPOST('price_ht')); + $price_base_type = 'HT'; + } + else + { + $up = price2num(GETPOST('price_ttc')); + $price_base_type = 'TTC'; + } - if (GETPOST('productid')) - { - $prod = new Product($db); - $prod->fetch(GETPOST('productid')); - $label = $prod->description; - if (trim($_POST['product_desc']) != trim($label)) $label=$_POST['product_desc']; + if (GETPOST('productid')) + { + $prod = new Product($db); + $prod->fetch(GETPOST('productid')); + $label = $prod->description; + if (trim($_POST['product_desc']) != trim($label)) $label=$_POST['product_desc']; - $type = $prod->type; - } - else - { - $label = $_POST['product_desc']; - $type = $_POST["type"]?$_POST["type"]:0; - } + $type = $prod->type; + } + else + { + $label = $_POST['product_desc']; + $type = $_POST["type"]?$_POST["type"]:0; + } - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $tva_tx)) + $info_bits |= 0x01; + + // Define vat_rate + $tva_tx = str_replace('*', '', $tva_tx); + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - $localtax1_tx= get_localtax($_POST['tauxtva'], 1, $mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($_POST['tauxtva'], 2, $mysoc,$object->thirdparty); $remise_percent=GETPOST('remise_percent'); $pu_ht_devise = GETPOST('multicurrency_subprice'); @@ -865,7 +841,7 @@ if (empty($reshook)) } } - $result=$object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, 0, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise); + $result=$object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise); if ($result >= 0) { unset($_POST['label']); @@ -882,28 +858,28 @@ if (empty($reshook)) unset($_POST['date_endmonth']); unset($_POST['date_endyear']); - $db->commit(); - } - else - { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + $db->commit(); + } + else + { + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) { $db->begin(); - $ret=$object->fetch($id); - if ($ret < 0) - { - dol_print_error($db,$object->error); - exit; - } - $ret=$object->fetch_thirdparty(); + $ret=$object->fetch($id); + if ($ret < 0) + { + dol_print_error($db,$object->error); + exit; + } + $ret=$object->fetch_thirdparty(); - $langs->load('errors'); + $langs->load('errors'); $error=0; // Set if we used free entry or predefined product @@ -930,43 +906,43 @@ if (empty($reshook)) $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } - if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0) - { - setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise==='') // Unit price can be 0 but not '' - { - setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && ! GETPOST('dp_desc')) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error++; - } - if (! GETPOST('qty')) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error++; - } + if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0) + { + setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise==='') // Unit price can be 0 but not '' + { + setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && ! GETPOST('dp_desc')) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); + $error++; + } + if (! GETPOST('qty')) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error++; + } if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') { if ($combinations = GETPOST('combinations', 'array')) { @@ -983,11 +959,11 @@ if (empty($reshook)) } if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { - $productsupplier=new ProductFournisseur($db); + { + $productsupplier=new ProductFournisseur($db); - $idprod=0; - if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + $idprod=0; + if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) if (preg_match('/^idprod_([0-9]+)$/',GETPOST('idprodfournprice'), $reg)) { @@ -997,68 +973,68 @@ if (empty($reshook)) // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price $productsupplier->get_buyprice(0, -1, $idprod, 'none'); // We force qty to -1 to be sure to find if a supplier price exist } - elseif (GETPOST('idprodfournprice') > 0) - { - $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. - //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist - $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); - $res=$productsupplier->fetch($idprod); - } + elseif (GETPOST('idprodfournprice') > 0) + { + $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. + //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); + $res=$productsupplier->fetch($idprod); + } - //Replaces $fk_unit with the product's - if ($idprod > 0) - { - $label = $productsupplier->label; + //Replaces $fk_unit with the product's + if ($idprod > 0) + { + $label = $productsupplier->label; - $desc = $productsupplier->description; - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); + $desc = $productsupplier->description; + if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); - $tva_tx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); - $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); + $tva_tx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); + $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); if (empty($tva_tx)) $tva_npr=0; - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - $type = $productsupplier->type; - $price_base_type = 'HT'; + $type = $productsupplier->type; + $price_base_type = 'HT'; - // TODO Save the product supplier ref into database (like done for supplier propal and order) into field ref_supplier (must rename field ref into ref_supplier first) - $result=$object->addline( - $desc, - $productsupplier->fourn_pu, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $qty, - $idprod, - $remise_percent, - $date_start, - $date_end, - 0, - $tva_npr, - $price_base_type, - $type, - -1, - 0, - $array_options, - $productsupplier->fk_unit - ); - } - if ($idprod == -99 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); - } - } + // TODO Save the product supplier ref into database (like done for supplier propal and order) into field ref_supplier (must rename field ref into ref_supplier first) + $result=$object->addline( + $desc, + $productsupplier->fourn_pu, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $qty, + $idprod, + $remise_percent, + $date_start, + $date_end, + 0, + $tva_npr, + $price_base_type, + $type, + -1, + 0, + $array_options, + $productsupplier->fk_unit + ); + } + if ($idprod == -99 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); + } + } else if (empty($error)) // $price_ht is already set { $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); @@ -1069,11 +1045,11 @@ if (empty($reshook)) $fk_unit= GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + $tva_tx = price2num($tva_tx); // When vat is text input field - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); if ($price_ht !== '') { @@ -1088,135 +1064,161 @@ if (empty($reshook)) $pu_ht_devise = price2num($price_ht_devise, 'MU'); $result=$object->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, $pu_ht_devise); - } + } - //print "xx".$tva_tx; exit; - if (! $error && $result > 0) - { - $db->commit(); + //print "xx".$tva_tx; exit; + if (! $error && $result > 0) + { + $db->commit(); - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } unset($_POST ['prod_entry_mode']); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['pu']); - unset($_POST['price_ht']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['pu']); + unset($_POST['price_ht']); unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['label']); - unset($localtax1_tx); - unset($localtax2_tx); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['label']); + unset($localtax1_tx); + unset($localtax2_tx); unset($_POST['np_marginRate']); unset($_POST['np_markRate']); - unset($_POST['dp_desc']); + unset($_POST['dp_desc']); unset($_POST['idprodfournprice']); - unset($_POST['units']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + } - $action = ''; + $action = ''; } elseif ($action == 'classin' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $result=$object->setProject($projectid); + $object->fetch($id); + $result=$object->setProject($projectid); } // Set invoice to draft status - elseif ($action == 'edit' && $user->rights->fournisseur->facture->creer) + elseif ($action == 'confirm_edit' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); + $object->fetch($id); - $totalpaye = $object->getSommePaiement(); - $resteapayer = $object->total_ttc - $totalpaye; + $totalpaye = $object->getSommePaiement(); + $resteapayer = $object->total_ttc - $totalpaye; - // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees - //$ventilExportCompta = $object->getVentilExportCompta(); + // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees + //$ventilExportCompta = $object->getVentilExportCompta(); // On verifie si aucun paiement n'a ete effectue - if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) + if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) { - $object->set_draft($user); + $idwarehouse = GETPOST('idwarehouse'); - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + $object->fetch_thirdparty(); - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } - $action=''; - } + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (! $idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action=''; + } + } + + $object->set_draft($user, $idwarehouse); + + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + $ret = $object->fetch($id); // Reload to get new records + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + + $action=''; + } } // Set invoice to validated/unpaid status elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer) { - $result = $object->fetch($id); - if ($object->statut == FactureFournisseur::STATUS_CLOSED - || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) - { - $result = $object->set_unpaid($user); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $result = $object->fetch($id); + if ($object->statut == FactureFournisseur::STATUS_CLOSED + || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) + { + $result = $object->set_unpaid($user); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } // Actions when printing a doc from card @@ -1239,14 +1241,14 @@ if (empty($reshook)) { $calculationrule=GETPOST('calculationrule'); - $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch($id); + $object->fetch_thirdparty(); $result=$object->update_price(0, (($calculationrule=='totalofround')?'0':'1'), 0, $object->thirdparty); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } + if ($result <= 0) + { + dol_print_error($db,$result); + exit; + } } if ($action == 'update_extras') { @@ -1371,9 +1373,9 @@ if ($action == 'create') $facturestatic = new FactureFournisseur($db); $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element); - print load_fiche_titre($langs->trans('NewBill')); + print load_fiche_titre($langs->trans('NewBill')); - dol_htmloutput_events(); + dol_htmloutput_events(); $currency_code = $conf->currency; @@ -1385,49 +1387,49 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code; } - if (! empty($origin) && ! empty($originid)) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = $origin; + if (! empty($origin) && ! empty($originid)) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; - if ($element == 'project') - { - $projectid = $originid; - $element = 'projet'; - } - else if (in_array($element,array('order_supplier'))) - { - // For compatibility - if ($element == 'order') { - $element = $subelement = 'commande'; - } - if ($element == 'propal') { - $element = 'comm/propal'; $subelement = 'propal'; - } - if ($element == 'contract') { - $element = $subelement = 'contrat'; - } - if ($element == 'order_supplier') { - $element = 'fourn'; $subelement = 'fournisseur.commande'; - } + if ($element == 'project') + { + $projectid = $originid; + $element = 'projet'; + } + else if (in_array($element,array('order_supplier'))) + { + // For compatibility + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } + if ($element == 'contract') { + $element = $subelement = 'contrat'; + } + if ($element == 'order_supplier') { + $element = 'fourn'; $subelement = 'fournisseur.commande'; + } - require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; - $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur'; - $objectsrc = new $classname($db); - $objectsrc->fetch($originid); - $objectsrc->fetch_thirdparty(); + require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; + $classname = ucfirst($subelement); + if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur'; + $objectsrc = new $classname($db); + $objectsrc->fetch($originid); + $objectsrc->fetch_thirdparty(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); - //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); + $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); - $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); - $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); - $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; + $soc = $objectsrc->thirdparty; + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; if (!empty($conf->multicurrency->enabled)) { @@ -1435,56 +1437,61 @@ if ($action == 'create') if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; } - $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); - $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); - $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); - $datedue=($datetmp==''?-1:$datetmp); - } - } - else - { + $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); + $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); + $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); + $datedue=($datetmp==''?-1:$datetmp); + + // Replicate extrafields + $objectsrc->fetch_optionals($originid); + $object->array_options = $objectsrc->array_options; + + } + } + else + { $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; - $fk_account = $societe->fk_account; - $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); - $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); - $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); - $datedue=($datetmp==''?-1:$datetmp); + $fk_account = $societe->fk_account; + $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); + $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); + $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); + $datedue=($datetmp==''?-1:$datetmp); if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; - } + } - print '
'; - print ''; - print ''; - if ($societe->id > 0) print '' . "\n"; - print ''; - print ''; + print ''; + print ''; + print ''; + if ($societe->id > 0) print '' . "\n"; + print ''; + print ''; if (!empty($currency_tx)) print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - // Ref - print ''; + // Ref + print ''; - // Third party - print ''; - print ''; + print ''; + } + print ' '.$langs->trans("AddThirdParty").''; + } + print ''; - // Ref supplier - print ''; - print ''; + // Ref supplier + print ''; + print ''; - // Type invoice + // Type invoice $facids = $facturestatic->list_replacable_supplier_invoices($societe->id); if ($facids < 0) { dol_print_error($db, $facturestatic); @@ -1640,19 +1647,19 @@ if ($action == 'create') if (empty($origin)) { - if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note - { - if ($societe->id > 0) - { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
'; - $tmp=' + if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note + { + if ($societe->id > 0) + { + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) + { + print '
'; + $tmp=' jQuery(document).ready(function() { if (! jQuery("#radio_creditnote").is(":checked")) { @@ -1666,41 +1673,41 @@ if ($action == 'create') }); }); '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; - print '
'; - print '    0 ? 'checked':'').' /> "; - print '
    0 ? 'checked':'').' /> "; - print '
'; + print '
'; + print '    0 ? 'checked':'').' /> "; + print '
    0 ? 'checked':'').' /> "; + print '
'; - print '
'; - } - } - else - { - print '
'; - $tmp=' '; - $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; - print '
' . "\n"; - } - } + print '
'; + } + } + else + { + print '
'; + $tmp=' '; + $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; + $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
' . "\n"; + } + } } print ''; @@ -1727,18 +1734,18 @@ if ($action == 'create') print ''; } - // Label - print ''; + // Label + print ''; - // Date invoice - print ''; + // Date invoice + print ''; - // Due date - print ''; + // Due date + print ''; // Payment term print ''; - // Bank Account - print ''; + // Bank Account + print ''; // Multicurrency if (! empty($conf->multicurrency->enabled)) { print ''; print ''; - print ''; } @@ -1781,73 +1788,73 @@ if ($action == 'create') { print ''; print ''; - print ''; } // Public note print ''; - print ''; + print ''; // print ''; - print ''; + print ''; - // Private note - print ''; - print ''; - // print ''; - print ''; + // Private note + print ''; + print ''; + // print ''; + print ''; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } - if (is_object($objectsrc)) - { - print "\n"; - print "\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''; - print ''; + if (is_object($objectsrc)) + { + print "\n"; + print "\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''; - $txt=$langs->trans($classname); - if ($classname=='CommandeFournisseur') { - $langs->load('orders'); - $txt=$langs->trans("SupplierOrder"); - } - print ''; - print ''; - print '"; - if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 - { - print '"; - } + $txt=$langs->trans($classname); + if ($classname=='CommandeFournisseur') { + $langs->load('orders'); + $txt=$langs->trans("SupplierOrder"); + } + print ''; + print ''; + print '"; + if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 + { + print '"; + } - if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 - { - print '"; - } - print '"; + if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 + { + print '"; + } + print '"; if (!empty($conf->multicurrency->enabled)) { @@ -1855,168 +1862,211 @@ if ($action == 'create') print '"; print '"; } - } + } - // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Other options + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - // Bouton "Create Draft" - print "
'.$langs->trans('Ref').''.$langs->trans('Draft').'
'.$langs->trans('Ref').''.$langs->trans('Draft').'
'.$langs->trans('Supplier').''; + // Third party + print '
'.$langs->trans('Supplier').''; - if ($societe->id > 0) - { - print $societe->getNomUrl(1); - print ''; - } - else - { - print $form->select_company($societe->id, 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); - // reload page to retrieve supplier informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { - print ''; - } - print ' '.$langs->trans("AddThirdParty").''; - } - print '
'.$langs->trans('RefSupplier').'
'.$langs->trans('RefSupplier').'
'.$langs->trans('Label').'
'.$langs->trans('Label').'
'.$langs->trans('DateInvoice').''; - $form->select_date($dateinvoice,'','','','',"add",1,1); - print '
'.$langs->trans('DateInvoice').''; + $form->select_date($dateinvoice,'','','','',"add",1,1); + print '
'.$langs->trans('DateMaxPayment').''; - $form->select_date($datedue,'ech','','','',"add",1,1); - print '
'.$langs->trans('DateMaxPayment').''; + $form->select_date($datedue,'ech','','','',"add",1,1); + print '
'.$langs->trans('PaymentConditionsShort').''; @@ -1750,18 +1757,18 @@ if ($action == 'create') $form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id, 'mode_reglement_id', 'DBIT'); print '
'.$langs->trans('BankAccount').''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
'.$langs->trans('BankAccount').''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
'.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
'; - print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); print '
'.$langs->trans('NotePublic').''; - $note_public = $object->getDefaultCreateValueFor('note_public'); - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print ''; + $note_public = $object->getDefaultCreateValueFor('note_public'); + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
'.$langs->trans('NotePrivate').''; - $note_private = $object->getDefaultCreateValueFor('note_private'); - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
'.$langs->trans('NotePrivate').''; + $note_private = $object->getDefaultCreateValueFor('note_private'); + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
'.$txt.''.$objectsrc->getNomUrl(1); - // We check if Origin document (id and type is known) has already at least one invoice attached to it - $objectsrc->fetchObjectLinked($originid,$origin,'','invoice_supplier'); - $cntinvoice=count($objectsrc->linkedObjects['invoice_supplier']); - if ($cntinvoice>=1) - { - setEventMessages('WarningBillExist', null, 'warnings'); - echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['invoice_supplier'])->getNomUrl(1).')'; - } - echo '
'.$langs->trans('TotalHT').''.price($objectsrc->total_ht).'
'.$langs->trans('TotalVAT').''.price($objectsrc->total_tva)."
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($objectsrc->total_localtax1)."
'.$txt.''.$objectsrc->getNomUrl(1); + // We check if Origin document (id and type is known) has already at least one invoice attached to it + $objectsrc->fetchObjectLinked($originid,$origin,'','invoice_supplier'); + $cntinvoice=count($objectsrc->linkedObjects['invoice_supplier']); + if ($cntinvoice>=1) + { + setEventMessages('WarningBillExist', null, 'warnings'); + echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['invoice_supplier'])->getNomUrl(1).')'; + } + echo '
'.$langs->trans('TotalHT').''.price($objectsrc->total_ht).'
'.$langs->trans('TotalVAT').''.price($objectsrc->total_tva)."
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($objectsrc->total_localtax1)."
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($objectsrc->total_localtax2)."
'.$langs->trans('TotalTTC').''.price($objectsrc->total_ttc)."
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($objectsrc->total_localtax2)."
'.$langs->trans('TotalTTC').''.price($objectsrc->total_ttc)."
' . $langs->trans('MulticurrencyTotalVAT') . '' . price($objectsrc->multicurrency_total_tva) . "
' . $langs->trans('MulticurrencyTotalTTC') . '' . price($objectsrc->multicurrency_total_ttc) . "
\n"; + // Bouton "Create Draft" + print "\n"; - dol_fiche_end(); + dol_fiche_end(); - print '
'; - print ''; + print '
'; + print ''; print '     '; print ''; - print '
'; + print '
'; - print "
\n"; + print "\n"; - // Show origin lines - if (is_object($objectsrc)) - { - print '
'; + // Show origin lines + if (is_object($objectsrc)) + { + print '
'; - $title=$langs->trans('ProductsAndServices'); - print load_fiche_titre($title); + $title=$langs->trans('ProductsAndServices'); + print load_fiche_titre($title); - print ''; + print '
'; - $objectsrc->printOriginLinesList(); + $objectsrc->printOriginLinesList(); - print '
'; - } + print ''; + } } else { - if ($id > 0 || ! empty($ref)) - { - /* *************************************************************************** */ - /* */ - /* Fiche en mode visu ou edition */ - /* */ - /* *************************************************************************** */ + if ($id > 0 || ! empty($ref)) + { + /* *************************************************************************** */ + /* */ + /* Fiche en mode visu ou edition */ + /* */ + /* *************************************************************************** */ - $now=dol_now(); + $now=dol_now(); - $productstatic = new Product($db); + $productstatic = new Product($db); - $object->fetch($id,$ref); - $result=$object->fetch_thirdparty(); - if ($result < 0) dol_print_error($db); + $object->fetch($id,$ref); + $result=$object->fetch_thirdparty(); + if ($result < 0) dol_print_error($db); - $societe = new Fournisseur($db); - $result=$societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + $societe = new Fournisseur($db); + $result=$societe->fetch($object->socid); + if ($result < 0) dol_print_error($db); - // fetch optionals attributes and labels + // fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $alreadypaid=$object->getSommePaiement(); - /* + /* * View card */ - $head = facturefourn_prepare_head($object); - $titre=$langs->trans('SupplierInvoice'); + $head = facturefourn_prepare_head($object); + $titre=$langs->trans('SupplierInvoice'); - dol_fiche_head($head, 'card', $titre, -1, 'bill'); + dol_fiche_head($head, 'card', $titre, -1, 'bill'); - // Clone confirmation - if ($action == 'clone') - { - // Create an array for form - $formquestion=array( - //'text' => $langs->trans("ConfirmClone"), - //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1) - ); - // Paiement incomplet. On demande si motif = escompte ou autre + // Clone confirmation + if ($action == 'clone') + { + // Create an array for form + $formquestion=array( + //'text' => $langs->trans("ConfirmClone"), + //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1) + ); + // Paiement incomplet. On demande si motif = escompte ou autre $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes', 1); - } + } - // Confirmation de la validation - if ($action == 'valid') - { + // Confirmation de la validation + if ($action == 'valid') + { // on verifie si l'objet est en numerotation provisoire - $objectref = substr($object->ref, 1, 4); - if ($objectref == 'PROV') - { - $savdate=$object->date; - $numref = $object->getNextNumRef($societe); - } - else - { - $numref = $object->ref; - } + $objectref = substr($object->ref, 1, 4); + if ($objectref == 'PROV') + { + $savdate=$object->date; + $numref = $object->getNextNumRef($societe); + } + else + { + $numref = $object->ref; + } - $text=$langs->trans('ConfirmValidateBill',$numref); - /*if (! empty($conf->notification->enabled)) + $text=$langs->trans('ConfirmValidateBill',$numref); + /*if (! empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php'; $notify=new Notify($db); $text.='
'; $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object); }*/ - $formquestion=array(); + $formquestion=array(); - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct=new FormProduct($db); - $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("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1))); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value) + ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1, 240); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1); } - // Confirmation set paid - if ($action == 'paid') + // Confirmation edit (back to draft) + if ($action == 'edit') { + $formquestion = array(); + + $qualified_for_stock_change = 0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change = $object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change = $object->hasProductsOrServices(1); + } + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value) + ); + } + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); + + } + + // Confirmation set paid + if ($action == 'paid') + { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1); - } + } - // Confirmation de la suppression de la facture fournisseur - if ($action == 'delete') - { + // Confirmation de la suppression de la facture fournisseur + if ($action == 'delete') + { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); - } - if ($action == 'deletepaiement') - { - $payment_id = GETPOST('paiement_id'); + } + if ($action == 'deletepaiement') + { + $payment_id = GETPOST('paiement_id'); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1); - } + } - // Confirmation to delete line + // Confirmation to delete line if ($action == 'ask_deleteline') { $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } - if (!$formconfirm) - { + if (!$formconfirm) + { $parameters=array('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; @@ -2215,9 +2265,9 @@ else print ''; print ''; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { - list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); - } + if($action == 'actualizemulticurrencyrate') { + list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); + } $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); @@ -2230,35 +2280,35 @@ else print ''; } - // Bank Account - print ''; - print ''; - print '
'; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->fournisseur->facture->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ""; - print ''; + // Bank Account + print ''; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->fournisseur->facture->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ""; + print ''; // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print '
'; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->fournisseur->facture->creer) print ''.img_edit().''; - else print ' '; - print '
'; - print ''; - print ''; + print '
'; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->fournisseur->facture->creer) print ''.img_edit().''; + else print ' '; + print '
'; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2267,142 +2317,142 @@ else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } - // Other attributes - $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print ''; + print ''; - print '
'; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print ''; - print ''; - print ''; + // Multicurrency Amount HT + print ''; + print ''; + print ''; - // Multicurrency Amount VAT - print ''; - print ''; - print ''; + // Multicurrency Amount VAT + print ''; + print ''; + print ''; - // Multicurrency Amount TTC - print ''; - print ''; - print ''; - } + // Multicurrency Amount TTC + print ''; + print ''; + print ''; + } - // Amount - print ''; - print ''; + // Amount + print ''; + print ''; - // Amount Local Taxes - //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj=="1") //Localtax1 - { - print ''; - print ''; - print ''; - } - if ($societe->localtax2_assuj=="1") //Localtax2 - { - print ''; - print ''; - print ''; - } - print ''; + // Amount Local Taxes + //TODO: Place into a function to control showing by country or study better option + if ($societe->localtax1_assuj=="1") //Localtax1 + { + print ''; + print ''; + print ''; + } + if ($societe->localtax2_assuj=="1") //Localtax2 + { + print ''; + print ''; + print ''; + } + print ''; - print '
' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
'.$langs->trans('AmountHT').''.price($object->total_ht,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->trans('AmountVAT').''.price($object->total_tva,1,$langs,0,-1,-1,$conf->currency).'
        '; - if (GETPOST('calculationrule')) $calculationrule=GETPOST('calculationrule','alpha'); - else $calculationrule=(empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)?'totalofround':'roundoftotal'); - if ($calculationrule == 'totalofround') $calculationrulenum=1; - else $calculationrulenum=2; - $s=$langs->trans("ReCalculate").' '; - $s.=''.$langs->trans("Mode1").''; - $s.=' / '; - $s.=''.$langs->trans("Mode2").''; - print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc",$calculationrulenum).'
'.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('','help')); - print '
'.$langs->trans('AmountHT').''.price($object->total_ht,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->trans('AmountVAT').''.price($object->total_tva,1,$langs,0,-1,-1,$conf->currency).'
        '; + if (GETPOST('calculationrule')) $calculationrule=GETPOST('calculationrule','alpha'); + else $calculationrule=(empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)?'totalofround':'roundoftotal'); + if ($calculationrule == 'totalofround') $calculationrulenum=1; + else $calculationrulenum=2; + $s=$langs->trans("ReCalculate").' '; + $s.=''.$langs->trans("Mode1").''; + $s.=' / '; + $s.=''.$langs->trans("Mode2").''; + print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc",$calculationrulenum).'
'.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('','help')); + print '
'.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->trans('AmountTTC').''.price($object->total_ttc,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).'
'.$langs->trans('AmountTTC').''.price($object->total_ttc,1,$langs,0,-1,-1,$conf->currency).'
'; + print ''; - /* + /* * List of payments */ - $totalpaye = 0; + $totalpaye = 0; $sign = 1; if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = - 1; $nbrows=9; $nbcols=3; - if (! empty($conf->projet->enabled)) $nbrows++; - if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } - if (! empty($conf->incoterm->enabled)) $nbrows++; + if (! empty($conf->projet->enabled)) $nbrows++; + if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } + if (! empty($conf->incoterm->enabled)) $nbrows++; if (! empty($conf->multicurrency->enabled)) $nbrows += 5; - // Local taxes - if ($societe->localtax1_assuj=="1") $nbrows++; - if ($societe->localtax2_assuj=="1") $nbrows++; + // Local taxes + if ($societe->localtax1_assuj=="1") $nbrows++; + if ($societe->localtax2_assuj=="1") $nbrows++; - $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; - $sql.= ' c.id as paiement_type,'; - $sql.= ' pf.amount,'; - $sql.= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; - $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; - $sql.= ' ORDER BY p.datep, p.tms'; + $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; + $sql.= ' c.id as paiement_type,'; + $sql.= ' pf.amount,'; + $sql.= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; + $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; + $sql.= ' ORDER BY p.datep, p.tms'; - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - print ''; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + print '
' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . ''.$langs->trans('Date').''.$langs->trans('Type').''.$langs->trans('BankAccount').''.$langs->trans('Amount').' 
'; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; - $var=false; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($result); + $var=false; + if ($num > 0) + { + while ($i < $num) + { + $objp = $db->fetch_object($result); - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) - { - $bankaccountstatic->id=$objp->baid; - $bankaccountstatic->ref=$objp->baref; - $bankaccountstatic->label=$objp->baref; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id=$objp->baid; + $bankaccountstatic->ref=$objp->baref; + $bankaccountstatic->label=$objp->baref; $bankaccountstatic->number = $objp->banumber; if (! empty($conf->accounting->enabled)) { @@ -2413,28 +2463,28 @@ else $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0,1,1,'',1); } - print ''; - } - print ''; - print ''; - print ''; - $totalpaye += $objp->amount; - $i++; - } - } - else - { - print ''; - } + print ''; + } + print ''; + print ''; + print ''; + $totalpaye += $objp->amount; + $i++; + } + } + else + { + print ''; + } /* if ($object->paye == 0) @@ -2449,12 +2499,12 @@ else } */ - $db->free($result); - } - else - { - dol_print_error($db); - } + $db->free($result); + } + else + { + dol_print_error($db); + } if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { @@ -2466,7 +2516,7 @@ else print $langs->trans('AlreadyPaid'); print ' :'; - $resteapayer = $object->total_ttc - $totalpaye; + $resteapayer = $object->total_ttc - $totalpaye; $resteapayeraffiche = $resteapayer; $cssforamountpaymentcomplete = 'amountpaymentcomplete'; @@ -2585,29 +2635,29 @@ else print '
' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . ''.$langs->trans('Date').''.$langs->trans('Type').''.$langs->trans('BankAccount').''.$langs->trans('Amount').' 
'; - $paymentstatic->id=$objp->rowid; - $paymentstatic->datepaye=$db->jdate($objp->dp); - $paymentstatic->ref=($objp->ref ? $objp->ref : $objp->rowid);; - $paymentstatic->num_paiement=$objp->num_paiement; - $paymentstatic->payment_code=$objp->payment_code; - print $paymentstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp), 'day') . ''; - print $form->form_modes_reglement(null, $objp->paiement_type,'none').' '.$objp->num_paiement; - print '
'; + $paymentstatic->id=$objp->rowid; + $paymentstatic->datepaye=$db->jdate($objp->dp); + $paymentstatic->ref=($objp->ref ? $objp->ref : $objp->rowid);; + $paymentstatic->num_paiement=$objp->num_paiement; + $paymentstatic->payment_code=$objp->payment_code; + print $paymentstatic->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->dp), 'day') . ''; + print $form->form_modes_reglement(null, $objp->paiement_type,'none').' '.$objp->num_paiement; + print ''; - if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1,'transactions'); - print '' . price($sign * $objp->amount) . ''; - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) - { - print 'rowid.'">'; - print img_delete(); - print ''; - } - print '
'.$langs->trans("None").'
'; + if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1,'transactions'); + print '' . price($sign * $objp->amount) . ''; + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) + { + print 'rowid.'">'; + print img_delete(); + print ''; + } + print '
'.$langs->trans("None").'
0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
'; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print '

'; + print '

'; - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { - $blocname = 'contacts'; - $title = $langs->trans('ContactsAddresses'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) + { + $blocname = 'contacts'; + $title = $langs->trans('ContactsAddresses'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $colwidth=20; - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $colwidth=20; + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - /* + /* * Lines */ print '
'; @@ -2621,7 +2671,7 @@ else include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
'; + print '
'; print ''; global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; @@ -2634,7 +2684,7 @@ else $num=count($object->lines); // Form to add new line - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $user->rights->fournisseur->facture->creer) + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $user->rights->fournisseur->facture->creer) { if ($action != 'editline') { @@ -2646,76 +2696,76 @@ else $parameters = array(); $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - } + } - print '
'; - print '
'; - print ''; + print ''; + print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - if ($action != 'presend') - { - /* + if ($action != 'presend') + { + /* * Boutons actions */ - print '
'; + print '
'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { // Modify a validated invoice with no payments - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'edit' && $object->getSommePaiement() == 0 && $user->rights->fournisseur->facture->creer) + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $user->rights->fournisseur->facture->creer) { print ''; } // Reopen a standard paid invoice - if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT) && ($object->statut == 2 || $object->statut == 3)) // A paid invoice (partially or completely) - { - if (! $facidnext && $object->close_code != 'replaced' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice - { - print ''; - } - else - { - if ($user->rights->fournisseur->facture->creer) { - print '
'.$langs->trans('ReOpen').'
'; - } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { - print '
'.$langs->trans('ReOpen').'
'; - } - } - } + if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT) && ($object->statut == 2 || $object->statut == 3)) // A paid invoice (partially or completely) + { + if (! $facidnext && $object->close_code != 'replaced' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice + { + print ''; + } + else + { + if ($user->rights->fournisseur->facture->creer) { + print '
'.$langs->trans('ReOpen').'
'; + } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { + print '
'.$langs->trans('ReOpen').'
'; + } + } + } - // Send by mail - if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send) - { - print ''; - } - else print '
'.$langs->trans('SendByMail').'
'; - } + // Send by mail + if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) + { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send) + { + print ''; + } + else print '
'.$langs->trans('SendByMail').'
'; + } // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { print ''; // must use facid because id is for payment id not invoice } // Classify paid - if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { print ''; - //print ''.$langs->trans('ClassifyPaid').''; - } + //print ''.$langs->trans('ClassifyPaid').''; + } // Reverse back money or convert to reduction if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { @@ -2744,7 +2794,7 @@ else } // Validate - if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) { if (count($object->lines)) { @@ -2768,11 +2818,11 @@ else print ''; } - // Clone - if ($action != 'edit' && $user->rights->fournisseur->facture->creer) - { - print ''; - } + // Clone + if ($action != 'edit' && $user->rights->fournisseur->facture->creer) + { + print ''; + } // Create a credit note if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $user->rights->fournisseur->facture->creer) @@ -2784,7 +2834,7 @@ else } // Delete - if ($action != 'edit' && $user->rights->fournisseur->facture->supprimer) + if ($action != 'confirm_edit' && $user->rights->fournisseur->facture->supprimer) { if ($object->getSommePaiement()) { print ''; @@ -2794,56 +2844,56 @@ else } print '
'; - if ($action != 'edit') + if ($action != 'confirm_edit') { print '
'; /* * Documents generes */ - $ref=dol_sanitizeFileName($object->ref); - $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; - $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; - $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id; - $genallowed=$user->rights->fournisseur->facture->creer; - $delallowed=$user->rights->fournisseur->facture->supprimer; - $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)?'':$conf->global->INVOICE_SUPPLIER_ADDON_PDF)); + $ref=dol_sanitizeFileName($object->ref); + $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; + $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; + $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id; + $genallowed=$user->rights->fournisseur->facture->lire; + $delallowed=$user->rights->fournisseur->facture->creer; + $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)?'':$conf->global->INVOICE_SUPPLIER_ADDON_PDF)); - print $formfile->showdocuments('facture_fournisseur',$subdir,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang); - $somethingshown=$formfile->numoffiles; + print $formfile->showdocuments('facture_fournisseur',$subdir,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang); + $somethingshown=$formfile->numoffiles; - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; - //print ''; - //print '
'; + print '
'; + //print ''; + //print '
'; - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object,'invoice_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown = $formactions->showactions($object,'invoice_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); print '
'; - //print ''; - } + //print ''; + } } - } + } - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } - // Presend form - $modelmail='supplier_order_send'; - $defaulttopic='SendBillRef'; - $diroutput = $conf->fournisseur->facture->dir_output; - $trackid = 'sin'.$object->id; + // Presend form + $modelmail='supplier_order_send'; + $defaulttopic='SendBillRef'; + $diroutput = $conf->fournisseur->facture->dir_output; + $trackid = 'sin'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - } + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; + } } diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index e6c8023496c..94df346aae4 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -1166,7 +1166,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->creer; print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index 36749977927..14eca2c58d0 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -374,8 +374,8 @@ if ($result > 0) $ref=dol_sanitizeFileName($object->ref); $filedir = $conf->fournisseur->payment->dir_output.'/'.dol_sanitizeFileName($object->ref); $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id; - $genallowed=$user->rights->fournisseur->facture->creer; - $delallowed=$user->rights->fournisseur->facture->supprimer; + $genallowed=$user->rights->fournisseur->facture->lire; + $delallowed=$user->rights->fournisseur->facture->creer; $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF)?'':$conf->global->SUPPLIER_PAYMENT_ADDON_PDF)); print $formfile->showdocuments('supplier_payment',$ref,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang); diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index ba976c2ee48..8fe8a14430a 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -34,7 +34,6 @@ class Holiday extends CommonObject { public $element='holiday'; public $table_element='holiday'; - protected $isnolinkedbythird = 1; // No field fk_soc protected $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'holiday'; diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index f25dcb9e227..efe1c87820e 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -259,6 +259,8 @@ if ($id > 0) $fuser->fetch($id, '', '', 1); $fuser->getrights(); $user_id = $fuser->id; + + $search_employee = $user_id; } // RĆ©cupĆ©ration des congĆ©s payĆ©s de l'utilisateur ou de tous les users diff --git a/htdocs/includes/jquery/plugins/fileupload/README.md b/htdocs/includes/jquery/plugins/fileupload/README.md deleted file mode 100644 index 513a028f06d..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# jQuery File Upload Plugin - -## Demo -[Demo File Upload](http://blueimp.github.com/jQuery-File-Upload/) - -## Setup instructions -* [How to setup the plugin on your website](https://github.com/blueimp/jQuery-File-Upload/wiki/Setup) -* [How to use only the basic plugin (minimal setup guide).](https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin) - -## Features -* **Multiple file upload:** - Allows to select multiple files at once and upload them simultaneously. -* **Drag & Drop support:** - Allows to upload files by dragging them from your desktop or filemanager and dropping them on your browser window. -* **Upload progress bar:** - Shows a progress bar indicating the upload progress for individual files and for all uploads combined. -* **Cancelable uploads:** - Individual file uploads can be canceled to stop the upload progress. -* **Resumable uploads:** - Aborted uploads can be resumed with browsers supporting the Blob API. -* **Chunked uploads:** - Large files can be uploaded in smaller chunks with browsers supporting the Blob API. -* **Client-side image resizing:** - Images can be automatically resized on client-side with browsers supporting the required JS APIs. -* **Preview images:** - A preview of image files can be displayed before uploading with browsers supporting the required JS APIs. -* **No browser plugins (e.g. Adobe Flash) required:** - The implementation is based on open standards like HTML5 and JavaScript and requires no additional browser plugins. -* **Graceful fallback for legacy browsers:** - Uploads files via XMLHttpRequests if supported and uses iframes as fallback for legacy browsers. -* **HTML file upload form fallback:** - Shows a standard HTML file upload form if JavaScript is disabled. -* **Cross-site file uploads:** - Supports uploading files to a different domain with Cross-site XMLHttpRequests. -* **Multiple plugin instances:** - Allows to use multiple plugin instances on the same webpage. -* **Customizable and extensible:** - Provides an API to set individual options and define callBack methods for various upload events. -* **Multipart and file contents stream uploads:** - Files can be uploaded as standard "multipart/form-data" or file contents stream (HTTP PUT file upload). -* **Compatible with any server-side application platform:** - Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads. - -## Requirements -* [jQuery](http://jquery.com/) v. 1.6+ -* [jQuery UI widget factory](http://wiki.jqueryui.com/w/page/12138135/Widget%20factory) v. 1.8+ -* [jQuery Iframe Transport plugin](https://github.com/blueimp/jQuery-File-Upload/blob/master/jquery.iframe-transport.js) (included) -* [JavaScript Templates engine](https://github.com/blueimp/JavaScript-Templates) v. 2.1.0+ (optional) -* [JavaScript Load Image function](https://github.com/blueimp/JavaScript-Load-Image) v. 1.1.6+ (optional) -* [JavaScript Canvas to Blob function](https://github.com/blueimp/JavaScript-Canvas-to-Blob) v. 2.0.0+ (optional) -* [Bootstrap CSS Toolkit](https://github.com/twitter/bootstrap/) v. 2.0+ (optional) - -The jQuery UI widget factory is a requirement for the basic File Upload plugin, but very lightweight without any other dependencies. -The jQuery Iframe Transport is required for [browsers without XHR file upload support](https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support). -The UI version of the File Upload plugin also requires the JavaScript Templates engine as well as the JavaScript Load Image and JavaScript Canvas to Blob functions (for the image previews and resizing functionality). These dependencies are marked as optional, as the basic File Upload plugin can be used without them and the UI version of the plugin can be extended to override these dependencies with alternative solutions. - -The User Interface is built with Twitter's [Bootstrap](https://github.com/twitter/bootstrap/) Toolkit. This enables a CSS based, responsive layout and fancy transition effects on modern browsers. The demo also includes the [Bootstrap Image Gallery Plugin](https://github.com/blueimp/Bootstrap-Image-Gallery). Both of these components are optional and not required. - -The repository also includes the [jQuery XDomainRequest Transport plugin](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/cors/jquery.xdr-transport.js), which enables Cross-domain AJAX requests (GET and POST only) in Microsoft Internet Explorer >= 8. However, the XDomainRequest object doesn't support file uploads and the plugin is only used by the [Demo](http://blueimp.github.com/jQuery-File-Upload/) for Cross-domain requests to delete uploaded files from the demo file upload service. - -[Cross-domain File Uploads](https://github.com/blueimp/jQuery-File-Upload/wiki/Cross-domain-uploads) using the [Iframe Transport plugin](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js) require a redirect back to the origin server to retrieve the upload results. The [example implementation](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/main.js) makes use of [result.html](https://github.com/blueimp/jQuery-File-Upload/blob/master/cors/result.html) as a static redirect page for the origin server. - -## Browser Support (tested versions) -* Google Chrome - 7.0+ -* Apple Safari - 4.0+ -* Mozilla Firefox - 3.0+ -* Opera - 10.0+ -* Microsoft Internet Explorer 6.0+ - -Drag & Drop is only supported on Google Chrome, Firefox 4.0+ and Safari 5.0+. -Microsoft Internet Explorer has no support for multiple file selection or upload progress. -[Extended browser support information](https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support). - -## License -Released under the [MIT license](http://www.opensource.org/licenses/MIT). diff --git a/htdocs/includes/jquery/plugins/fileupload/css/jquery.fileupload-ui.css b/htdocs/includes/jquery/plugins/fileupload/css/jquery.fileupload-ui.css deleted file mode 100644 index c86d3d8e712..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/css/jquery.fileupload-ui.css +++ /dev/null @@ -1,117 +0,0 @@ -@charset 'UTF-8'; -/* - * jQuery File Upload UI Plugin CSS 6.3 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -.fileinput-button { - position: relative; - overflow: hidden; - float: left; - margin-right: 5px; -} -.fileinput-button input { - position: absolute; - top: 0; - right: 0; - margin: 0; - border: solid transparent; - border-width: 0 0 100px 200px; - opacity: 0; - filter: alpha(opacity=0); - -moz-transform: translate(-300px, 0) scale(4); - direction: ltr; - cursor: pointer; -} -.fileupload-buttonbar .ui-button, -.fileupload-buttonbar .toggle { - margin-bottom: 5px; -} -.files .progress { - width: 200px; -} -.files .progress, -.fileupload-buttonbar .progress { - height: 20px; -} -.files .ui-progressbar-value, -.fileupload-buttonbar .ui-progressbar-value { - background: url(../img/progressbar.gif); -} -.fileupload-buttonbar .fade, -.files .fade { - display: none; -} -.fileupload-loading { - position: absolute; - left: 50%; - width: 128px; - height: 128px; - background: url(../img/loading.gif) center no-repeat; - display: none; -} -.fileupload-processing .fileupload-loading { - display: block; -} - -/* Fix for IE 6: */ -*html .fileinput-button { - margin-right: -2px; -} -*html .fileinput-button .ui-button-text { - line-height: 24px; -} -*html .fileupload-buttonbar .ui-button { - margin-left: 3px; -} - -/* Fix for IE 7: */ -*+html .fileinput-button { - margin-right: 1px; -} -*+html .fileinput-button .ui-button-text { - line-height: 24px; -} -*+html .fileupload-buttonbar .ui-button { - margin-left: 3px; -} - -@media (max-width: 480px) { - .files .preview * { - width: 40px; - } - .files .name * { - width: 80px; - display: inline-block; - word-wrap: break-word; - } - .files .progress { - width: 20px; - } - .files .delete { - width: 60px; - } -} - -/* Fix for Webkit (Safari, Chrome) */ -@media screen and (-webkit-min-device-pixel-ratio:0) { - .fileinput-button { - margin-top: 2px; - } -} - -.span5 { - width: 400px; - float: left; -} -.span7 { - width: 560px ; - float: left; -} - diff --git a/htdocs/includes/jquery/plugins/fileupload/img/loading.gif b/htdocs/includes/jquery/plugins/fileupload/img/loading.gif deleted file mode 100644 index 90f28cbdbb3..00000000000 Binary files a/htdocs/includes/jquery/plugins/fileupload/img/loading.gif and /dev/null differ diff --git a/htdocs/includes/jquery/plugins/fileupload/img/progressbar.gif b/htdocs/includes/jquery/plugins/fileupload/img/progressbar.gif deleted file mode 100644 index fbcce6bc9ab..00000000000 Binary files a/htdocs/includes/jquery/plugins/fileupload/img/progressbar.gif and /dev/null differ diff --git a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.postmessage-transport.js b/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.postmessage-transport.js deleted file mode 100644 index 931b6352ba2..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.postmessage-transport.js +++ /dev/null @@ -1,117 +0,0 @@ -/* - * jQuery postMessage Transport Plugin 1.1 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint unparam: true, nomen: true */ -/*global define, window, document */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - - var counter = 0, - names = [ - 'accepts', - 'cache', - 'contents', - 'contentType', - 'crossDomain', - 'data', - 'dataType', - 'headers', - 'ifModified', - 'mimeType', - 'password', - 'processData', - 'timeout', - 'traditional', - 'type', - 'url', - 'username' - ], - convert = function (p) { - return p; - }; - - $.ajaxSetup({ - converters: { - 'postmessage text': convert, - 'postmessage json': convert, - 'postmessage html': convert - } - }); - - $.ajaxTransport('postmessage', function (options) { - if (options.postMessage && window.postMessage) { - var iframe, - loc = $('').prop('href', options.postMessage)[0], - target = loc.protocol + '//' + loc.host, - xhrUpload = options.xhr().upload; - return { - send: function (_, completeCallback) { - var message = { - id: 'postmessage-transport-' + (counter += 1) - }, - eventName = 'message.' + message.id; - iframe = $( - '' - ).bind('load', function () { - $.each(names, function (i, name) { - message[name] = options[name]; - }); - message.dataType = message.dataType.replace('postmessage ', ''); - $(window).bind(eventName, function (e) { - e = e.originalEvent; - var data = e.data, - ev; - if (e.origin === target && data.id === message.id) { - if (data.type === 'progress') { - ev = document.createEvent('Event'); - ev.initEvent(data.type, false, true); - $.extend(ev, data); - xhrUpload.dispatchEvent(ev); - } else { - completeCallback( - data.status, - data.statusText, - {postmessage: data.result}, - data.headers - ); - iframe.remove(); - $(window).unbind(eventName); - } - } - }); - iframe[0].contentWindow.postMessage( - message, - target - ); - }).appendTo(document.body); - }, - abort: function () { - if (iframe) { - iframe.remove(); - } - } - }; - } - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.xdr-transport.js b/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.xdr-transport.js deleted file mode 100644 index c42c54828d8..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.xdr-transport.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * jQuery XDomainRequest Transport Plugin 1.1.2 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - * - * Based on Julian Aubourg's ajaxHooks xdr.js: - * https://github.com/jaubourg/ajaxHooks/ - */ - -/*jslint unparam: true */ -/*global define, window, XDomainRequest */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - if (window.XDomainRequest && !$.support.cors) { - $.ajaxTransport(function (s) { - if (s.crossDomain && s.async) { - if (s.timeout) { - s.xdrTimeout = s.timeout; - delete s.timeout; - } - var xdr; - return { - send: function (headers, completeCallback) { - function callback(status, statusText, responses, responseHeaders) { - xdr.onload = xdr.onerror = xdr.ontimeout = $.noop; - xdr = null; - completeCallback(status, statusText, responses, responseHeaders); - } - xdr = new XDomainRequest(); - // XDomainRequest only supports GET and POST: - if (s.type === 'DELETE') { - s.url = s.url + (/\?/.test(s.url) ? '&' : '?') + - '_method=DELETE'; - s.type = 'POST'; - } else if (s.type === 'PUT') { - s.url = s.url + (/\?/.test(s.url) ? '&' : '?') + - '_method=PUT'; - s.type = 'POST'; - } - xdr.open(s.type, s.url); - xdr.onload = function () { - callback( - 200, - 'OK', - {text: xdr.responseText}, - 'Content-Type: ' + xdr.contentType - ); - }; - xdr.onerror = function () { - callback(404, 'Not Found'); - }; - if (s.xdrTimeout) { - xdr.ontimeout = function () { - callback(0, 'timeout'); - }; - xdr.timeout = s.xdrTimeout; - } - xdr.send((s.hasContent && s.data) || null); - }, - abort: function () { - if (xdr) { - xdr.onerror = $.noop(); - xdr.abort(); - } - } - }; - } - }); - } -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-fp.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-fp.js deleted file mode 100644 index 634fb5e4ee5..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-fp.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * jQuery File Upload File Processing Plugin 1.0 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2012, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global define, window, document */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define([ - 'jquery', - 'load-image', - 'canvas-to-blob', - './jquery.fileupload' - ], factory); - } else { - // Browser globals: - factory( - window.jQuery, - window.loadImage - ); - } -}(function ($, loadImage) { - 'use strict'; - - // The File Upload IP version extends the basic fileupload widget - // with file processing functionality: - $.widget('blueimpFP.fileupload', $.blueimp.fileupload, { - - options: { - // The list of file processing actions: - process: [ - /* - { - action: 'load', - fileTypes: /^image\/(gif|jpeg|png)$/, - maxFileSize: 20000000 // 20MB - }, - { - action: 'resize', - maxWidth: 1920, - maxHeight: 1200, - minWidth: 800, - minHeight: 600 - }, - { - action: 'save' - } - */ - ], - - // The add callback is invoked as soon as files are added to the - // fileupload widget (via file input selection, drag & drop or add - // API call). See the basic file upload widget for more information: - add: function (e, data) { - $(this).fileupload('process', data).done(function () { - data.submit(); - }); - } - }, - - processActions: { - // Loads the image given via data.files and data.index - // as canvas element. - // Accepts the options fileTypes (regular expression) - // and maxFileSize (integer) to limit the files to load: - load: function (data, options) { - var that = this, - file = data.files[data.index], - dfd = $.Deferred(); - if (window.HTMLCanvasElement && - window.HTMLCanvasElement.prototype.toBlob && - ($.type(options.maxFileSize) !== 'number' || - file.size < options.maxFileSize) && - (!options.fileTypes || - options.fileTypes.test(file.type))) { - loadImage( - file, - function (canvas) { - data.canvas = canvas; - dfd.resolveWith(that, [data]); - }, - {canvas: true} - ); - } else { - dfd.rejectWith(that, [data]); - } - return dfd.promise(); - }, - // Resizes the image given as data.canvas and updates - // data.canvas with the resized image. - // Accepts the options maxWidth, maxHeight, minWidth and - // minHeight to scale the given image: - resize: function (data, options) { - if (data.canvas) { - var canvas = loadImage.scale(data.canvas, options); - if (canvas.width !== data.canvas.width || - canvas.height !== data.canvas.height) { - data.canvas = canvas; - data.processed = true; - } - } - return data; - }, - // Saves the processed image given as data.canvas - // inplace at data.index of data.files: - save: function (data, options) { - // Do nothing if no processing has happened: - if (!data.canvas || !data.processed) { - return data; - } - var that = this, - file = data.files[data.index], - name = file.name, - dfd = $.Deferred(), - callback = function (blob) { - if (!blob.name) { - if (file.type === blob.type) { - blob.name = file.name; - } else if (file.name) { - blob.name = file.name.replace( - /\..+$/, - '.' + blob.type.substr(6) - ); - } - } - // Store the created blob at the position - // of the original file in the files list: - data.files[data.index] = blob; - dfd.resolveWith(that, [data]); - }; - // Use canvas.mozGetAsFile directly, to retain the filename, as - // Gecko doesn't support the filename option for FormData.append: - if (data.canvas.mozGetAsFile) { - callback(data.canvas.mozGetAsFile( - (/^image\/(jpeg|png)$/.test(file.type) && name) || - ((name && name.replace(/\..+$/, '')) || - 'blob') + '.png', - file.type - )); - } else { - data.canvas.toBlob(callback, file.type); - } - return dfd.promise(); - } - }, - - // Resizes the file at the given index and stores the created blob at - // the original position of the files list, returns a Promise object: - _processFile: function (files, index, options) { - var that = this, - dfd = $.Deferred().resolveWith(that, [{ - files: files, - index: index - }]), - chain = dfd.promise(); - that._processing += 1; - $.each(options.process, function (i, settings) { - chain = chain.pipe(function (data) { - return that.processActions[settings.action] - .call(this, data, settings); - }); - }); - chain.always(function () { - that._processing -= 1; - if (that._processing === 0) { - that.element - .removeClass('fileupload-processing'); - } - }); - if (that._processing === 1) { - that.element.addClass('fileupload-processing'); - } - return chain; - }, - - // Processes the files given as files property of the data parameter, - // returns a Promise object that allows to bind a done handler, which - // will be invoked after processing all files (inplace) is done: - process: function (data) { - var that = this, - options = $.extend({}, this.options, data); - if (options.process && options.process.length && - this._isXHRUpload(options)) { - $.each(data.files, function (index, file) { - that._processingQueue = that._processingQueue.pipe( - function () { - var dfd = $.Deferred(); - that._processFile(data.files, index, options) - .always(function () { - dfd.resolveWith(that); - }); - return dfd.promise(); - } - ); - }); - } - return this._processingQueue; - }, - - _create: function () { - $.blueimp.fileupload.prototype._create.call(this); - this._processing = 0; - this._processingQueue = $.Deferred().resolveWith(this) - .promise(); - } - - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-jui.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-jui.js deleted file mode 100644 index 69736a4a44d..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-jui.js +++ /dev/null @@ -1,141 +0,0 @@ -/* - * jQuery File Upload jQuery UI Plugin 1.2 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2012, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true */ -/*global define, window */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery', './jquery.fileupload-ui.js'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - $.widget('blueimpJUI.fileupload', $.blueimpUI.fileupload, { - options: { - sent: function (e, data) { - if (data.context && data.dataType && - data.dataType.substr(0, 6) === 'iframe') { - // Iframe Transport does not support progress events. - // In lack of an indeterminate progress bar, we set - // the progress to 100%, showing the full animated bar: - data.context - .find('.progress').progressbar( - 'option', - 'value', - 100 - ); - } - }, - progress: function (e, data) { - if (data.context) { - data.context.find('.progress').progressbar( - 'option', - 'value', - parseInt(data.loaded / data.total * 100, 10) - ); - } - }, - progressall: function (e, data) { - var $this = $(this); - $this.find('.fileupload-progress') - .find('.progress').progressbar( - 'option', - 'value', - parseInt(data.loaded / data.total * 100, 10) - ).end() - .find('.progress-extended').each(function () { - $(this).html( - $this.data('fileupload') - ._renderExtendedProgress(data) - ); - }); - } - }, - _renderUpload: function (func, files) { - var node = $.blueimpUI.fileupload.prototype - ._renderUpload.call(this, func, files), - showIconText = $(window).width() > 480; - node.find('.progress').empty().progressbar(); - node.find('.start button').button({ - icons: {primary: 'ui-icon-circle-arrow-e'}, - text: showIconText - }); - node.find('.cancel button').button({ - icons: {primary: 'ui-icon-cancel'}, - text: showIconText - }); - return node; - }, - _renderDownload: function (func, files) { - var node = $.blueimpUI.fileupload.prototype - ._renderDownload.call(this, func, files), - showIconText = $(window).width() > 480; - node.find('.delete button').button({ - icons: {primary: 'ui-icon-trash'}, - text: showIconText - }); - return node; - }, - _transition: function (node) { - var that = this, - deferred = $.Deferred(); - if (node.hasClass('fade')) { - node.fadeToggle(function () { - deferred.resolveWith(node); - }); - } else { - deferred.resolveWith(node); - } - return deferred; - }, - _create: function () { - $.blueimpUI.fileupload.prototype._create.call(this); - this.element - .find('.fileupload-buttonbar') - .find('.fileinput-button').each(function () { - var input = $(this).find('input:file').detach(); - $(this) - .button({icons: {primary: 'ui-icon-plusthick'}}) - .append(input); - }) - .end().find('.start') - .button({icons: {primary: 'ui-icon-circle-arrow-e'}}) - .end().find('.cancel') - .button({icons: {primary: 'ui-icon-cancel'}}) - .end().find('.delete') - .button({icons: {primary: 'ui-icon-trash'}}) - .end().find('.progress').empty().progressbar(); - }, - destroy: function () { - this.element - .find('.fileupload-buttonbar') - .find('.fileinput-button').each(function () { - var input = $(this).find('input:file').detach(); - $(this) - .button('destroy') - .append(input); - }) - .end().find('.start') - .button('destroy') - .end().find('.cancel') - .button('destroy') - .end().find('.delete') - .button('destroy') - .end().find('.progress').progressbar('destroy'); - $.blueimpUI.fileupload.prototype.destroy.call(this); - } - }); -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-ui.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-ui.js deleted file mode 100644 index 4c36f00865b..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-ui.js +++ /dev/null @@ -1,736 +0,0 @@ -/* - * jQuery File Upload User Interface Plugin 6.9.4 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global define, window, document, URL, webkitURL, FileReader */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define([ - 'jquery', - 'tmpl', - 'load-image', - './jquery.fileupload-fp' - ], factory); - } else { - // Browser globals: - factory( - window.jQuery, - window.tmpl, - window.loadImage - ); - } -}(function ($, tmpl, loadImage) { - 'use strict'; - - // The UI version extends the FP (file processing) version or the basic - // file upload widget and adds complete user interface interaction: - var parentWidget = ($.blueimpFP || $.blueimp).fileupload; - $.widget('blueimpUI.fileupload', parentWidget, { - - options: { - // By default, files added to the widget are uploaded as soon - // as the user clicks on the start buttons. To enable automatic - // uploads, set the following option to true: - autoUpload: false, - // The following option limits the number of files that are - // allowed to be uploaded using this widget: - maxNumberOfFiles: undefined, - // The maximum allowed file size: - maxFileSize: undefined, - // The minimum allowed file size: - minFileSize: undefined, - // The regular expression for allowed file types, matches - // against either file type or file name: - acceptFileTypes: /.+$/i, - // The regular expression to define for which files a preview - // image is shown, matched against the file type: - previewSourceFileTypes: /^image\/(gif|jpeg|png)$/, - // The maximum file size of images that are to be displayed as preview: - previewSourceMaxFileSize: 5000000, // 5MB - // The maximum width of the preview images: - previewMaxWidth: 80, - // The maximum height of the preview images: - previewMaxHeight: 80, - // By default, preview images are displayed as canvas elements - // if supported by the browser. Set the following option to false - // to always display preview images as img elements: - previewAsCanvas: true, - // The ID of the upload template: - uploadTemplateId: 'template-upload', - // The ID of the download template: - downloadTemplateId: 'template-download', - // The container for the list of files. If undefined, it is set to - // an element with class "files" inside of the widget element: - filesContainer: undefined, - // By default, files are appended to the files container. - // Set the following option to true, to prepend files instead: - prependFiles: false, - // The expected data type of the upload response, sets the dataType - // option of the $.ajax upload requests: - dataType: 'json', - - // The add callback is invoked as soon as files are added to the fileupload - // widget (via file input selection, drag & drop or add API call). - // See the basic file upload widget for more information: - add: function (e, data) { - var that = $(this).data('fileupload'), - options = that.options, - files = data.files; - $(this).fileupload('process', data).done(function () { - that._adjustMaxNumberOfFiles(-files.length); - data.maxNumberOfFilesAdjusted = true; - data.files.valid = data.isValidated = that._validate(files); - data.context = that._renderUpload(files).data('data', data); - options.filesContainer[ - options.prependFiles ? 'prepend' : 'append' - ](data.context); - that._renderPreviews(files, data.context); - that._forceReflow(data.context); - that._transition(data.context).done( - function () { - if ((that._trigger('added', e, data) !== false) && - (options.autoUpload || data.autoUpload) && - data.autoUpload !== false && data.isValidated) { - data.submit(); - } - } - ); - }); - }, - // Callback for the start of each file upload request: - send: function (e, data) { - var that = $(this).data('fileupload'); - if (!data.isValidated) { - if (!data.maxNumberOfFilesAdjusted) { - that._adjustMaxNumberOfFiles(-data.files.length); - data.maxNumberOfFilesAdjusted = true; - } - if (!that._validate(data.files)) { - return false; - } - } - if (data.context && data.dataType && - data.dataType.substr(0, 6) === 'iframe') { - // Iframe Transport does not support progress events. - // In lack of an indeterminate progress bar, we set - // the progress to 100%, showing the full animated bar: - data.context - .find('.progress').addClass( - !$.support.transition && 'progress-animated' - ) - .attr('aria-valuenow', 100) - .find('.bar').css( - 'width', - '100%' - ); - } - return that._trigger('sent', e, data); - }, - // Callback for successful uploads: - done: function (e, data) { - var that = $(this).data('fileupload'), - template; - if (data.context) { - data.context.each(function (index) { - var file = ($.isArray(data.result) && - data.result[index]) || {error: 'emptyResult'}; - if (file.error) { - that._adjustMaxNumberOfFiles(1); - } - that._transition($(this)).done( - function () { - var node = $(this); - template = that._renderDownload([file]) - .replaceAll(node); - that._forceReflow(template); - that._transition(template).done( - function () { - data.context = $(this); - that._trigger('completed', e, data); - } - ); - } - ); - }); - } else { - if ($.isArray(data.result)) { - $.each(data.result, function (index, file) { - if (data.maxNumberOfFilesAdjusted && file.error) { - that._adjustMaxNumberOfFiles(1); - } else if (!data.maxNumberOfFilesAdjusted && - !file.error) { - that._adjustMaxNumberOfFiles(-1); - } - }); - data.maxNumberOfFilesAdjusted = true; - } - template = that._renderDownload(data.result) - .appendTo(that.options.filesContainer); - that._forceReflow(template); - that._transition(template).done( - function () { - data.context = $(this); - that._trigger('completed', e, data); - } - ); - } - }, - // Callback for failed (abort or error) uploads: - fail: function (e, data) { - var that = $(this).data('fileupload'), - template; - if (data.maxNumberOfFilesAdjusted) { - that._adjustMaxNumberOfFiles(data.files.length); - } - if (data.context) { - data.context.each(function (index) { - if (data.errorThrown !== 'abort') { - var file = data.files[index]; - file.error = file.error || data.errorThrown || - true; - that._transition($(this)).done( - function () { - var node = $(this); - template = that._renderDownload([file]) - .replaceAll(node); - that._forceReflow(template); - that._transition(template).done( - function () { - data.context = $(this); - that._trigger('failed', e, data); - } - ); - } - ); - } else { - that._transition($(this)).done( - function () { - $(this).remove(); - that._trigger('failed', e, data); - } - ); - } - }); - } else if (data.errorThrown !== 'abort') { - data.context = that._renderUpload(data.files) - .appendTo(that.options.filesContainer) - .data('data', data); - that._forceReflow(data.context); - that._transition(data.context).done( - function () { - data.context = $(this); - that._trigger('failed', e, data); - } - ); - } else { - that._trigger('failed', e, data); - } - }, - // Callback for upload progress events: - progress: function (e, data) { - if (data.context) { - var progress = parseInt(data.loaded / data.total * 100, 10); - data.context.find('.progress') - .attr('aria-valuenow', progress) - .find('.bar').css( - 'width', - progress + '%' - ); - } - }, - // Callback for global upload progress events: - progressall: function (e, data) { - var $this = $(this), - progress = parseInt(data.loaded / data.total * 100, 10), - globalProgressNode = $this.find('.fileupload-progress'), - extendedProgressNode = globalProgressNode - .find('.progress-extended'); - if (extendedProgressNode.length) { - extendedProgressNode.html( - $this.data('fileupload')._renderExtendedProgress(data) - ); - } - globalProgressNode - .find('.progress') - .attr('aria-valuenow', progress) - .find('.bar').css( - 'width', - progress + '%' - ); - }, - // Callback for uploads start, equivalent to the global ajaxStart event: - start: function (e) { - var that = $(this).data('fileupload'); - that._transition($(this).find('.fileupload-progress')).done( - function () { - that._trigger('started', e); - } - ); - }, - // Callback for uploads stop, equivalent to the global ajaxStop event: - stop: function (e) { - var that = $(this).data('fileupload'); - that._transition($(this).find('.fileupload-progress')).done( - function () { - $(this).find('.progress') - .attr('aria-valuenow', '0') - .find('.bar').css('width', '0%'); - $(this).find('.progress-extended').html(' '); - that._trigger('stopped', e); - } - ); - }, - // Callback for file deletion: - destroy: function (e, data) { - var that = $(this).data('fileupload'); - if (data.url) { - $.ajax(data); - that._adjustMaxNumberOfFiles(1); - } - that._transition(data.context).done( - function () { - $(this).remove(); - that._trigger('destroyed', e, data); - } - ); - } - }, - - // Link handler, that allows to download files - // by drag & drop of the links to the desktop: - _enableDragToDesktop: function () { - var link = $(this), - url = link.prop('href'), - name = link.prop('download'), - type = 'application/octet-stream'; - link.bind('dragstart', function (e) { - try { - e.originalEvent.dataTransfer.setData( - 'DownloadURL', - [type, name, url].join(':') - ); - } catch (err) {} - }); - }, - - _adjustMaxNumberOfFiles: function (operand) { - if (typeof this.options.maxNumberOfFiles === 'number') { - this.options.maxNumberOfFiles += operand; - if (this.options.maxNumberOfFiles < 1) { - this._disableFileInputButton(); - } else { - this._enableFileInputButton(); - } - } - }, - - _formatFileSize: function (bytes) { - if (typeof bytes !== 'number') { - return ''; - } - if (bytes >= 1000000000) { - return (bytes / 1000000000).toFixed(2) + ' GB'; - } - if (bytes >= 1000000) { - return (bytes / 1000000).toFixed(2) + ' MB'; - } - return (bytes / 1000).toFixed(2) + ' KB'; - }, - - _formatBitrate: function (bits) { - if (typeof bits !== 'number') { - return ''; - } - if (bits >= 1000000000) { - return (bits / 1000000000).toFixed(2) + ' Gbit/s'; - } - if (bits >= 1000000) { - return (bits / 1000000).toFixed(2) + ' Mbit/s'; - } - if (bits >= 1000) { - return (bits / 1000).toFixed(2) + ' kbit/s'; - } - return bits + ' bit/s'; - }, - - _formatTime: function (seconds) { - var date = new Date(seconds * 1000), - days = parseInt(seconds / 86400, 10); - days = days ? days + 'd ' : ''; - return days + - ('0' + date.getUTCHours()).slice(-2) + ':' + - ('0' + date.getUTCMinutes()).slice(-2) + ':' + - ('0' + date.getUTCSeconds()).slice(-2); - }, - - _formatPercentage: function (floatValue) { - return (floatValue * 100).toFixed(2) + ' %'; - }, - - _renderExtendedProgress: function (data) { - return this._formatBitrate(data.bitrate) + ' | ' + - this._formatTime( - (data.total - data.loaded) * 8 / data.bitrate - ) + ' | ' + - this._formatPercentage( - data.loaded / data.total - ) + ' | ' + - this._formatFileSize(data.loaded) + ' / ' + - this._formatFileSize(data.total); - }, - - _hasError: function (file) { - if (file.error) { - return file.error; - } - // The number of added files is subtracted from - // maxNumberOfFiles before validation, so we check if - // maxNumberOfFiles is below 0 (instead of below 1): - if (this.options.maxNumberOfFiles < 0) { - return 'maxNumberOfFiles'; - } - // Files are accepted if either the file type or the file name - // matches against the acceptFileTypes regular expression, as - // only browsers with support for the File API report the type: - if (!(this.options.acceptFileTypes.test(file.type) || - this.options.acceptFileTypes.test(file.name))) { - return 'acceptFileTypes'; - } - if (this.options.maxFileSize && - file.size > this.options.maxFileSize) { - return 'maxFileSize'; - } - if (typeof file.size === 'number' && - file.size < this.options.minFileSize) { - return 'minFileSize'; - } - return null; - }, - - _validate: function (files) { - var that = this, - valid = !!files.length; - $.each(files, function (index, file) { - file.error = that._hasError(file); - if (file.error) { - valid = false; - } - }); - return valid; - }, - - _renderTemplate: function (func, files) { - if (!func) { - return $(); - } - var result = func({ - files: files, - formatFileSize: this._formatFileSize, - options: this.options - }); - if (result instanceof $) { - return result; - } - return $(this.options.templatesContainer).html(result).children(); - }, - - _renderPreview: function (file, node) { - var that = this, - options = this.options, - dfd = $.Deferred(); - return ((loadImage && loadImage( - file, - function (img) { - node.append(img); - that._forceReflow(node); - that._transition(node).done(function () { - dfd.resolveWith(node); - }); - if (!$.contains(document.body, node[0])) { - // If the element is not part of the DOM, - // transition events are not triggered, - // so we have to resolve manually: - dfd.resolveWith(node); - } - }, - { - maxWidth: options.previewMaxWidth, - maxHeight: options.previewMaxHeight, - canvas: options.previewAsCanvas - } - )) || dfd.resolveWith(node)) && dfd; - }, - - _renderPreviews: function (files, nodes) { - var that = this, - options = this.options; - nodes.find('.preview span').each(function (index, element) { - var file = files[index]; - if (options.previewSourceFileTypes.test(file.type) && - ($.type(options.previewSourceMaxFileSize) !== 'number' || - file.size < options.previewSourceMaxFileSize)) { - that._processingQueue = that._processingQueue.pipe(function () { - var dfd = $.Deferred(); - that._renderPreview(file, $(element)).done( - function () { - dfd.resolveWith(that); - } - ); - return dfd.promise(); - }); - } - }); - return this._processingQueue; - }, - - _renderUpload: function (files) { - return this._renderTemplate( - this.options.uploadTemplate, - files - ); - }, - - _renderDownload: function (files) { - return this._renderTemplate( - this.options.downloadTemplate, - files - ).find('a[download]').each(this._enableDragToDesktop).end(); - }, - - _startHandler: function (e) { - e.preventDefault(); - var button = $(this), - template = button.closest('.template-upload'), - data = template.data('data'); - if (data && data.submit && !data.jqXHR && data.submit()) { - button.prop('disabled', true); - } - }, - - _cancelHandler: function (e) { - e.preventDefault(); - var template = $(this).closest('.template-upload'), - data = template.data('data') || {}; - if (!data.jqXHR) { - data.errorThrown = 'abort'; - e.data.fileupload._trigger('fail', e, data); - } else { - data.jqXHR.abort(); - } - }, - - _deleteHandler: function (e) { - e.preventDefault(); - var button = $(this); - e.data.fileupload._trigger('destroy', e, { - context: button.closest('.template-download'), - url: button.attr('data-url'), - type: button.attr('data-type') || 'DELETE', - dataType: e.data.fileupload.options.dataType - }); - }, - - _forceReflow: function (node) { - return $.support.transition && node.length && - node[0].offsetWidth; - }, - - _transition: function (node) { - var dfd = $.Deferred(); - if ($.support.transition && node.hasClass('fade')) { - node.bind( - $.support.transition.end, - function (e) { - // Make sure we don't respond to other transitions events - // in the container element, e.g. from button elements: - if (e.target === node[0]) { - node.unbind($.support.transition.end); - dfd.resolveWith(node); - } - } - ).toggleClass('in'); - } else { - node.toggleClass('in'); - dfd.resolveWith(node); - } - return dfd; - }, - - _initButtonBarEventHandlers: function () { - var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'), - filesList = this.options.filesContainer, - ns = this.options.namespace; - fileUploadButtonBar.find('.start') - .bind('click.' + ns, function (e) { - e.preventDefault(); - filesList.find('.start button').click(); - }); - fileUploadButtonBar.find('.cancel') - .bind('click.' + ns, function (e) { - e.preventDefault(); - filesList.find('.cancel button').click(); - }); - fileUploadButtonBar.find('.delete') - .bind('click.' + ns, function (e) { - e.preventDefault(); - filesList.find('.delete input:checked') - .siblings('button').click(); - fileUploadButtonBar.find('.toggle') - .prop('checked', false); - }); - fileUploadButtonBar.find('.toggle') - .bind('change.' + ns, function (e) { - filesList.find('.delete input').prop( - 'checked', - $(this).is(':checked') - ); - }); - }, - - _destroyButtonBarEventHandlers: function () { - this.element.find('.fileupload-buttonbar button') - .unbind('click.' + this.options.namespace); - this.element.find('.fileupload-buttonbar .toggle') - .unbind('change.' + this.options.namespace); - }, - - _initEventHandlers: function () { - parentWidget.prototype._initEventHandlers.call(this); - var eventData = {fileupload: this}; - this.options.filesContainer - .delegate( - '.start button', - 'click.' + this.options.namespace, - eventData, - this._startHandler - ) - .delegate( - '.cancel button', - 'click.' + this.options.namespace, - eventData, - this._cancelHandler - ) - .delegate( - '.delete button', - 'click.' + this.options.namespace, - eventData, - this._deleteHandler - ); - this._initButtonBarEventHandlers(); - }, - - _destroyEventHandlers: function () { - var options = this.options; - this._destroyButtonBarEventHandlers(); - options.filesContainer - .undelegate('.start button', 'click.' + options.namespace) - .undelegate('.cancel button', 'click.' + options.namespace) - .undelegate('.delete button', 'click.' + options.namespace); - parentWidget.prototype._destroyEventHandlers.call(this); - }, - - _enableFileInputButton: function () { - this.element.find('.fileinput-button input') - .prop('disabled', false) - .parent().removeClass('disabled'); - }, - - _disableFileInputButton: function () { - this.element.find('.fileinput-button input') - .prop('disabled', true) - .parent().addClass('disabled'); - }, - - _initTemplates: function () { - var options = this.options; - options.templatesContainer = document.createElement( - options.filesContainer.prop('nodeName') - ); - if (tmpl) { - if (options.uploadTemplateId) { - options.uploadTemplate = tmpl(options.uploadTemplateId); - } - if (options.downloadTemplateId) { - options.downloadTemplate = tmpl(options.downloadTemplateId); - } - } - }, - - _initFilesContainer: function () { - var options = this.options; - if (options.filesContainer === undefined) { - options.filesContainer = this.element.find('.files'); - } else if (!(options.filesContainer instanceof $)) { - options.filesContainer = $(options.filesContainer); - } - }, - - _stringToRegExp: function (str) { - var parts = str.split('/'), - modifiers = parts.pop(); - parts.shift(); - return new RegExp(parts.join('/'), modifiers); - }, - - _initRegExpOptions: function () { - var options = this.options; - if ($.type(options.acceptFileTypes) === 'string') { - options.acceptFileTypes = this._stringToRegExp( - options.acceptFileTypes - ); - } - if ($.type(options.previewSourceFileTypes) === 'string') { - options.previewSourceFileTypes = this._stringToRegExp( - options.previewSourceFileTypes - ); - } - }, - - _initSpecialOptions: function () { - parentWidget.prototype._initSpecialOptions.call(this); - this._initFilesContainer(); - this._initTemplates(); - this._initRegExpOptions(); - }, - - _create: function () { - parentWidget.prototype._create.call(this); - this._refreshOptionsList.push( - 'filesContainer', - 'uploadTemplateId', - 'downloadTemplateId' - ); - if (!$.blueimpFP) { - this._processingQueue = $.Deferred().resolveWith(this).promise(); - this.process = function () { - return this._processingQueue; - }; - } - }, - - enable: function () { - parentWidget.prototype.enable.call(this); - this.element.find('input, button').prop('disabled', false); - this._enableFileInputButton(); - }, - - disable: function () { - this.element.find('input, button').prop('disabled', true); - this._disableFileInputButton(); - parentWidget.prototype.disable.call(this); - } - - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload.js deleted file mode 100644 index 4bbd287295a..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload.js +++ /dev/null @@ -1,972 +0,0 @@ -/* - * jQuery File Upload Plugin 5.13 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global define, window, document, Blob, FormData, location */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define([ - 'jquery', - 'jquery.ui.widget' - ], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - - // The FileReader API is not actually used, but works as feature detection, - // as e.g. Safari supports XHR file uploads via the FormData API, - // but not non-multipart XHR file uploads: - $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); - $.support.xhrFormDataFileUpload = !!window.FormData; - - // The fileupload widget listens for change events on file input fields defined - // via fileInput setting and paste or drop events of the given dropZone. - // In addition to the default jQuery Widget methods, the fileupload widget - // exposes the "add" and "send" methods, to add or directly send files using - // the fileupload API. - // By default, files added via file input selection, paste, drag & drop or - // "add" method are uploaded immediately, but it is possible to override - // the "add" callback option to queue file uploads. - $.widget('blueimp.fileupload', { - - options: { - // The namespace used for event handler binding on the dropZone and - // fileInput collections. - // If not set, the name of the widget ("fileupload") is used. - namespace: undefined, - // The drop target collection, by the default the complete document. - // Set to null or an empty collection to disable drag & drop support: - dropZone: $(document), - // The file input field collection, that is listened for change events. - // If undefined, it is set to the file input fields inside - // of the widget element on plugin initialization. - // Set to null or an empty collection to disable the change listener. - fileInput: undefined, - // By default, the file input field is replaced with a clone after - // each input field change event. This is required for iframe transport - // queues and allows change events to be fired for the same file - // selection, but can be disabled by setting the following option to false: - replaceFileInput: true, - // The parameter name for the file form data (the request argument name). - // If undefined or empty, the name property of the file input field is - // used, or "files[]" if the file input name property is also empty, - // can be a string or an array of strings: - paramName: undefined, - // By default, each file of a selection is uploaded using an individual - // request for XHR type uploads. Set to false to upload file - // selections in one request each: - singleFileUploads: true, - // To limit the number of files uploaded with one XHR request, - // set the following option to an integer greater than 0: - limitMultiFileUploads: undefined, - // Set the following option to true to issue all file upload requests - // in a sequential order: - sequentialUploads: false, - // To limit the number of concurrent uploads, - // set the following option to an integer greater than 0: - limitConcurrentUploads: undefined, - // Set the following option to true to force iframe transport uploads: - forceIframeTransport: false, - // Set the following option to the location of a redirect url on the - // origin server, for cross-domain iframe transport uploads: - redirect: undefined, - // The parameter name for the redirect url, sent as part of the form - // data and set to 'redirect' if this option is empty: - redirectParamName: undefined, - // Set the following option to the location of a postMessage window, - // to enable postMessage transport uploads: - postMessage: undefined, - // By default, XHR file uploads are sent as multipart/form-data. - // The iframe transport is always using multipart/form-data. - // Set to false to enable non-multipart XHR uploads: - multipart: true, - // To upload large files in smaller chunks, set the following option - // to a preferred maximum chunk size. If set to 0, null or undefined, - // or the browser does not support the required Blob API, files will - // be uploaded as a whole. - maxChunkSize: undefined, - // When a non-multipart upload or a chunked multipart upload has been - // aborted, this option can be used to resume the upload by setting - // it to the size of the already uploaded bytes. This option is most - // useful when modifying the options object inside of the "add" or - // "send" callbacks, as the options are cloned for each file upload. - uploadedBytes: undefined, - // By default, failed (abort or error) file uploads are removed from the - // global progress calculation. Set the following option to false to - // prevent recalculating the global progress data: - recalculateProgress: true, - // Interval in milliseconds to calculate and trigger progress events: - progressInterval: 100, - // Interval in milliseconds to calculate progress bitrate: - bitrateInterval: 500, - - // Additional form data to be sent along with the file uploads can be set - // using this option, which accepts an array of objects with name and - // value properties, a function returning such an array, a FormData - // object (for XHR file uploads), or a simple object. - // The form of the first fileInput is given as parameter to the function: - formData: function (form) { - return form.serializeArray(); - }, - - // The add callback is invoked as soon as files are added to the fileupload - // widget (via file input selection, drag & drop, paste or add API call). - // If the singleFileUploads option is enabled, this callback will be - // called once for each file in the selection for XHR file uplaods, else - // once for each file selection. - // The upload starts when the submit method is invoked on the data parameter. - // The data object contains a files property holding the added files - // and allows to override plugin options as well as define ajax settings. - // Listeners for this callback can also be bound the following way: - // .bind('fileuploadadd', func); - // data.submit() returns a Promise object and allows to attach additional - // handlers using jQuery's Deferred callbacks: - // data.submit().done(func).fail(func).always(func); - add: function (e, data) { - data.submit(); - }, - - // Other callbacks: - // Callback for the submit event of each file upload: - // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); - // Callback for the start of each file upload request: - // send: function (e, data) {}, // .bind('fileuploadsend', func); - // Callback for successful uploads: - // done: function (e, data) {}, // .bind('fileuploaddone', func); - // Callback for failed (abort or error) uploads: - // fail: function (e, data) {}, // .bind('fileuploadfail', func); - // Callback for completed (success, abort or error) requests: - // always: function (e, data) {}, // .bind('fileuploadalways', func); - // Callback for upload progress events: - // progress: function (e, data) {}, // .bind('fileuploadprogress', func); - // Callback for global upload progress events: - // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); - // Callback for uploads start, equivalent to the global ajaxStart event: - // start: function (e) {}, // .bind('fileuploadstart', func); - // Callback for uploads stop, equivalent to the global ajaxStop event: - // stop: function (e) {}, // .bind('fileuploadstop', func); - // Callback for change events of the fileInput collection: - // change: function (e, data) {}, // .bind('fileuploadchange', func); - // Callback for paste events to the dropZone collection: - // paste: function (e, data) {}, // .bind('fileuploadpaste', func); - // Callback for drop events of the dropZone collection: - // drop: function (e, data) {}, // .bind('fileuploaddrop', func); - // Callback for dragover events of the dropZone collection: - // dragover: function (e) {}, // .bind('fileuploaddragover', func); - - // The plugin options are used as settings object for the ajax calls. - // The following are jQuery ajax settings required for the file uploads: - processData: false, - contentType: false, - cache: false - }, - - // A list of options that require a refresh after assigning a new value: - _refreshOptionsList: [ - 'namespace', - 'dropZone', - 'fileInput', - 'multipart', - 'forceIframeTransport' - ], - - _BitrateTimer: function () { - this.timestamp = +(new Date()); - this.loaded = 0; - this.bitrate = 0; - this.getBitrate = function (now, loaded, interval) { - var timeDiff = now - this.timestamp; - if (!this.bitrate || !interval || timeDiff > interval) { - this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; - this.loaded = loaded; - this.timestamp = now; - } - return this.bitrate; - }; - }, - - _isXHRUpload: function (options) { - return !options.forceIframeTransport && - ((!options.multipart && $.support.xhrFileUpload) || - $.support.xhrFormDataFileUpload); - }, - - _getFormData: function (options) { - var formData; - if (typeof options.formData === 'function') { - return options.formData(options.form); - } - if ($.isArray(options.formData)) { - return options.formData; - } - if (options.formData) { - formData = []; - $.each(options.formData, function (name, value) { - formData.push({name: name, value: value}); - }); - return formData; - } - return []; - }, - - _getTotal: function (files) { - var total = 0; - $.each(files, function (index, file) { - total += file.size || 1; - }); - return total; - }, - - _onProgress: function (e, data) { - if (e.lengthComputable) { - var now = +(new Date()), - total, - loaded; - if (data._time && data.progressInterval && - (now - data._time < data.progressInterval) && - e.loaded !== e.total) { - return; - } - data._time = now; - total = data.total || this._getTotal(data.files); - loaded = parseInt( - e.loaded / e.total * (data.chunkSize || total), - 10 - ) + (data.uploadedBytes || 0); - this._loaded += loaded - (data.loaded || data.uploadedBytes || 0); - data.lengthComputable = true; - data.loaded = loaded; - data.total = total; - data.bitrate = data._bitrateTimer.getBitrate( - now, - loaded, - data.bitrateInterval - ); - // Trigger a custom progress event with a total data property set - // to the file size(s) of the current upload and a loaded data - // property calculated accordingly: - this._trigger('progress', e, data); - // Trigger a global progress event for all current file uploads, - // including ajax calls queued for sequential file uploads: - this._trigger('progressall', e, { - lengthComputable: true, - loaded: this._loaded, - total: this._total, - bitrate: this._bitrateTimer.getBitrate( - now, - this._loaded, - data.bitrateInterval - ) - }); - } - }, - - _initProgressListener: function (options) { - var that = this, - xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); - // Accesss to the native XHR object is required to add event listeners - // for the upload progress event: - if (xhr.upload) { - $(xhr.upload).bind('progress', function (e) { - var oe = e.originalEvent; - // Make sure the progress event properties get copied over: - e.lengthComputable = oe.lengthComputable; - e.loaded = oe.loaded; - e.total = oe.total; - that._onProgress(e, options); - }); - options.xhr = function () { - return xhr; - }; - } - }, - - _initXHRData: function (options) { - var formData, - file = options.files[0], - // Ignore non-multipart setting if not supported: - multipart = options.multipart || !$.support.xhrFileUpload, - paramName = options.paramName[0]; - if (!multipart || options.blob) { - // For non-multipart uploads and chunked uploads, - // file meta data is not part of the request body, - // so we transmit this data as part of the HTTP headers. - // For cross domain requests, these headers must be allowed - // via Access-Control-Allow-Headers or removed using - // the beforeSend callback: - options.headers = $.extend(options.headers, { - 'X-File-Name': file.name, - 'X-File-Type': file.type, - 'X-File-Size': file.size - }); - if (!options.blob) { - // Non-chunked non-multipart upload: - options.contentType = file.type; - options.data = file; - } else if (!multipart) { - // Chunked non-multipart upload: - options.contentType = 'application/octet-stream'; - options.data = options.blob; - } - } - if (multipart && $.support.xhrFormDataFileUpload) { - if (options.postMessage) { - // window.postMessage does not allow sending FormData - // objects, so we just add the File/Blob objects to - // the formData array and let the postMessage window - // create the FormData object out of this array: - formData = this._getFormData(options); - if (options.blob) { - formData.push({ - name: paramName, - value: options.blob - }); - } else { - $.each(options.files, function (index, file) { - formData.push({ - name: options.paramName[index] || paramName, - value: file - }); - }); - } - } else { - if (options.formData instanceof FormData) { - formData = options.formData; - } else { - formData = new FormData(); - $.each(this._getFormData(options), function (index, field) { - formData.append(field.name, field.value); - }); - } - if (options.blob) { - formData.append(paramName, options.blob, file.name); - } else { - $.each(options.files, function (index, file) { - // File objects are also Blob instances. - // This check allows the tests to run with - // dummy objects: - if (file instanceof Blob) { - formData.append( - options.paramName[index] || paramName, - file, - file.name - ); - } - }); - } - } - options.data = formData; - } - // Blob reference is not needed anymore, free memory: - options.blob = null; - }, - - _initIframeSettings: function (options) { - // Setting the dataType to iframe enables the iframe transport: - options.dataType = 'iframe ' + (options.dataType || ''); - // The iframe transport accepts a serialized array as form data: - options.formData = this._getFormData(options); - // Add redirect url to form data on cross-domain uploads: - if (options.redirect && $('').prop('href', options.url) - .prop('host') !== location.host) { - options.formData.push({ - name: options.redirectParamName || 'redirect', - value: options.redirect - }); - } - }, - - _initDataSettings: function (options) { - if (this._isXHRUpload(options)) { - if (!this._chunkedUpload(options, true)) { - if (!options.data) { - this._initXHRData(options); - } - this._initProgressListener(options); - } - if (options.postMessage) { - // Setting the dataType to postmessage enables the - // postMessage transport: - options.dataType = 'postmessage ' + (options.dataType || ''); - } - } else { - this._initIframeSettings(options, 'iframe'); - } - }, - - _getParamName: function (options) { - var fileInput = $(options.fileInput), - paramName = options.paramName; - if (!paramName) { - paramName = []; - fileInput.each(function () { - var input = $(this), - name = input.prop('name') || 'files[]', - i = (input.prop('files') || [1]).length; - while (i) { - paramName.push(name); - i -= 1; - } - }); - if (!paramName.length) { - paramName = [fileInput.prop('name') || 'files[]']; - } - } else if (!$.isArray(paramName)) { - paramName = [paramName]; - } - return paramName; - }, - - _initFormSettings: function (options) { - // Retrieve missing options from the input field and the - // associated form, if available: - if (!options.form || !options.form.length) { - options.form = $(options.fileInput.prop('form')); - } - options.paramName = this._getParamName(options); - if (!options.url) { - options.url = options.form.prop('action') || location.href; - } - // The HTTP request method must be "POST" or "PUT": - options.type = (options.type || options.form.prop('method') || '') - .toUpperCase(); - if (options.type !== 'POST' && options.type !== 'PUT') { - options.type = 'POST'; - } - }, - - _getAJAXSettings: function (data) { - var options = $.extend({}, this.options, data); - this._initFormSettings(options); - this._initDataSettings(options); - return options; - }, - - // Maps jqXHR callbacks to the equivalent - // methods of the given Promise object: - _enhancePromise: function (promise) { - promise.success = promise.done; - promise.error = promise.fail; - promise.complete = promise.always; - return promise; - }, - - // Creates and returns a Promise object enhanced with - // the jqXHR methods abort, success, error and complete: - _getXHRPromise: function (resolveOrReject, context, args) { - var dfd = $.Deferred(), - promise = dfd.promise(); - context = context || this.options.context || promise; - if (resolveOrReject === true) { - dfd.resolveWith(context, args); - } else if (resolveOrReject === false) { - dfd.rejectWith(context, args); - } - promise.abort = dfd.promise; - return this._enhancePromise(promise); - }, - - // Uploads a file in multiple, sequential requests - // by splitting the file up in multiple blob chunks. - // If the second parameter is true, only tests if the file - // should be uploaded in chunks, but does not invoke any - // upload requests: - _chunkedUpload: function (options, testOnly) { - var that = this, - file = options.files[0], - fs = file.size, - ub = options.uploadedBytes = options.uploadedBytes || 0, - mcs = options.maxChunkSize || fs, - // Use the Blob methods with the slice implementation - // according to the W3C Blob API specification: - slice = file.webkitSlice || file.mozSlice || file.slice, - upload, - n, - jqXHR, - pipe; - if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || - options.data) { - return false; - } - if (testOnly) { - return true; - } - if (ub >= fs) { - file.error = 'uploadedBytes'; - return this._getXHRPromise( - false, - options.context, - [null, 'error', file.error] - ); - } - // n is the number of blobs to upload, - // calculated via filesize, uploaded bytes and max chunk size: - n = Math.ceil((fs - ub) / mcs); - // The chunk upload method accepting the chunk number as parameter: - upload = function (i) { - if (!i) { - return that._getXHRPromise(true, options.context); - } - // Upload the blobs in sequential order: - return upload(i -= 1).pipe(function () { - // Clone the options object for each chunk upload: - var o = $.extend({}, options); - o.blob = slice.call( - file, - ub + i * mcs, - ub + (i + 1) * mcs - ); - // Expose the chunk index: - o.chunkIndex = i; - // Expose the number of chunks: - o.chunksNumber = n; - // Store the current chunk size, as the blob itself - // will be dereferenced after data processing: - o.chunkSize = o.blob.size; - // Process the upload data (the blob and potential form data): - that._initXHRData(o); - // Add progress listeners for this chunk upload: - that._initProgressListener(o); - jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context)) - .done(function () { - // Create a progress event if upload is done and - // no progress event has been invoked for this chunk: - if (!o.loaded) { - that._onProgress($.Event('progress', { - lengthComputable: true, - loaded: o.chunkSize, - total: o.chunkSize - }), o); - } - options.uploadedBytes = o.uploadedBytes += - o.chunkSize; - }); - return jqXHR; - }); - }; - // Return the piped Promise object, enhanced with an abort method, - // which is delegated to the jqXHR object of the current upload, - // and jqXHR callbacks mapped to the equivalent Promise methods: - pipe = upload(n); - pipe.abort = function () { - return jqXHR.abort(); - }; - return this._enhancePromise(pipe); - }, - - _beforeSend: function (e, data) { - if (this._active === 0) { - // the start callback is triggered when an upload starts - // and no other uploads are currently running, - // equivalent to the global ajaxStart event: - this._trigger('start'); - // Set timer for global bitrate progress calculation: - this._bitrateTimer = new this._BitrateTimer(); - } - this._active += 1; - // Initialize the global progress values: - this._loaded += data.uploadedBytes || 0; - this._total += this._getTotal(data.files); - }, - - _onDone: function (result, textStatus, jqXHR, options) { - if (!this._isXHRUpload(options)) { - // Create a progress event for each iframe load: - this._onProgress($.Event('progress', { - lengthComputable: true, - loaded: 1, - total: 1 - }), options); - } - options.result = result; - options.textStatus = textStatus; - options.jqXHR = jqXHR; - this._trigger('done', null, options); - }, - - _onFail: function (jqXHR, textStatus, errorThrown, options) { - options.jqXHR = jqXHR; - options.textStatus = textStatus; - options.errorThrown = errorThrown; - this._trigger('fail', null, options); - if (options.recalculateProgress) { - // Remove the failed (error or abort) file upload from - // the global progress calculation: - this._loaded -= options.loaded || options.uploadedBytes || 0; - this._total -= options.total || this._getTotal(options.files); - } - }, - - _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { - this._active -= 1; - options.textStatus = textStatus; - if (jqXHRorError && jqXHRorError.always) { - options.jqXHR = jqXHRorError; - options.result = jqXHRorResult; - } else { - options.jqXHR = jqXHRorResult; - options.errorThrown = jqXHRorError; - } - this._trigger('always', null, options); - if (this._active === 0) { - // The stop callback is triggered when all uploads have - // been completed, equivalent to the global ajaxStop event: - this._trigger('stop'); - // Reset the global progress values: - this._loaded = this._total = 0; - this._bitrateTimer = null; - } - }, - - _onSend: function (e, data) { - var that = this, - jqXHR, - slot, - pipe, - options = that._getAJAXSettings(data), - send = function (resolve, args) { - that._sending += 1; - // Set timer for bitrate progress calculation: - options._bitrateTimer = new that._BitrateTimer(); - jqXHR = jqXHR || ( - (resolve !== false && - that._trigger('send', e, options) !== false && - (that._chunkedUpload(options) || $.ajax(options))) || - that._getXHRPromise(false, options.context, args) - ).done(function (result, textStatus, jqXHR) { - that._onDone(result, textStatus, jqXHR, options); - }).fail(function (jqXHR, textStatus, errorThrown) { - that._onFail(jqXHR, textStatus, errorThrown, options); - }).always(function (jqXHRorResult, textStatus, jqXHRorError) { - that._sending -= 1; - that._onAlways( - jqXHRorResult, - textStatus, - jqXHRorError, - options - ); - if (options.limitConcurrentUploads && - options.limitConcurrentUploads > that._sending) { - // Start the next queued upload, - // that has not been aborted: - var nextSlot = that._slots.shift(); - while (nextSlot) { - if (!nextSlot.isRejected()) { - nextSlot.resolve(); - break; - } - nextSlot = that._slots.shift(); - } - } - }); - return jqXHR; - }; - this._beforeSend(e, options); - if (this.options.sequentialUploads || - (this.options.limitConcurrentUploads && - this.options.limitConcurrentUploads <= this._sending)) { - if (this.options.limitConcurrentUploads > 1) { - slot = $.Deferred(); - this._slots.push(slot); - pipe = slot.pipe(send); - } else { - pipe = (this._sequence = this._sequence.pipe(send, send)); - } - // Return the piped Promise object, enhanced with an abort method, - // which is delegated to the jqXHR object of the current upload, - // and jqXHR callbacks mapped to the equivalent Promise methods: - pipe.abort = function () { - var args = [undefined, 'abort', 'abort']; - if (!jqXHR) { - if (slot) { - slot.rejectWith(args); - } - return send(false, args); - } - return jqXHR.abort(); - }; - return this._enhancePromise(pipe); - } - return send(); - }, - - _onAdd: function (e, data) { - var that = this, - result = true, - options = $.extend({}, this.options, data), - limit = options.limitMultiFileUploads, - paramName = this._getParamName(options), - paramNameSet, - paramNameSlice, - fileSet, - i; - if (!(options.singleFileUploads || limit) || - !this._isXHRUpload(options)) { - fileSet = [data.files]; - paramNameSet = [paramName]; - } else if (!options.singleFileUploads && limit) { - fileSet = []; - paramNameSet = []; - for (i = 0; i < data.files.length; i += limit) { - fileSet.push(data.files.slice(i, i + limit)); - paramNameSlice = paramName.slice(i, i + limit); - if (!paramNameSlice.length) { - paramNameSlice = paramName; - } - paramNameSet.push(paramNameSlice); - } - } else { - paramNameSet = paramName; - } - data.originalFiles = data.files; - $.each(fileSet || data.files, function (index, element) { - var newData = $.extend({}, data); - newData.files = fileSet ? element : [element]; - newData.paramName = paramNameSet[index]; - newData.submit = function () { - newData.jqXHR = this.jqXHR = - (that._trigger('submit', e, this) !== false) && - that._onSend(e, this); - return this.jqXHR; - }; - return (result = that._trigger('add', e, newData)); - }); - return result; - }, - - // File Normalization for Gecko 1.9.1 (Firefox 3.5) support: - _normalizeFile: function (index, file) { - if (file.name === undefined && file.size === undefined) { - file.name = file.fileName; - file.size = file.fileSize; - } - }, - - _replaceFileInput: function (input) { - var inputClone = input.clone(true); - $('
').append(inputClone)[0].reset(); - // Detaching allows to insert the fileInput on another form - // without loosing the file input value: - input.after(inputClone).detach(); - // Avoid memory leaks with the detached file input: - $.cleanData(input.unbind('remove')); - // Replace the original file input element in the fileInput - // collection with the clone, which has been copied including - // event handlers: - this.options.fileInput = this.options.fileInput.map(function (i, el) { - if (el === input[0]) { - return inputClone[0]; - } - return el; - }); - // If the widget has been initialized on the file input itself, - // override this.element with the file input clone: - if (input[0] === this.element[0]) { - this.element = inputClone; - } - }, - - _getFileInputFiles: function (fileInput) { - fileInput = $(fileInput); - var files = $.each($.makeArray(fileInput.prop('files')), this._normalizeFile), - value; - if (!files.length) { - value = fileInput.prop('value'); - if (!value) { - return []; - } - // If the files property is not available, the browser does not - // support the File API and we add a pseudo File object with - // the input value as name with path information removed: - files = [{name: value.replace(/^.*\\/, '')}]; - } - return files; - }, - - _onChange: function (e) { - var that = e.data.fileupload, - data = { - fileInput: $(e.target), - form: $(e.target.form) - }; - data.files = that._getFileInputFiles(data.fileInput); - if (that.options.replaceFileInput) { - that._replaceFileInput(data.fileInput); - } - if (that._trigger('change', e, data) === false || - that._onAdd(e, data) === false) { - return false; - } - }, - - _onPaste: function (e) { - var that = e.data.fileupload, - cbd = e.originalEvent.clipboardData, - items = (cbd && cbd.items) || [], - data = {files: []}; - $.each(items, function (index, item) { - var file = item.getAsFile && item.getAsFile(); - if (file) { - data.files.push(file); - } - }); - if (that._trigger('paste', e, data) === false || - that._onAdd(e, data) === false) { - return false; - } - }, - - _onDrop: function (e) { - var that = e.data.fileupload, - dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer, - data = { - files: $.each( - $.makeArray(dataTransfer && dataTransfer.files), - that._normalizeFile - ) - }; - if (that._trigger('drop', e, data) === false || - that._onAdd(e, data) === false) { - return false; - } - e.preventDefault(); - }, - - _onDragOver: function (e) { - var that = e.data.fileupload, - dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer; - if (that._trigger('dragover', e) === false) { - return false; - } - if (dataTransfer) { - dataTransfer.dropEffect = 'copy'; - } - e.preventDefault(); - }, - - _initEventHandlers: function () { - var ns = this.options.namespace; - if (this._isXHRUpload(this.options)) { - this.options.dropZone - .bind('dragover.' + ns, {fileupload: this}, this._onDragOver) - .bind('drop.' + ns, {fileupload: this}, this._onDrop) - .bind('paste.' + ns, {fileupload: this}, this._onPaste); - } - this.options.fileInput - .bind('change.' + ns, {fileupload: this}, this._onChange); - }, - - _destroyEventHandlers: function () { - var ns = this.options.namespace; - this.options.dropZone - .unbind('dragover.' + ns, this._onDragOver) - .unbind('drop.' + ns, this._onDrop) - .unbind('paste.' + ns, this._onPaste); - this.options.fileInput - .unbind('change.' + ns, this._onChange); - }, - - _setOption: function (key, value) { - var refresh = $.inArray(key, this._refreshOptionsList) !== -1; - if (refresh) { - this._destroyEventHandlers(); - } - $.Widget.prototype._setOption.call(this, key, value); - if (refresh) { - this._initSpecialOptions(); - this._initEventHandlers(); - } - }, - - _initSpecialOptions: function () { - var options = this.options; - if (options.fileInput === undefined) { - options.fileInput = this.element.is('input:file') ? - this.element : this.element.find('input:file'); - } else if (!(options.fileInput instanceof $)) { - options.fileInput = $(options.fileInput); - } - if (!(options.dropZone instanceof $)) { - options.dropZone = $(options.dropZone); - } - }, - - _create: function () { - var options = this.options; - // Initialize options set via HTML5 data-attributes: - $.extend(options, $(this.element[0].cloneNode(false)).data()); - options.namespace = options.namespace || this.widgetName; - this._initSpecialOptions(); - this._slots = []; - this._sequence = this._getXHRPromise(true); - this._sending = this._active = this._loaded = this._total = 0; - this._initEventHandlers(); - }, - - destroy: function () { - this._destroyEventHandlers(); - $.Widget.prototype.destroy.call(this); - }, - - enable: function () { - $.Widget.prototype.enable.call(this); - this._initEventHandlers(); - }, - - disable: function () { - this._destroyEventHandlers(); - $.Widget.prototype.disable.call(this); - }, - - // This method is exposed to the widget API and allows adding files - // using the fileupload API. The data parameter accepts an object which - // must have a files property and can contain additional options: - // .fileupload('add', {files: filesList}); - add: function (data) { - if (!data || this.options.disabled) { - return; - } - if (data.fileInput && !data.files) { - data.files = this._getFileInputFiles(data.fileInput); - } else { - data.files = $.each($.makeArray(data.files), this._normalizeFile); - } - this._onAdd(null, data); - }, - - // This method is exposed to the widget API and allows sending files - // using the fileupload API. The data parameter accepts an object which - // must have a files property and can contain additional options: - // .fileupload('send', {files: filesList}); - // The method returns a Promise object for the file upload call. - send: function (data) { - if (data && !this.options.disabled) { - if (data.fileInput && !data.files) { - data.files = this._getFileInputFiles(data.fileInput); - } else { - data.files = $.each($.makeArray(data.files), this._normalizeFile); - } - if (data.files.length) { - return this._onSend(null, data); - } - } - return this._getXHRPromise(false, data && data.context); - } - - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.iframe-transport.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.iframe-transport.js deleted file mode 100644 index 04a56623085..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.iframe-transport.js +++ /dev/null @@ -1,171 +0,0 @@ -/* - * jQuery Iframe Transport Plugin 1.4 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint unparam: true, nomen: true */ -/*global define, window, document */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - - // Helper variable to create unique names for the transport iframes: - var counter = 0; - - // The iframe transport accepts three additional options: - // options.fileInput: a jQuery collection of file input fields - // options.paramName: the parameter name for the file form data, - // overrides the name property of the file input field(s), - // can be a string or an array of strings. - // options.formData: an array of objects with name and value properties, - // equivalent to the return data of .serializeArray(), e.g.: - // [{name: 'a', value: 1}, {name: 'b', value: 2}] - $.ajaxTransport('iframe', function (options) { - if (options.async && (options.type === 'POST' || options.type === 'GET')) { - var form, - iframe; - return { - send: function (_, completeCallback) { - form = $('
'); - // javascript:false as initial iframe src - // prevents warning popups on HTTPS in IE6. - // IE versions below IE8 cannot set the name property of - // elements that have already been added to the DOM, - // so we set the name along with the iframe HTML markup: - iframe = $( - '' - ).bind('load', function () { - var fileInputClones, - paramNames = $.isArray(options.paramName) ? - options.paramName : [options.paramName]; - iframe - .unbind('load') - .bind('load', function () { - var response; - // Wrap in a try/catch block to catch exceptions thrown - // when trying to access cross-domain iframe contents: - try { - response = iframe.contents(); - // Google Chrome and Firefox do not throw an - // exception when calling iframe.contents() on - // cross-domain requests, so we unify the response: - if (!response.length || !response[0].firstChild) { - throw new Error(); - } - } catch (e) { - response = undefined; - } - // The complete callback returns the - // iframe content document as response object: - completeCallback( - 200, - 'success', - {'iframe': response} - ); - // Fix for IE endless progress bar activity bug - // (happens on form submits to iframe targets): - $('') - .appendTo(form); - form.remove(); - }); - form - .prop('target', iframe.prop('name')) - .prop('action', options.url) - .prop('method', options.type); - if (options.formData) { - $.each(options.formData, function (index, field) { - $('') - .prop('name', field.name) - .val(field.value) - .appendTo(form); - }); - } - if (options.fileInput && options.fileInput.length && - options.type === 'POST') { - fileInputClones = options.fileInput.clone(); - // Insert a clone for each file input field: - options.fileInput.after(function (index) { - return fileInputClones[index]; - }); - if (options.paramName) { - options.fileInput.each(function (index) { - $(this).prop( - 'name', - paramNames[index] || options.paramName - ); - }); - } - // Appending the file input fields to the hidden form - // removes them from their original location: - form - .append(options.fileInput) - .prop('enctype', 'multipart/form-data') - // enctype must be set as encoding for IE: - .prop('encoding', 'multipart/form-data'); - } - form.submit(); - // Insert the file input fields at their original location - // by replacing the clones with the originals: - if (fileInputClones && fileInputClones.length) { - options.fileInput.each(function (index, input) { - var clone = $(fileInputClones[index]); - $(input).prop('name', clone.prop('name')); - clone.replaceWith(input); - }); - } - }); - form.append(iframe).appendTo(document.body); - }, - abort: function () { - if (iframe) { - // javascript:false as iframe src aborts the request - // and prevents warning popups on HTTPS in IE6. - // concat is used to avoid the "Script URL" JSLint error: - iframe - .unbind('load') - .prop('src', 'javascript'.concat(':false;')); - } - if (form) { - form.remove(); - } - } - }; - } - }); - - // The iframe transport returns the iframe content document as response. - // The following adds converters from iframe to text, json, html, and script: - $.ajaxSetup({ - converters: { - 'iframe text': function (iframe) { - return $(iframe[0].body).text(); - }, - 'iframe json': function (iframe) { - return $.parseJSON($(iframe[0].body).text()); - }, - 'iframe html': function (iframe) { - return $(iframe[0].body).html(); - }, - 'iframe script': function (iframe) { - return $.globalEval($(iframe[0].body).text()); - } - } - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/locale.js b/htdocs/includes/jquery/plugins/fileupload/js/locale.js deleted file mode 100644 index ea64b0a870f..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/locale.js +++ /dev/null @@ -1,29 +0,0 @@ -/* - * jQuery File Upload Plugin Localization Example 6.5.1 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2012, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*global window */ - -window.locale = { - "fileupload": { - "errors": { - "maxFileSize": "File is too big", - "minFileSize": "File is too small", - "acceptFileTypes": "Filetype not allowed", - "maxNumberOfFiles": "Max number of files exceeded", - "uploadedBytes": "Uploaded bytes exceed file size", - "emptyResult": "Empty file upload result" - }, - "error": "Error", - "start": "Start", - "cancel": "Cancel", - "destroy": "Delete" - } -}; diff --git a/htdocs/includes/jquery/plugins/fileupload/js/main.js b/htdocs/includes/jquery/plugins/fileupload/js/main.js deleted file mode 100644 index 67109588de3..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/main.js +++ /dev/null @@ -1,93 +0,0 @@ -/* - * jQuery File Upload Plugin JS Example 6.7 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global $, window, document */ - -$(function () { - 'use strict'; - - // Initialize the jQuery File Upload widget: - $('#fileupload').fileupload(); - - // Enable iframe cross-domain access via redirect option: - $('#fileupload').fileupload( - 'option', - 'redirect', - window.location.href.replace( - /\/[^\/]*$/, - '/cors/result.html?%s' - ) - ); - - if (window.location.hostname === 'blueimp.github.com') { - // Demo settings: - $('#fileupload').fileupload('option', { - url: '//jquery-file-upload.appspot.com/', - maxFileSize: 5000000, - acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, - process: [ - { - action: 'load', - fileTypes: /^image\/(gif|jpeg|png)$/, - maxFileSize: 20000000 // 20MB - }, - { - action: 'resize', - maxWidth: 1440, - maxHeight: 900 - }, - { - action: 'save' - } - ] - }); - // Upload server status check for browsers with CORS support: - if ($.support.cors) { - $.ajax({ - url: '//jquery-file-upload.appspot.com/', - type: 'HEAD' - }).fail(function () { - $('') - .text('Upload server currently unavailable - ' + - new Date()) - .appendTo('#fileupload'); - }); - } - } else { - // Load existing files: - $('#fileupload').each(function () { - var that = this; - $.getJSON(this.action, function (result) { - if (result && result.length) { - $(that).fileupload('option', 'done') - .call(that, null, {result: result}); - } - }); - }); - } - - // Initialize the Image Gallery widget: - $('#fileupload .files').imagegallery(); - - // Initialize the theme switcher: - $('#theme-switcher').change(function () { - var theme = $('#theme'); - theme.prop( - 'href', - theme.prop('href').replace( - /[\w\-]+\/jquery-ui.css/, - $(this).val() + '/jquery-ui.css' - ) - ); - }); - -}); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/vendor/jquery.ui.widget.js b/htdocs/includes/jquery/plugins/fileupload/js/vendor/jquery.ui.widget.js deleted file mode 100644 index 9da8673a58b..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/vendor/jquery.ui.widget.js +++ /dev/null @@ -1,282 +0,0 @@ -/* - * jQuery UI Widget 1.8.18+amd - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -(function (factory) { - if (typeof define === "function" && define.amd) { - // Register as an anonymous AMD module: - define(["jquery"], factory); - } else { - // Browser globals: - factory(jQuery); - } -}(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})); diff --git a/htdocs/includes/jquery/plugins/select2/.gitignore b/htdocs/includes/jquery/plugins/select2/.gitignore deleted file mode 100644 index c6ef2182bdc..00000000000 --- a/htdocs/includes/jquery/plugins/select2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea - diff --git a/htdocs/includes/jquery/plugins/select2/CHANGELOG.md b/htdocs/includes/jquery/plugins/select2/CHANGELOG.md new file mode 100644 index 00000000000..3ae60aff255 --- /dev/null +++ b/htdocs/includes/jquery/plugins/select2/CHANGELOG.md @@ -0,0 +1,254 @@ +# Change Log + +## 4.0.4 + +### New features / Improvements +- Make tag matching case insensitive [https://github.com/select2/select2/commit/cb9a90457867ffb14c7b1550bb67e872e0a5c2dd, https://github.com/select2/select2/commit/1167bace78cd3b1a918c1b04f3bac54674eab62b] +- Support selecting options with blank or `0` option values [https://github.com/select2/select2/commit/16b4840c0e2df0461998e3b464ee0a546173950d, https://github.com/select2/select2/commit/0358ee528765157234643d289bce6b8ca5889c72] + +### Bug fixes +- Fix issue with entire form losing focus when tabbing away from a Select2 control (#4419) +- Fix UMD support for CommonJS [https://github.com/select2/select2/commit/45a877345482956021161203ac789c25f40a7d5e] + +### Documentation +- Github Pages documentation has been deprecated, replaced with https://github.com/select2/docs +- Add django-autocomplete-light to integrations [https://github.com/select2/select2/pull/4597] +- Correct typo in options page [https://github.com/select2/select2/pull/4389] +- Correct misspelling in AJAX query parameters example [https://github.com/select2/select2/pull/4435] +- "highlight" should be "focus" in focus example [https://github.com/select2/select2/pull/4441] +- Correct misspelling in `` is now handled [https://github.com/select2/select2/commit/31e7a1d4c52ed7477769fcad5d15166ae3c9b4d0] +- Adding and removing options now refreshes the selection automatically [https://github.com/select2/select2/commit/ea79a197e0ffe55aa600eed6d18cbd1c804c3176] + +### Bug fixes +- `select2('option')` no longer mutate the arguments when working on multiple elements [https://github.com/select2/select2/commit/c2c1aeef31c95c6df5545c900a4e1782d712497c] +- Better detect aborted requests [https://github.com/select2/select2/commit/cfb66f5e4f71a56c46a6890c5dde4b7f24f11fa8] +- New options are now properly created during tokenization [https://github.com/select2/select2/commit/3b8cd2e36990e695e4cb4b966c8658e7ca1574dc] +- Fix positioning bug with non-static parents for the dropdown [https://github.com/select2/select2/pull/4267] +- Infinite scrolling no longer resets the keyboard focus [https://github.com/select2/select2/commit/e897d008a672da262ba84cee2a144578696ada29, https://github.com/select2/select2/commit/9f581285d88128b29a01fc1e5fd2d445d610b553] +- `selectOnClose` now works properly with `closeOnSelect` [https://github.com/select2/select2/commit/481c43883e23874e9c35879d173eb8cc5b994b12] +- Apply `ajax.delay` to empty search terms as well [https://github.com/select2/select2/commit/4b9e02f02211248be25ac4c16d4635cf38237bb9] + +### Documentation +- Added example for attaching event listeners [https://github.com/select2/select2/commit/84d6b5d840f7f4e6b7a2fb3f08424bf5495c876d] +- Correct link to the [Select2 Bootstrap Theme](https://github.com/select2/select2-bootstrap-theme) [https://github.com/select2/select2/pull/4318] +- Added example for using a `