diff --git a/.travis.yml b/.travis.yml index bac020e13c5..d66915eb44b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -325,18 +325,21 @@ script: set +e echo #cat $TRAVIS_BUILD_DIR/upgrade400500-2.log + #cat $TRAVIS_BUILD_DIR/upgrade500600.log + #cat $TRAVIS_BUILD_DIR/upgrade500600-2.log + #cat $TRAVIS_BUILD_DIR/upgrade500600-3.log #cat /tmp/dolibarr_install.log - | echo "Unit testing" - # Ensure we catch errors. Set this to +e if you want to go to the end to see log file. + # Ensure we catch errors. Set this to +e if you want to go to the end to see dolibarr.log file. set -e phpunit -d memory_limit=-1 -c test/phpunit/phpunittest.xml test/phpunit/AllTests.php set +e - | #echo "Output dolibarr.log" - #echo cat documents/dolibarr.log + #cat documents/dolibarr.log after_script: - | diff --git a/ChangeLog b/ChangeLog index 7823d4cefb1..9b5eef7aca5 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,6 +3,7 @@ English Dolibarr ChangeLog -------------------------------------------------------------- + ***** ChangeLog for 7.0.0 compared to 6.0.* ***** For developers: @@ -12,11 +13,51 @@ NEW: complete_head_from_modules() in ldap_prepare_head() WARNING: Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: -* The methode "cloture" on contact were renamed into "closeAll". +* The methode "cloture" on contract were renamed into "closeAll". * The substitution key for reference of object is now __REF__ whatever is the object (it replaces __ORDERREF__, __PROPALREF__, ...) +* The substition key __SIGNATURE__ was renamed into __USER_SIGNATURE__ to standardize naming conventions. +* Substitution keys with syntax %XXX% were renamed into __XXX__ to match others. +* Some REST API to access the dictionary (country, town, ...) were moved into a common API. +* Page bank/index.php and bank/bankentries.php were renamed into bank/list.php and bank/bankentries_list.php to + 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 +***** ChangeLog for 6.0.2 compared to 6.0.1 ***** +FIX: #7148 +FIX: #7288 +FIX: #7366 renaming table with pgsql +FIX: #7435 Can't add payment term +FIX: #7461 +FIX: #7464 +FIX: #7471 +FIX: #7473 Mass update of vat rates and other bugs on localtax +FIX: #7475 +FIX: #7486 Empty value for multicurrency rate must be forbidden +FIX: #7490 +FIX: #7505 +FIX: #7510 Bug: extrafield content disappear when generate pdf within intervention +FIX: #7514 +FIX: #7531 #7537 +FIX: #7541 +FIX: #7546 +FIX: #7550 +FIX: #7554 +FIX: #7567 +FIX: Accountancy export model for Agiris Isacompta +FIX: Allow create shipping if STOCK_SUPPORTS_SERVICES option is enabled +FIX: Bad preview on scroping when special file names +FIX: Generation of invoice from bulk action "Bill Orders" +FIX: Implementation of a Luracast recommandation for the REST api server (#7370) +FIX: Missing space in request +FIX: Only modified values must be modified +FIX: replenish if line test GETPOST on line 0 +FIX: Stripe not working on live mode +FIX: wrong basePath in the swagger view +FIX: Implementation of a Luracast recommandation for the REST api server + ***** ChangeLog for 6.0.1 compared to 6.0.* ***** FIX: #7000 Dashboard link for late pending payment supplier invoices do not work FIX: #7325 Default VAT rate when editing template invoices is 0% diff --git a/dev/initdata/import-thirdparties.php b/dev/initdata/import-thirdparties.php index 08ad248ecc0..0c32c7ea6a3 100755 --- a/dev/initdata/import-thirdparties.php +++ b/dev/initdata/import-thirdparties.php @@ -21,7 +21,7 @@ /** * \file dev/initdata/import-thirdparties.php - * \brief Script example to insert thirdparties from a csv file. + * \brief Script example to insert thirdparties from a csv file. * To purge data, you can have a look at purge-data.php */ @@ -123,15 +123,15 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) if ($endlinenb && $i > $endlinenb) continue; $nboflines++; - + $object = new Societe($db); $object->state = $fields[6]; $object->client = $fields[7]; $object->fournisseur = $fields[8]; - + $object->name = $fields[13]?trim($fields[13]):$fields[0]; $object->name_alias = $fields[0]!=$fields[13]?trim($fields[0]):''; - + $object->address = trim($fields[14]); $object->zip = trim($fields[15]); $object->town = trim($fields[16]); @@ -149,7 +149,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $condpayment = trim($fields[36]); if ($condpayment == 'A la commande') $condpayment = 'A réception de commande'; if ($condpayment == 'A reception facture') $condpayment = 'Réception de facture'; - $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid'); + $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1); if (empty($object->cond_reglement_id)) { print " - Error cant find payment mode for ".$condpayment."\n"; @@ -166,7 +166,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) // Set price level $object->price_level = 1; if ($labeltype == 'Revendeur') $object->price_level = 2; - + print "Process line nb ".$i.", name ".$object->name; @@ -182,7 +182,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) print " - Error in create result code = ".$ret." - ".$object->errorsToString(); $errorrecord++; } - else + else { print " - Creation OK with name ".$object->name." - id = ".$ret; } @@ -198,7 +198,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) if (! $errorrecord && $fields[3]) { $salesrep=new User($db); - + $tmp=explode(' ',$fields[3],2); $salesrep->firstname = trim($tmp[0]); $salesrep->lastname = trim($tmp[1]); @@ -206,7 +206,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) else $salesrep->login=strtolower($salesrep->firstname); $salesrep->login=preg_replace('/ /','',$salesrep->login); $salesrep->fetch(0,$salesrep->login); - + $result = $object->add_commercial($user, $salesrep->id); if ($result < 0) { @@ -217,14 +217,14 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) { print " - create link sale representative OK"; } - } - + } + dol_syslog("Add invoice contacts"); // Insert an invoice contact if there is an invoice email != standard email if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) { $ret1=$ret2=0; - + $contact = new Contact($db); $contact->lastname = $object->name; $contact->address=$object->address; @@ -233,7 +233,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $contact->country_id=$object->country_id; $contact->email=$fields[27]; $contact->socid=$object->id; - + $ret1=$contact->create($user); if ($ret1 > 0) { @@ -244,18 +244,18 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); $errorrecord++; } - else + else { print " - create contact OK"; } } - + dol_syslog("Add delivery contacts"); // Insert a delivery contact if (! $errorrecord && $fields[47]) { $ret1=$ret2=0; - + $contact2 = new Contact($db); $contact2->lastname = 'Service livraison - '.$fields[47]; $contact2->address = $fields[48]; @@ -264,10 +264,10 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $contact2->country_id=dol_getIdFromCode($db, trim($fields[52]), 'c_country', 'code', 'rowid'); $contact2->note_public=$fields[54]; $contact2->socid=$object->id; - + // Extrafields $contact2->array_options['options_anazoneliv']=price2num($fields[53]); - + $ret1=$contact2->create($user); if ($ret1 > 0) { @@ -278,16 +278,16 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); $errorrecord++; } - else + else { print " - create contact OK"; } } - + print "\n"; - - if ($errorrecord) + + if ($errorrecord) { fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); $error++; // $errorrecord will be reset diff --git a/dev/initdemo/savedemo.sh b/dev/initdemo/savedemo.sh index fd3f8caafd5..20aebb29b28 100755 --- a/dev/initdemo/savedemo.sh +++ b/dev/initdemo/savedemo.sh @@ -187,6 +187,7 @@ export list=" --ignore-table=$base.llx_bt_webseedfiles --ignore-table=$base.llx_c_civilite --ignore-table=$base.llx_c_dolicloud_plans + --ignore-table=$base.llx_c_pays --ignore-table=$base.llx_c_source --ignore-table=$base.llx_cabinetmed_c_banques --ignore-table=$base.llx_cabinetmed_c_ccam diff --git a/dev/resources/iso-normes/code_nace.txt b/dev/resources/iso-normes/code_nace.txt new file mode 100644 index 00000000000..0c490bd4bf1 --- /dev/null +++ b/dev/resources/iso-normes/code_nace.txt @@ -0,0 +1 @@ +http://ec.europa.eu/eurostat/ramon/nomenclatures/index.cfm?TargetUrl=LST_CLS_DLD&StrNom=NACE_REV2&StrLanguageCode=FR&StrLayoutCode=# \ No newline at end of file diff --git a/dev/resources/sepa/pain.001.001.03.xsd b/dev/resources/sepa/pain.001.001.03.xsd new file mode 100644 index 00000000000..8649779919c --- /dev/null +++ b/dev/resources/sepa/pain.001.001.03.xsd @@ -0,0 +1,921 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dev/resources/sepa/pain.008.001.02.xsd b/dev/resources/sepa/pain.008.001.02.xsd new file mode 100644 index 00000000000..63359725617 --- /dev/null +++ b/dev/resources/sepa/pain.008.001.02.xsd @@ -0,0 +1,879 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/dev/resources/sepa/text.txt b/dev/resources/sepa/text.txt new file mode 100644 index 00000000000..0a5336a128e --- /dev/null +++ b/dev/resources/sepa/text.txt @@ -0,0 +1,2 @@ +To test a SEPA file: +http://www.mesfluxdepaiement.fr/testez-vos-fichiers-sepa \ No newline at end of file diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index 32a938662e6..b8cb751fe9e 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -126,7 +126,7 @@ - + diff --git a/dev/translation/txpush.sh b/dev/translation/txpush.sh index 05ec107b6ff..f64b60f9d3b 100755 --- a/dev/translation/txpush.sh +++ b/dev/translation/txpush.sh @@ -15,7 +15,7 @@ then echo "This push local files to transifex for project $project." echo "Note: If you push a language file (not source), file will be skipped if transifex file is newer." echo " Using -f will overwrite translation but not memory." - echo "Usage: ./dev/translation/txpush.sh (source|xx_XX|all) [-r dolibarr.file] [-f] [--no-interactive]" + echo "Usage: ./dev/translation/txpush.sh (source|xx_XX|all) [-r ".$project.".file] [-f] [--no-interactive]" exit fi diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 5c17f07183e..03565528fc1 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -87,9 +87,6 @@ $hookmanager->initHooks(array('admin')); // This page is a generic page to edit dictionaries // Put here declaration of dictionaries properties -// Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,17,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,25,0,26,0,31,32,0); - // Name of SQL tables of dictionaries $tabname=array(); @@ -148,75 +145,10 @@ $tabfieldcheck=array(); $tabfieldcheck[31] = array(); $tabfieldcheck[32] = array(); -// Complete all arrays with entries found into modules -complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort,$tabfield,$tabfieldvalue,$tabfieldinsert,$tabrowid,$tabcond,$tabhelp,$tabfieldcheck); - // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); $sourceList=array(); -if ($id == 11) -{ - $langs->load("orders"); - $langs->load("contracts"); - $langs->load("projects"); - $langs->load("propal"); - $langs->load("bills"); - $langs->load("interventions"); - $elementList = array( - '' => '', - 'societe' => $langs->trans('ThirdParty'), -// 'proposal' => $langs->trans('Proposal'), -// 'order' => $langs->trans('Order'), -// 'invoice' => $langs->trans('Bill'), - 'invoice_supplier' => $langs->trans('SupplierBill'), - 'order_supplier' => $langs->trans('SupplierOrder'), -// 'intervention' => $langs->trans('InterventionCard'), -// 'contract' => $langs->trans('Contract'), - 'project' => $langs->trans('Project'), - 'project_task' => $langs->trans('Task'), - 'agenda' => $langs->trans('Agenda'), - // old deprecated - 'contrat' => $langs->trans('Contract'), - 'propal' => $langs->trans('Proposal'), - 'commande' => $langs->trans('Order'), - 'facture' => $langs->trans('Bill'), - 'resource' => $langs->trans('Resource'), -// 'facture_fourn' => $langs->trans('SupplierBill'), - 'fichinter' => $langs->trans('InterventionCard') - ); - if (! empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) $elementList["societe"] = $langs->trans('ThirdParty'); - - complete_elementList_with_modules($elementList); - - asort($elementList); - $sourceList = array( - 'internal' => $langs->trans('Internal'), - 'external' => $langs->trans('External') - ); -} -if ($id == 25) -{ - // We save list of template email Dolibarr can manage. This list can found by a grep into code on "->param['models']" - $elementList = array(); - if ($conf->propal->enabled) $elementList['propal_send']=$langs->trans('MailToSendProposal'); - if ($conf->commande->enabled) $elementList['order_send']=$langs->trans('MailToSendOrder'); - if ($conf->facture->enabled) $elementList['facture_send']=$langs->trans('MailToSendInvoice'); - if ($conf->expedition->enabled) $elementList['shipping_send']=$langs->trans('MailToSendShipment'); - if ($conf->ficheinter->enabled) $elementList['fichinter_send']=$langs->trans('MailToSendIntervention'); - if ($conf->supplier_proposal->enabled) $elementList['supplier_proposal_send']=$langs->trans('MailToSendSupplierRequestForQuotation'); - if ($conf->fournisseur->enabled) $elementList['order_supplier_send']=$langs->trans('MailToSendSupplierOrder'); - if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$langs->trans('MailToSendSupplierInvoice'); - if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); - - $parameters=array('elementList'=>$elementList); - $reshook=$hookmanager->executeHooks('emailElementlist',$parameters); // Note that $action and $object may have been modified by some hooks - if ($reshook == 0) { - foreach ($hookmanager->resArray as $item => $value) { - $elementList[$item] = $value; - } - } -} @@ -226,309 +158,309 @@ if ($id == 25) if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x')) { - $search_country_id = ''; + $search_country_id = ''; } // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); - $listfieldinsert=explode(',',$tabfieldinsert[$id]); - $listfieldmodify=explode(',',$tabfieldinsert[$id]); - $listfieldvalue=explode(',',$tabfieldvalue[$id]); + $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); + $listfieldinsert=explode(',',$tabfieldinsert[$id]); + $listfieldmodify=explode(',',$tabfieldinsert[$id]); + $listfieldvalue=explode(',',$tabfieldvalue[$id]); - // Check that all fields are filled - $ok=1; - foreach ($listfield as $f => $value) - { - if ($value == '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' && 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; - if ($value == 'color' && empty($_POST['color'])) continue; + // Check that all fields are filled + $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' && 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; + if ($value == 'color' && empty($_POST['color'])) continue; if ($value == 'formula' && empty($_POST['formula'])) continue; - if ((! isset($_POST[$value]) || $_POST[$value]=='') - && (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy')) // Fields that are not mandatory - && (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 - ) + if ((! isset($_POST[$value]) || $_POST[$value]=='') + && (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy')) // Fields that are not mandatory + && (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 + ) ) - { - $ok=0; - $fieldnamekey=$listfield[$f]; - // We take translate key of field - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; - if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; - if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; - if ($fieldnamekey == 'decalage') $fieldnamekey='Offset'; - if ($fieldnamekey == 'module') $fieldnamekey='Module'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; - if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; - if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; - if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; - if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; - if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; - if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; + { + $ok=0; + $fieldnamekey=$listfield[$f]; + // We take translate key of field + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; + if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; + if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; + if ($fieldnamekey == 'decalage') $fieldnamekey='Offset'; + if ($fieldnamekey == 'module') $fieldnamekey='Module'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; + if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; + if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; + if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; + if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated'; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - } - } - // Other checks - if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) { - $ok=0; - setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); - } - if (isset($_POST["code"])) - { - if ($_POST["code"]=='0') - { - $ok=0; - setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); - } - /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } + // Other checks + if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) { + $ok=0; + setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); + } + if (isset($_POST["code"])) + { + if ($_POST["code"]=='0') + { + $ok=0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ - } - if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) - { - if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries - { - $_POST["country"]=''; - } - else - { - $ok=0; - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); - } - } - if ($id == 3 && ! is_numeric($_POST["code"])) - { - $ok=0; - setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric",$langs->transnoentities("Code")), null, 'errors'); - } + } + if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) + { + if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries + { + $_POST["country"]=''; + } + else + { + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); + } + } + if ($id == 3 && ! is_numeric($_POST["code"])) + { + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric",$langs->transnoentities("Code")), null, 'errors'); + } // Clean some parameters - if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 - if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 + if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 + if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd')) - { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid=0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid=0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid=($obj->newid + 1); - } else { - dol_print_error($db); - } - } + } else { + dol_print_error($db); + } + } - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active)"; - $sql.= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $tabrowid[$id].","; + $sql.= $tabfieldinsert[$id]; + $sql.=",active)"; + $sql.= " VALUES("; - // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $newid.","; - $i=0; - foreach ($listfieldinsert as $f => $value) - { - if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.=",1)"; + // List of values + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $newid.","; + $i=0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.=",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only - } - else - { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } - else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST=array('id'=>$id); // Clean $_POST array, we keep only + } + else + { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } + else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify')) - { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) - { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) + { + $sql.= $tabrowid[$id]."="; + $sql.= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + $sql.= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if (! $resql) - { - setEventMessages($db->error(), null, 'errors'); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (! $resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (! $result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } - else - { - dol_print_error($db); - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (! $result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } + else + { + dol_print_error($db); + } + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // favorite if ($action == 'activate_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable favorite if ($action == 'disable_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -548,8 +480,8 @@ print load_fiche_titre($titre,$linkback,'title_accountancy'); if (empty($id)) { - print $langs->trans("DictionaryDesc"); - print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; + print $langs->trans("DictionaryDesc"); + print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; } print "
\n"; @@ -557,7 +489,7 @@ print "
\n"; // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); } //var_dump($elementList); @@ -566,633 +498,557 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; + // Complete requete recherche valeurs avec critere de tri + $sql=$tabsql[$id]; - if ($search_country_id > 0) - { - if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " c.rowid = ".$search_country_id; - } + if ($search_country_id > 0) + { + if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; + else $sql.=" WHERE "; + $sql.= " c.rowid = ".$search_country_id; + } - if ($sortfield) - { - // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.= " ORDER BY ".$sortfield; - if ($sortorder) - { - $sql.=" ".strtoupper($sortorder); - } - $sql.=", "; - // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); - } - else { - $sql.=" ORDER BY "; - } - $sql.=$tabsqlsort[$id]; - $sql.=$db->plimit($listlimit+1,$offset); - //print $sql; + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield='country_code'; + $sql.= " ORDER BY ".$sortfield; + if ($sortorder) + { + $sql.=" ".strtoupper($sortorder); + } + $sql.=", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); + } + else { + $sql.=" ORDER BY "; + } + $sql.=$tabsqlsort[$id]; + $sql.=$db->plimit($listlimit+1,$offset); + //print $sql; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - print '
'; - print ''; + print ''; + print ''; print '
'; - print ''; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused=0; - $var=false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused=0; + $var=false; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $align="left"; - if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } - if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } - if ($fieldlist[$field]=='taux') { + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + $align="left"; + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); else $valuetoshow=$langs->trans("Amount"); $align='right'; - } - if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2";} - if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3";} - if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } - if ($fieldlist[$field]=='type') { + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2";} + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3";} + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { if ($tabname[$id] == MAIN_DB_PREFIX."c_paiement") $valuetoshow=$form->textwithtooltip($langs->trans("Type"),$langs->trans("TypePaymentDesc"),2,1,img_help(1,'')); else $valuetoshow=$langs->trans("Type"); - } - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - if ($id != 25) $valuetoshow.="*"; - } - if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } - if ($fieldlist[$field]=='country') { - if (in_array('region_id',$fieldlist)) { print ''; continue; } // For region page, we do not show the country input - $valuetoshow=$langs->trans("Country"); - } - if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } - if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } - if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } - if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } - if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } - if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } - if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $valuetoshow=''; } - if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); } - if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); } - if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountparent"); } - if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } - if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } - if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } - if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } - if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { + if (in_array('region_id',$fieldlist)) { print ''; continue; } // For region page, we do not show the country input + $valuetoshow=$langs->trans("Country"); + } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $valuetoshow=''; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); } + if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } - if ($id == 2) // Special cas for state page - { - if ($fieldlist[$field]=='region_id') { $valuetoshow=' '; $showfield=1; } - if ($fieldlist[$field]=='region') { $valuetoshow=$langs->trans("Country").'/'.$langs->trans("Region"); $showfield=1; } - } + if ($id == 2) // Special cas for state page + { + if ($fieldlist[$field]=='region_id') { $valuetoshow=' '; $showfield=1; } + if ($fieldlist[$field]=='region') { $valuetoshow=$langs->trans("Country").'/'.$langs->trans("Region"); $showfield=1; } + } - if ($valuetoshow != '') - { - print ''; - } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; - } + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + } - if ($id == 4) print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - // Line to enter new values - print ""; + // Line to enter new values + print ""; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val)) - $obj->$val=GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val)) + $obj->$val=GETPOST($val); + } + } - $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'create'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($id == 3) unset($fieldlist[2]); + if ($id == 3) unset($fieldlist[2]); - if (empty($reshook)) - { - if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') - { + if (empty($reshook)) + { + if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') + { fieldListAccountModel($fieldlist,$obj,$tabname[$id],'hide'); - } - else - { - fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add'); - } - } + } + else + { + fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add'); + } + } - if ($id == 4) print ''; - print ''; - print ""; + print ''; + print ""; - $colspan=count($fieldlist)+3; - if ($id == 4) $colspan++; + $colspan=count($fieldlist)+3; - if (! empty($alabelisused) && $id != 25) // If there is one label among fields, we show legend of * - { - print ''; - } - print ''; // Keep   to have a line with enough height - } + if (! empty($alabelisused)) // If there is one label among fields, we show legend of * + { + print ''; + } + print ''; // Keep   to have a line with enough height + } - // List of available values in database - dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - $var=true; + // List of available values in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + $var=true; - $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; - $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + $param = '&id='.$id; + if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - // There is several pages - if ($num > $listlimit) - { - print ''; - } + // There is several pages + if ($num > $listlimit) + { + print ''; + } - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield=1; // By defaut - $align="left"; - $sortable=1; - $valuetoshow=''; - /* + // Title line with search boxes + print ''; + foreach ($fieldlist as $field => $value) + { + $showfield=1; // By defaut + + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + + if ($showfield) + { + if ($value == 'country') + { + print ''; + } + else + { + print ''; + } + } + } + print ''; + print ''; + print ''; + + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield=1; // By defaut + $align="left"; + $sortable=1; + $valuetoshow=''; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow=ucfirst($fieldlist[$field]); // By defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } - if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } - if ($fieldlist[$field]=='taux') { + $valuetoshow=ucfirst($fieldlist[$field]); // By defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); else $valuetoshow=$langs->trans("Amount"); $align='right'; - } - if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $sortable=0; } - if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $sortable=0; } - if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } - if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - if ($id != 25) $valuetoshow.="*"; - } - if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } - if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } - if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } - if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } - if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } - if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } - if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } - if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } - if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } - if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } - if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $sortable=0; } + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $sortable=0; } + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } if ($fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } - if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } - if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } - if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } - if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } - if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); - } - } - // Favorite - Only activated on country dictionary - if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); - + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Title line with search boxes - print ''; - foreach ($fieldlist as $field => $value) - { - $showfield=1; // By defaut + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + { + print ''; + print ''; + print ''; + print ''; - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + $tmpaction='edit'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($showfield) - { - if ($value == 'country') - { - print ''; - } - else - { - print ''; - } - } - } - if ($id == 4) print ''; - print ''; - print ''; - print ''; + if (empty($reshook)) fieldListAccountModel($fieldlist,$obj,$tabname[$id],'edit'); - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) - { - print ''; - print ''; - print ''; - print ''; + print ''; + } + else + { + $tmpaction = 'view'; + $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $error=$hookmanager->error; $errors=$hookmanager->errors; - if (empty($reshook)) fieldListAccountModel($fieldlist,$obj,$tabname[$id],'edit'); + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { - print ''; - } - else - { - $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - - $error=$hookmanager->error; $errors=$hookmanager->errors; - - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { - - $showfield=1; - $align="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; - if ($value == 'type_template') - { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; - } - if ($value == 'element') - { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; - } - else if ($value == 'source') - { - $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; - } - else if ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); - } - else if ($fieldlist[$field]=='country') { - if (empty($obj->country_code)) - { - $valuetoshow='-'; - } - else - { - $key=$langs->trans("Country".strtoupper($obj->country_code)); - $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); - } - } - else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field]=='type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if(empty($valuetoshow)) $valuetoshow = $langs->trans('None'); - elseif($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); - elseif($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); - $align="center"; - } - else if ($fieldlist[$field]=='price' || preg_match('/^amount/i',$fieldlist[$field])) { - $valuetoshow=price($valuetoshow); - } - else if ($fieldlist[$field]=='libelle_facture') { - $langs->load("bills"); - $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - $valuetoshow=nl2br($valuetoshow); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { - $key=$langs->trans("Country".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_availability') { - $langs->load("propal"); - $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_actioncomm') { - $key=$langs->trans("Action".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if (! empty($obj->code_iso) && $fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_currencies') { - $key=$langs->trans("Currency".strtoupper($obj->code_iso)); - $valuetoshow=($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_typent') { - $key=$langs->trans(strtoupper($obj->code)); - $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_prospectlevel') { - $key=$langs->trans(strtoupper($obj->code)); - $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_civility') { - $key=$langs->trans("Civility".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "Civility".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_type_contact') { - $langs->load('agenda'); - $key=$langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $key=$langs->trans("PaymentConditionShort".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paiement') { - $langs->load("bills"); - $key=$langs->trans("PaymentType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_reason') { - $key=$langs->trans("DemandReasonType".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "DemandReasonType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_method') { - $langs->load("orders"); - $key=$langs->trans($obj->code); - $valuetoshow=($obj->code && $key != $obj->code)?$key:$obj->{$fieldlist[$field]}; - } - else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_shipment_mode') { - $langs->load("sendings"); - $key=$langs->trans("SendingMethod".strtoupper($obj->code)); - $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field] == 'libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paper_format') - { - $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') - { - $langs->load('trips'); - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { - $showfield=0; - } - else if ($fieldlist[$field]=='unicode') { - $valuetoshow = $langs->getCurrencySymbol($obj->code,1); - } - else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); - } - else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } - else if (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) - { - $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); - $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); - } + $showfield=1; + $align="left"; + $valuetoshow=$obj->{$fieldlist[$field]}; + if ($value == 'type_template') + { + $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + } + if ($value == 'element') + { + $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + } + else if ($value == 'source') + { + $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; + } + else if ($valuetoshow=='all') { + $valuetoshow=$langs->trans('All'); + } + else if ($fieldlist[$field]=='country') { + if (empty($obj->country_code)) + { + $valuetoshow='-'; + } + else + { + $key=$langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); + } + } + else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field]=='type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + if(empty($valuetoshow)) $valuetoshow = $langs->trans('None'); + elseif($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); + elseif($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); + $align="center"; + } + else if ($fieldlist[$field]=='price' || preg_match('/^amount/i',$fieldlist[$field])) { + $valuetoshow=price($valuetoshow); + } + else if ($fieldlist[$field]=='libelle_facture') { + $langs->load("bills"); + $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + $valuetoshow=nl2br($valuetoshow); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { + $key=$langs->trans("Country".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_availability') { + $langs->load("propal"); + $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_actioncomm') { + $key=$langs->trans("Action".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if (! empty($obj->code_iso) && $fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_currencies') { + $key=$langs->trans("Currency".strtoupper($obj->code_iso)); + $valuetoshow=($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_typent') { + $key=$langs->trans(strtoupper($obj->code)); + $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_prospectlevel') { + $key=$langs->trans(strtoupper($obj->code)); + $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_civility') { + $key=$langs->trans("Civility".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Civility".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_type_contact') { + $langs->load('agenda'); + $key=$langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $key=$langs->trans("PaymentConditionShort".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paiement') { + $langs->load("bills"); + $key=$langs->trans("PaymentType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_reason') { + $key=$langs->trans("DemandReasonType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "DemandReasonType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_method') { + $langs->load("orders"); + $key=$langs->trans($obj->code); + $valuetoshow=($obj->code && $key != $obj->code)?$key:$obj->{$fieldlist[$field]}; + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_shipment_mode') { + $langs->load("sendings"); + $key=$langs->trans("SendingMethod".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field] == 'libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paper_format') + { + $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') + { + $langs->load('trips'); + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { + $showfield=0; + } + else if ($fieldlist[$field]=='unicode') { + $valuetoshow = $langs->getCurrencySymbol($obj->code,1); + } + else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } + else if (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) + { + $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); + $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); + } else if ($fieldlist[$field]=='taux') { - $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - $align="right"; + $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); + $align="right"; } else if (in_array($fieldlist[$field],array('recuperableonly'))) { $align="center"; } else if ($fieldlist[$field]=='accountancy_code' || $fieldlist[$field]=='accountancy_code_sell' || $fieldlist[$field]=='accountancy_code_buy') { - $valuetoshow = length_accountg($valuetoshow); - } + $valuetoshow = length_accountg($valuetoshow); + } - $class='tddict'; - if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; + $class='tddict'; + if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; // Show value for field if ($showfield) print ''; - } - } - - // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default - if (isset($obj->code) && $id != 10) - { - if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } - } - - if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable=0; } - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled=0; $canbedisabled = 0; } - $canbemodified=$iserasable; - if ($obj->code == 'RECEP') $canbemodified=1; - - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); - if ($param) $url .= '&'.$param; - $url.='&'; - - // Favorite - // Only activated on country dictionary - if ($id == 4) - { - print ''; + } } - // Active - print '"; + // Can an entry be erased or disabled ? + $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } - // Modify link - if ($canbemodified) print ''; - else print ''; + if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable=0; } + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled=0; $canbedisabled = 0; } + $canbemodified=$iserasable; + if ($obj->code == 'RECEP') $canbemodified=1; - // Delete link - if ($iserasable) print ''; - else print ''; + $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + if ($param) $url .= '&'.$param; + $url.='&'; - print "\n"; - } - $i++; - } - } - } - else { - dol_print_error($db); - } + // Active + print '"; - print '
  '; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; - else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); - else print $valuetoshow; - print ''; + if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; + else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + else print $valuetoshow; + print ''; - print ''; - print '
'; + print ''; + print '
'; - if ($tabname[$id] != MAIN_DB_PREFIX.'c_email_templates' || $action != 'edit') - { - print ''; - } - print '
'; + if ($tabname[$id] != MAIN_DB_PREFIX.'c_email_templates' || $action != 'edit') + { + print ''; + } + print '
* '.$langs->trans("LabelUsedByDefault").'.
 
* '.$langs->trans("LabelUsedByDefault").'.
 
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print '
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone'); + print ''; + $searchpicto=$form->showFilterAndCheckAddButtons(0); + print $searchpicto; + print '
'; - print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone'); - print ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print '
 '; + print '  '; - print ' '.$valuetoshow.''; - if ($iserasable) print ''.$actl[$obj->favorite].''; - else print $langs->trans("AlwaysActive"); - print ''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else - { - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } - print "'.img_edit().' '.img_delete().' 
'; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else + { + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "
'; + // Modify link + if ($canbemodified) print ''.img_edit().''; + else print ' '; + + // Delete link + if ($iserasable) print ''.img_delete().''; + else print ' '; + + print "\n"; + } + $i++; + } + } + } + else { + dol_print_error($db); + } + + print ''; print '
'; - print '
'; -} -else -{ - /* - * Show list of dictionary to show - */ - - $lastlineisempty=false; - print ''; - print ''; - //print ''; - print ''; - print ''; - print ''; - - $showemptyline=''; - foreach ($taborder as $i) - { - if (isset($tabname[$i]) && empty($tabcond[$i])) continue; - - if ($i) - { - if ($showemptyline) - { - print ''; - $showemptyline=0; - } - - - $value=$tabname[$i]; - print ''; - print ''; - print ''; - $lastlineisempty=false; - } - else - { - if (! $lastlineisempty) - { - $showemptyline=1; - $lastlineisempty=true; - } - } - } - print '
'.$langs->trans("Module").''.$langs->trans("Dictionary").''.$langs->trans("Table").'
   
'; - if (! empty($tabcond[$i])) - { - print ''.$langs->trans($tablib[$i]).''; - } - else - { - print $langs->trans($tablib[$i]); - } - print ''; - /*if (empty($tabcond[$i])) - { - print info_admin($langs->trans("DictionaryDisabledSinceNoModuleNeedIt"),1); - }*/ - print ''.$tabname[$i].'
'; + print ''; } print '
'; @@ -1296,8 +1152,8 @@ function fieldListAccountModel($fieldlist, $obj='', $tabname='', $context='') print ''; } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if ($fieldlist[$field] == 'type_cdr') print ''; - else print ''; + if ($fieldlist[$field] == 'type_cdr') print ''; + else print ''; if ($fieldlist[$field] == 'type_cdr') { print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); } else { diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index bc078c062c6..5ce7d6c0413 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -6,6 +6,7 @@ * Copyright (C) 2014 Marcos García * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 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 @@ -19,7 +20,6 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * */ /** @@ -167,7 +167,7 @@ print '' print ''; // Default mode for calculating turnover (parameter ACCOUNTING_MODE) - +/* print ''; print ''; @@ -194,7 +194,7 @@ print "
\n"; print '
'; - +*/ // Others params diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index 2271fa73c0b..220b36c6a52 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -128,8 +128,8 @@ complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort, // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); - // Must match ids defined into eldy.lib.php - $sourceList = array( + // Must match ids defined into eldy.lib.php + $sourceList = array( '1' => $langs->trans('AccountingJournalType1'), '2' => $langs->trans('AccountingJournalType2'), '3' => $langs->trans('AccountingJournalType3'), @@ -144,216 +144,217 @@ $elementList = array(); if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x')) { - $search_country_id = ''; + $search_country_id = ''; } // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); - $listfieldinsert=explode(',',$tabfieldinsert[$id]); - $listfieldmodify=explode(',',$tabfieldinsert[$id]); - $listfieldvalue=explode(',',$tabfieldvalue[$id]); + $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); + $listfieldinsert=explode(',',$tabfieldinsert[$id]); + $listfieldmodify=explode(',',$tabfieldinsert[$id]); + $listfieldvalue=explode(',',$tabfieldvalue[$id]); - // Check that all fields are filled - $ok=1; - foreach ($listfield as $f => $value) - { + // Check that all fields are filled + $ok=1; + foreach ($listfield as $f => $value) + { if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'nature') $fieldnamekey = 'Nature'; - } - // Other checks - if (isset($_POST["code"])) - { - if ($_POST["code"]=='0') - { - $ok=0; - setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); - } - /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + } + // Other checks + if (isset($_POST["code"])) + { + if ($_POST["code"]=='0') + { + $ok=0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ - } + } // Clean some parameters - if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null + if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd')) - { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid=0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid=0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid=($obj->newid + 1); - } else { - dol_print_error($db); - } - } + } else { + dol_print_error($db); + } + } - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active)"; - $sql.= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $tabrowid[$id].","; + $sql.= $tabfieldinsert[$id]; + $sql.=",active)"; + $sql.= " VALUES("; - // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $newid.","; - $i=0; - foreach ($listfieldinsert as $f => $value) - { - if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.=",1)"; + // List of values + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $newid.","; + $i=0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.=",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only - } - else - { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } - else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST=array('id'=>$id); // Clean $_POST array, we keep only + } + else + { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } + else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify')) - { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) - { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { - $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); - } - else if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) + { + $sql.= $tabrowid[$id]."="; + $sql.= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + $sql.= $field."="; + if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if (! $resql) - { - setEventMessages($db->error(), null, 'errors'); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (! $resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (! $result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } - else - { - dol_print_error($db); - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (! $result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } + else + { + dol_print_error($db); + } + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } + /* * View */ @@ -367,8 +368,8 @@ $titre=$langs->trans("DictionarySetup"); $linkback=''; if ($id) { - $titre.=' - '.$langs->trans($tablib[$id]); - $titlepicto='title_accountancy'; + $titre.=' - '.$langs->trans($tablib[$id]); + $titlepicto='title_accountancy'; } print load_fiche_titre($titre,$linkback,$titlepicto); @@ -377,7 +378,7 @@ print load_fiche_titre($titre,$linkback,$titlepicto); // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); } //var_dump($elementList); @@ -386,315 +387,315 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; + // Complete requete recherche valeurs avec critere de tri + $sql=$tabsql[$id]; - if ($search_country_id > 0) - { - if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " c.rowid = ".$search_country_id; - } + if ($search_country_id > 0) + { + if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; + else $sql.=" WHERE "; + $sql.= " c.rowid = ".$search_country_id; + } - if ($sortfield) - { - // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.= " ORDER BY ".$sortfield; - if ($sortorder) - { - $sql.=" ".strtoupper($sortorder); - } - $sql.=", "; - // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); - $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); - } - else { - $sql.=" ORDER BY "; - } - $sql.=$tabsqlsort[$id]; - $sql.=$db->plimit($listlimit+1,$offset); - //print $sql; + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield='country_code'; + $sql.= " ORDER BY ".$sortfield; + if ($sortorder) + { + $sql.=" ".strtoupper($sortorder); + } + $sql.=", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); + } + else { + $sql.=" ORDER BY "; + } + $sql.=$tabsqlsort[$id]; + $sql.=$db->plimit($listlimit+1,$offset); + //print $sql; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - print '
'; - print ''; + print '
'; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused=0; - $var=false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused=0; + $var=false; - $fieldlist=explode(',',$tabfield[$id]); + $fieldlist=explode(',',$tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $align="left"; - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - } - if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + $align="left"; + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + } + if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } - if ($valuetoshow != '') - { - print ''; - } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; - } + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + } - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - // Line to enter new values - print ''; + // Line to enter new values + print ''; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val) != '') - $obj->$val=GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val) != '') + $obj->$val=GETPOST($val); + } + } - $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'create'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if (empty($reshook)) - { - fieldListJournal($fieldlist,$obj,$tabname[$id],'add'); - } + if (empty($reshook)) + { + fieldListJournal($fieldlist,$obj,$tabname[$id],'add'); + } - print ''; - print ""; + print ''; + print ""; - print ''; // Keep   to have a line with enough height - } + print ''; // Keep   to have a line with enough height + } - // List of available record in database - dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - $var=true; + // List of available record in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + $var=true; - $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; - $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; - if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); + $param = '&id='.$id; + if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); - // There is several pages - if ($num > $listlimit) - { - print ''; - } + // There is several pages + if ($num > $listlimit) + { + print ''; + } - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield=1; // By defaut - $align="left"; - $sortable=1; - $valuetoshow=''; - /* + // Title line with search boxes + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield=1; // By defaut + $align="left"; + $sortable=1; + $valuetoshow=''; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow=ucfirst($fieldlist[$field]); // By defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } - if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } + $valuetoshow=ucfirst($fieldlist[$field]); // By defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } + if ($fieldlist[$field]=='nature') { $valuetoshow=$langs->trans("Nature"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); - } - } + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Title line with search boxes - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + { + $tmpaction='edit'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) - { - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + // Show fields + if (empty($reshook)) fieldListJournal($fieldlist,$obj,$tabname[$id],'edit'); - // Show fields - if (empty($reshook)) fieldListJournal($fieldlist,$obj,$tabname[$id],'edit'); + print ''; + } + else + { + $tmpaction = 'view'; + $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - print ''; - } - else - { - $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; - $error=$hookmanager->error; $errors=$hookmanager->errors; + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { + $showfield=1; + $align="left"; + $valuetoshow=$obj->{$fieldlist[$field]}; + if ($valuetoshow=='all') { + $valuetoshow=$langs->trans('All'); + } + else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { + $langs->load("accountancy"); + $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature)); + $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]}); + } - $showfield=1; - $align="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; - if ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); - } - else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { - $langs->load("accountancy"); - $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature)); - $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]}); - } - - $class='tddict'; + $class='tddict'; // Show value for field if ($showfield) print ''; - } - } + } + } - // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default - if (isset($obj->code) && $id != 10) - { - if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } - else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } - } + // Can an entry be erased or disabled ? + $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } - $canbemodified=$iserasable; + $canbemodified=$iserasable; - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); - if ($param) $url .= '&'.$param; - $url.='&'; + $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + if ($param) $url .= '&'.$param; + $url.='&'; - // Active - print '"; + // Active + print '"; - // Modify link - if ($canbemodified) print ''; - else print ''; + // Modify link + if ($canbemodified) print ''; + else print ''; - // Delete link - if ($iserasable) - { - print ''; - } - else print ''; + // Delete link + if ($iserasable) + { + print ''; + } + else print ''; - print ''; + print ''; - print ''; - } + print ''; + } - print "\n"; - $i++; - } - } - } - else { - dol_print_error($db); - } + print "\n"; + $i++; + } + } + } + else { + dol_print_error($db); + } - print '
'; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; - else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); - else print $valuetoshow; - print ''; + if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; + else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + else print $valuetoshow; + print ''; - print ''; - print '
'; + print ''; + print '
'; - print ''; - print '
'; + print ''; + print '
 
 
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print '
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + if ($filterfound) + { + $searchpicto=$form->showFilterAndCheckAddButtons(0); + print $searchpicto; + } + print '
'; - if ($filterfound) - { - $searchpicto=$form->showFilterAndCheckAddButtons(0); - print $searchpicto; - } - print '
'; + print ''; + print ''; + print ''; + print ''; + print '
'; + print '
'; - print ''; - print ''; - print ''; - print ''; - print '
'; - print '
'.$valuetoshow.''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else - { - if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } - print "'; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else + { + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "'.img_edit().' '.img_edit().' '; - if ($user->admin) print ''.img_delete().''; - //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - print ' '; + if ($user->admin) print ''.img_delete().''; + //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin + print ' 
'; + print ''; print '
'; - print '
'; + print ''; } print '
'; diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index d3252b01a18..81adbcb266b 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -569,7 +569,7 @@ if ($action == 'create') { print_liste_field_titre("AccountAccountingShort"); print_liste_field_titre("SubledgerAccount"); - print_liste_field_titre("Labelcompte"); + print_liste_field_titre("LabelAccount"); print_liste_field_titre("Label"); print_liste_field_titre("Debit", "", "", "", "", 'align="right"'); print_liste_field_titre("Credit", "", "", "", "", 'align="right"'); diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index c87b906f45e..30db29db927 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -98,8 +98,8 @@ $form = new Form($db); if ($action != 'export_file' && ! isset($_POST['begin']) && ! isset($_GET['begin']) && ! isset($_POST['formfilteraction']) && empty($page)) { - $search_date_start = dol_mktime(0, 0, 0, 1, 1, dol_print_date(dol_now(), '%Y')); - $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); + $search_date_start = dol_mktime(0, 0, 0, 1, 1, dol_print_date(dol_now(), '%Y')); + $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); } @@ -134,67 +134,67 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $param = ''; $filter = array (); if (! empty($search_date_start)) { - $filter['t.doc_date>='] = $search_date_start; - $tmp=dol_getdate($search_date_start); - $param .= '&date_startmonth=' . $tmp['mon'] . '&date_startday=' . $tmp['mday'] . '&date_startyear=' . $tmp['year']; + $filter['t.doc_date>='] = $search_date_start; + $tmp=dol_getdate($search_date_start); + $param .= '&date_startmonth=' . $tmp['mon'] . '&date_startday=' . $tmp['mday'] . '&date_startyear=' . $tmp['year']; } if (! empty($search_date_end)) { - $filter['t.doc_date<='] = $search_date_end; - $tmp=dol_getdate($search_date_end); - $param .= '&date_endmonth=' . $tmp['mon'] . '&date_endday=' . $tmp['mday'] . '&date_endyear=' . $tmp['year']; + $filter['t.doc_date<='] = $search_date_end; + $tmp=dol_getdate($search_date_end); + $param .= '&date_endmonth=' . $tmp['mon'] . '&date_endday=' . $tmp['mday'] . '&date_endyear=' . $tmp['year']; } if (! empty($search_doc_date)) { - $filter['t.doc_date'] = $search_doc_date; - $tmp=dol_getdate($search_doc_date); - $param .= '&doc_datemonth=' . $tmp['mon'] . '&doc_dateday=' . $tmp['mday'] . '&doc_dateyear=' . $tmp['year']; + $filter['t.doc_date'] = $search_doc_date; + $tmp=dol_getdate($search_doc_date); + $param .= '&doc_datemonth=' . $tmp['mon'] . '&doc_dateday=' . $tmp['mday'] . '&doc_dateyear=' . $tmp['year']; } if (! empty($search_doc_type)) { - $filter['t.doc_type'] = $search_doc_type; - $param .= '&search_doc_type=' . $search_doc_type; + $filter['t.doc_type'] = $search_doc_type; + $param .= '&search_doc_type=' . $search_doc_type; } if (! empty($search_doc_ref)) { - $filter['t.doc_ref'] = $search_doc_ref; - $param .= '&search_doc_ref=' . $search_doc_ref; + $filter['t.doc_ref'] = $search_doc_ref; + $param .= '&search_doc_ref=' . $search_doc_ref; } if (! empty($search_accountancy_code)) { - $filter['t.numero_compte'] = $search_accountancy_code; - $param .= '&search_accountancy_code=' . $search_accountancy_code; + $filter['t.numero_compte'] = $search_accountancy_code; + $param .= '&search_accountancy_code=' . $search_accountancy_code; } if (! empty($search_accountancy_code_start)) { - $filter['t.numero_compte>='] = $search_accountancy_code_start; - $param .= '&search_accountancy_code_start=' . $search_accountancy_code_start; + $filter['t.numero_compte>='] = $search_accountancy_code_start; + $param .= '&search_accountancy_code_start=' . $search_accountancy_code_start; } if (! empty($search_accountancy_code_end)) { - $filter['t.numero_compte<='] = $search_accountancy_code_end; - $param .= '&search_accountancy_code_end=' . $search_accountancy_code_end; + $filter['t.numero_compte<='] = $search_accountancy_code_end; + $param .= '&search_accountancy_code_end=' . $search_accountancy_code_end; } if (! empty($search_accountancy_aux_code)) { - $filter['t.subledger_account'] = $search_accountancy_aux_code; - $param .= '&search_accountancy_aux_code=' . $search_accountancy_aux_code; + $filter['t.subledger_account'] = $search_accountancy_aux_code; + $param .= '&search_accountancy_aux_code=' . $search_accountancy_aux_code; } if (! empty($search_accountancy_aux_code_start)) { - $filter['t.subledger_account>='] = $search_accountancy_aux_code_start; - $param .= '&search_accountancy_aux_code_start=' . $search_accountancy_aux_code_start; + $filter['t.subledger_account>='] = $search_accountancy_aux_code_start; + $param .= '&search_accountancy_aux_code_start=' . $search_accountancy_aux_code_start; } if (! empty($search_accountancy_aux_code_end)) { - $filter['t.subledger_account<='] = $search_accountancy_aux_code_end; - $param .= '&search_accountancy_aux_code_end=' . $search_accountancy_aux_code_end; + $filter['t.subledger_account<='] = $search_accountancy_aux_code_end; + $param .= '&search_accountancy_aux_code_end=' . $search_accountancy_aux_code_end; } if (! empty($search_mvt_label)) { - $filter['t.label_operation'] = $search_mvt_label; - $param .= '&search_mvt_label=' . $search_mvt_label; + $filter['t.label_operation'] = $search_mvt_label; + $param .= '&search_mvt_label=' . $search_mvt_label; } if (! empty($search_direction)) { - $filter['t.sens'] = $search_direction; - $param .= '&search_direction=' . $search_direction; + $filter['t.sens'] = $search_direction; + $param .= '&search_direction=' . $search_direction; } if (! empty($search_ledger_code)) { - $filter['t.code_journal'] = $search_ledger_code; - $param .= '&search_ledger_code=' . $search_ledger_code; + $filter['t.code_journal'] = $search_ledger_code; + $param .= '&search_ledger_code=' . $search_ledger_code; } if (! empty($search_mvt_num)) { - $filter['t.piece_num'] = $search_mvt_num; - $param .= '&search_mvt_num=' . $search_mvt_num; + $filter['t.piece_num'] = $search_mvt_num; + $param .= '&search_mvt_num=' . $search_mvt_num; } if ($action == 'delbookkeeping') { @@ -229,16 +229,16 @@ if ($action == 'delbookkeepingyearconfirm') { } else { - setEventMessages("RecordDeleted", null, 'mesgs'); + setEventMessages("RecordDeleted", null, 'mesgs'); } Header("Location: list.php"); exit; } else { - setEventMessages("NoRecordDeleted", null, 'warnings'); - Header("Location: list.php"); - exit; + setEventMessages("NoRecordDeleted", null, 'warnings'); + Header("Location: list.php"); + exit; } } if ($action == 'delmouvconfirm') { @@ -248,11 +248,11 @@ if ($action == 'delmouvconfirm') { if (! empty($mvt_num)) { $result = $object->deleteMvtNum($mvt_num); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { - setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); } Header("Location: list.php"); exit; @@ -262,21 +262,21 @@ if ($action == 'delmouvconfirm') { // Export into a file with format defined into setup if ($action == 'export_file') { - $result = $object->fetchAll($sortorder, $sortfield, 0, 0, $filter); + $result = $object->fetchAll($sortorder, $sortfield, 0, 0, $filter); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - else - { - $accountancyexport = new AccountancyExport($db); - $accountancyexport->export($object->lines); - if (!empty($accountancyexport->errors)) { - setEventMessages('', $accountancyexport->errors, 'errors'); - } - exit; - } + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + else + { + $accountancyexport = new AccountancyExport($db); + $accountancyexport->export($object->lines); + if (!empty($accountancyexport->errors)) { + setEventMessages('', $accountancyexport->errors, 'errors'); + } + exit; + } } @@ -330,7 +330,7 @@ if ($action == 'delbookkeepingyear') { ); $form_question['deljournal'] = array ( 'name' => 'deljournal', - 'type' => 'other', // We don't use select here, the journal_array is already a select html component + 'type' => 'other', // We don't use select here, the journal_array is already a select html component 'label' => $langs->trans('DelJournal'), 'value' => $journal_array, 'default' => $deljournal @@ -340,7 +340,7 @@ if ($action == 'delbookkeepingyear') { print $formconfirm; } -//$param=''; param started before +//$param=''; param started before if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; @@ -399,28 +399,28 @@ print ''; print ''; print '
'; print $langs->trans('From').' '; -// TODO For the moment we keep a fre input text instead of a combo. The select_auxaccount has problem because it does not +// TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { - print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); + print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); } else { - print ''; + print ''; } print '
'; print '
'; print $langs->trans('to').' '; -// TODO For the moment we keep a fre input text instead of a combo. The select_auxaccount has problem because it does not +// TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not // use setup of keypress to select thirdparty and this hang browser on large database. if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { - print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); + print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); } else { - print ''; + print ''; } print '
'; print ''; @@ -489,8 +489,8 @@ while ($i < min($num, $limit)) } print ''; -if ($num < $limit) print ''.$langs->trans("Total").''; -else print ''.$langs->trans("Totalforthispage").''; +if ($num < $limit) print ''.$langs->trans("Total").''; +else print ''.$langs->trans("Totalforthispage").''; print ''; print ''; print price($total_debit); diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index e9ad42858aa..ac92dcab195 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -419,7 +419,7 @@ class AccountancyExport /** - * Export format : Agiris + * Export format : Agiris Isacompta * * @param array $objectLines data * @@ -433,30 +433,23 @@ class AccountancyExport $date = dol_print_date($line->doc_date, '%d%m%Y'); - print $line->id . $this->separator; - print '"'.dol_trunc($line->piece_num,15,'right','UTF-8',1).'"'.$this->separator; + print $line->piece_num . $this->separator; + print $line->label_operation . $this->separator; print $date . $this->separator; - print '"'.dol_trunc($line->piece_num,15,'right','UTF-8',1).'"'.$this->separator; + print $line->label_operation . $this->separator; if (empty($line->subledger_account)) { print length_accountg($line->numero_compte) . $this->separator; } else { - // FIXME Because the subledger_account is already an accounting account, does we really need - // to concat 4011 or 401 to it ? - if (substr($line->numero_compte, 0, 1) == 'C' || substr($line->numero_compte, 0, 1) == '9') { - print '411' . substr(str_replace(" ", "", $line->subledger_account), 0, 5) . $this->separator; - } - if (substr($line->numero_compte, 0, 1) == 'F' || substr($line->numero_compte, 0, 1) == '0') { - print '401' . substr(str_replace(" ", "", $line->subledger_account), 0, 5) . $this->separator; - } + print length_accounta($line->subledger_account) . $this->separator; } - print length_accounta($line->subledger_account) . $this->separator; + print $line->doc_ref . $this->separator; print price($line->debit) . $this->separator; print price($line->credit) . $this->separator; print price($line->montant).$this->separator; print $line->sens.$this->separator; - print $line->code_journal . $this->separator; + print $line->code_journal; print $this->end_line; } } 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/customer/index.php b/htdocs/accountancy/customer/index.php index 4aad88df54d..86327b27636 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -1,9 +1,9 @@ - * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2016 Alexandre Spangaro - * Copyright (C) 2014 Juanjo Menent - * Copyright (C) 2015 Jean-François Ferry +/* Copyright (C) 2013 Olivier Geffroy + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -310,6 +310,7 @@ if ($resql) { } else print length_accountg($row[0]); print ''; + print ''; if ($row[0] == 'tobind') { @@ -317,7 +318,7 @@ if ($resql) { } else print $row[1]; print ''; - print '' . $row[1] . ''; + for($i = 2; $i <= 12; $i ++) { print '' . price($row[$i]) . ''; } 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 ' + + global->MAIN_USE_METEO_WITH_PERCENTAGE)) { + + print '
'; + print '
'; + print img_weather($text,'weather-clear.png',$options); + print '= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL0.' %'; + print '
'; + print img_weather($text,'weather-few-clouds.png',$options); + print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL1.' %'; + print '
'; + print img_weather($text,'weather-clouds.png',$options); + print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL2.' %'; + print '
'; + print img_weather($text,'weather-many-clouds.png',$options); + print '<= '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; + print '
'; + print img_weather($text,'weather-storm.png',$options); + print '> '.$conf->global->MAIN_METEO_PERCENTAGE_LEVEL3.' %'; + print '
'; + print '
'; + + } else { + + print '
'; + print '
'; + print img_weather($text,'weather-clear.png',$options); + print '= '.$level0; + print '
'; + print img_weather($text,'weather-few-clouds.png',$options); + print '<= '.$level1; + print '
'; + print img_weather($text,'weather-clouds.png',$options); + print '<= '.$level2; + print '
'; + print img_weather($text,'weather-many-clouds.png',$options); + print '<= '.$level3; + print '
'; + print img_weather($text,'weather-storm.png',$options); + print '> '.$level3; + print '
'; + print '
'; + + } +} + +print ''; + +if($action == 'edit') { + + print '
'; + print '
'; + +} else { + + // Boutons d'action + print '
'; + +} + llxFooter(); $db->close(); diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index 427eba96854..068513b245c 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -1,16 +1,16 @@ - * Copyright (C) 2004-2015 Laurent Destailleur - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2011-2015 Philippe Grand - * Copyright (C) 2011 Remy Younes - * Copyright (C) 2012-2015 Marcos García - * Copyright (C) 2012 Christophe Battarel - * Copyright (C) 2011-2016 Alexandre Spangaro - * Copyright (C) 2015 Ferran Marcet - * Copyright (C) 2016 Raphaël Doursenaud +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2010-2016 Juanjo Menent + * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2011 Remy Younes + * Copyright (C) 2012-2015 Marcos García + * Copyright (C) 2012 Christophe Battarel + * Copyright (C) 2011-2016 Alexandre Spangaro + * Copyright (C) 2015 Ferran Marcet + * Copyright (C) 2016 Raphaël Doursenaud * * 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 @@ -54,6 +54,7 @@ $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); $id=GETPOST('id','int'); $rowid=GETPOST('rowid','alpha'); +$entity=GETPOST('entity','int'); $code=GETPOST('code','alpha'); $allowed=$user->admin; @@ -181,8 +182,8 @@ $tabsql[8] = "SELECT t.id as rowid, t.code as code, t.libelle, t.fk_country as $tabsql[9] = "SELECT c.code_iso as code, c.label, c.unicode, c.active FROM ".MAIN_DB_PREFIX."c_currencies AS c"; $tabsql[10]= "SELECT t.rowid, t.code, t.taux, t.localtax1_type, t.localtax1, t.localtax2_type, t.localtax2, c.label as country, c.code as country_code, t.fk_pays as country_id, t.recuperableonly, t.note, t.active, t.accountancy_code_sell, t.accountancy_code_buy FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c WHERE t.fk_pays=c.rowid"; $tabsql[11]= "SELECT t.rowid as rowid, t.element, t.source, t.code, t.libelle, t.position, t.active FROM ".MAIN_DB_PREFIX."c_type_contact AS t"; -$tabsql[12]= "SELECT c.rowid as rowid, c.code, c.libelle, c.libelle_facture, c.nbjour, c.type_cdr, c.decalage, c.active, c.sortorder FROM ".MAIN_DB_PREFIX.'c_payment_term AS c'; -$tabsql[13]= "SELECT c.id as rowid, c.code, c.libelle, c.type, c.active, c.accountancy_code FROM ".MAIN_DB_PREFIX."c_paiement AS c"; +$tabsql[12]= "SELECT c.rowid as rowid, c.code, c.libelle, c.libelle_facture, c.nbjour, c.type_cdr, c.decalage, c.active, c.sortorder, c.entity FROM ".MAIN_DB_PREFIX."c_payment_term AS c WHERE c.entity = " . getEntity($tabname[12]); +$tabsql[13]= "SELECT c.id as rowid, c.code, c.libelle, c.type, c.active, c.accountancy_code, c.entity FROM ".MAIN_DB_PREFIX."c_paiement AS c WHERE c.entity = " . getEntity($tabname[13]); $tabsql[14]= "SELECT e.rowid as rowid, e.code as code, e.libelle, e.price, e.organization, e.fk_pays as country_id, c.code as country_code, c.label as country, e.active FROM ".MAIN_DB_PREFIX."c_ecotaxe AS e, ".MAIN_DB_PREFIX."c_country as c WHERE e.fk_pays=c.rowid and c.active=1"; $tabsql[15]= "SELECT rowid as rowid, code, label as libelle, width, height, unit, active FROM ".MAIN_DB_PREFIX."c_paper_format"; $tabsql[16]= "SELECT code, label as libelle, sortorder, active FROM ".MAIN_DB_PREFIX."c_prospectlevel"; @@ -259,8 +260,8 @@ $tabfield[8] = "code,libelle,country_id,country".(! empty($conf->global->SOCIETE $tabfield[9] = "code,label,unicode"; $tabfield[10]= "country_id,country,code,taux,localtax1_type,localtax1,localtax2_type,localtax2,recuperableonly,accountancy_code_sell,accountancy_code_buy,note"; $tabfield[11]= "element,source,code,libelle,position"; -$tabfield[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; -$tabfield[13]= "code,libelle,type,accountancy_code"; +$tabfield[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder,entity"; +$tabfield[13]= "code,libelle,type,accountancy_code,entity"; $tabfield[14]= "code,libelle,price,organization,country_id,country"; $tabfield[15]= "code,libelle,width,height,unit"; $tabfield[16]= "code,libelle,sortorder"; @@ -335,8 +336,8 @@ $tabfieldinsert[8] = "code,libelle,fk_country".(! empty($conf->global->SOCIETE_S $tabfieldinsert[9] = "code_iso,label,unicode"; $tabfieldinsert[10]= "fk_pays,code,taux,localtax1_type,localtax1,localtax2_type,localtax2,recuperableonly,accountancy_code_sell,accountancy_code_buy,note"; $tabfieldinsert[11]= "element,source,code,libelle,position"; -$tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; -$tabfieldinsert[13]= "code,libelle,type,accountancy_code"; +$tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder,entity"; +$tabfieldinsert[13]= "code,libelle,type,accountancy_code,entity"; $tabfieldinsert[14]= "code,libelle,price,organization,fk_pays"; $tabfieldinsert[15]= "code,label,width,height,unit"; $tabfieldinsert[16]= "code,label,sortorder"; @@ -733,7 +734,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); } else if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; + $_POST[$listfieldvalue[$i]] = getEntity($tabname[$id]); } if ($i) $sql.=","; if ($listfieldvalue[$i] == 'sortorder') // For column name 'sortorder', we use the field name 'position' @@ -785,7 +786,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); } else if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; + $_POST[$listfieldvalue[$i]] = getEntity($tabname[$id]); } if ($i) $sql.=","; $sql.= $field."="; @@ -798,6 +799,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $i++; } $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql.= " AND entity = '".getEntity($tabname[$id])."'"; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; @@ -820,7 +822,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } else { $rowidcol="rowid"; } - $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + $sql = "DELETE FROM ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); @@ -844,10 +846,10 @@ if ($action == $acts[0]) else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -864,10 +866,10 @@ if ($action == $acts[1]) else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -884,10 +886,10 @@ if ($action == 'activate_favorite') else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -904,10 +906,10 @@ if ($action == 'disable_favorite') else { $rowidcol="rowid"; } if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'"; + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = " . (int) $entity : ''); } $result = $db->query($sql); @@ -959,6 +961,7 @@ print "
\n"; $param = '&id='.$id; if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; if ($search_code != '') $param.= '&search_code='.urlencode($search_country_id); +if ($entity != '') $param.= '&entity=' . (int) $entity; $paramwithsearch = $param; if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; @@ -1016,6 +1019,7 @@ if ($id) if ($tabname[$id]) { $alabelisused=0; + $withentity=null; $fieldlist=explode(',',$tabfield[$id]); @@ -1026,6 +1030,11 @@ if ($id) print ''; foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'entity') { + $withentity = getEntity($tabname[$id]); + continue; + } + // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut @@ -1119,6 +1128,8 @@ if ($id) if ($id == 4) print ''; print ''; print ''; + if (! is_null($withentity)) + print ''; print ''; print ''; print ''; @@ -1197,7 +1208,9 @@ if ($id) $filterfound=0; foreach ($fieldlist as $field => $value) { - $showfield=1; // By defaut + if ($fieldlist[$field] == 'entity') continue; + + $showfield=1; // By default if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } @@ -1239,6 +1252,8 @@ if ($id) print ''; foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'entity') continue; + // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees $showfield=1; // By defaut @@ -1349,12 +1364,16 @@ if ($id) $error=$hookmanager->error; $errors=$hookmanager->errors; // Show fields - if (empty($reshook)) fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + if (empty($reshook)) { + $withentity = fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + } print ''; print '
'; print ''; print ''; + if (! is_null($withentity)) + print ''; print ''; print ''; print ''; @@ -1369,11 +1388,19 @@ if ($id) if (empty($reshook)) { + $withentity=null; + foreach ($fieldlist as $field => $value) { - $showfield=1; + $showfield=1; $align="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; + $valuetoshow=$obj->{$fieldlist[$field]}; + + if ($fieldlist[$field] == 'entity') { + $withentity = $valuetoshow; + continue; + } + if ($value == 'element') { $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; @@ -1588,7 +1615,8 @@ if ($id) // If rowidcol not defined if (empty($rowidcol) || in_array($id, array(6,7,8,13,17,19,27))) $rowidcol='rowid'; $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.((! empty($obj->{$rowidcol}) || $obj->{$rowidcol} == '0')?$obj->{$rowidcol}:(! empty($obj->code)?urlencode($obj->code):'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); - if ($param) $url .= '&'.$param; + if (! empty($param)) $url .= '&'.$param; + if (! is_null($withentity)) $url .= '&entity='.$withentity; $url.='&'; // Favorite @@ -1721,7 +1749,7 @@ $db->close(); * @param Object $obj If we show a particular record, obj is filled with record fields * @param string $tabname Name of SQL table * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered - * @return void + * @return string '' or value of entity into table */ function fieldList($fieldlist, $obj='', $tabname='', $context='') { @@ -1735,8 +1763,15 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') $formcompany = new FormCompany($db); if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + $withentity=''; + foreach ($fieldlist as $field => $value) { + if ($fieldlist[$field] == 'entity') { + $withentity = $obj->{$fieldlist[$field]}; + continue; + } + if (in_array($fieldlist[$field], array('code', 'libelle', 'type')) && $tabname == MAIN_DB_PREFIX."c_actioncomm" && in_array($obj->type, array('system','systemauto'))) { $hidden = (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''); @@ -1948,5 +1983,7 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') print ''; } } + + return $withentity; } diff --git a/htdocs/admin/dolistore/class/dolistore.class.php b/htdocs/admin/dolistore/class/dolistore.class.php index f437dc66975..07dbec4b902 100644 --- a/htdocs/admin/dolistore/class/dolistore.class.php +++ b/htdocs/admin/dolistore/class/dolistore.class.php @@ -25,117 +25,119 @@ include_once DOL_DOCUMENT_ROOT.'/admin/dolistore/class/PSWebServiceLibrary.class */ class Dolistore { - // params - public $start // beginning of pagination - , $end // end of pagination - , $per_page // pagination: display per page - , $categorie // the current categorie - , $search // the search keywords - // setups - , $url // the url of this page - , $shop_url // the url of the shop - , $vat_rate // the vat rate used in the shop (prices are provided without vat) - , $lang // the integer representing the lang in the store - , $debug_api; // usefull if no dialog + // params + public $start; // beginning of pagination + public $end; // end of pagination + public $per_page; // pagination: display per page + public $categorie; // the current categorie + public $search; // the search keywords - /** - * Constructor - */ - function __construct() - { - global $conf, $langs; + // setups + public $url; // the url of this page + public $shop_url; // the url of the shop + public $vat_rate; // the vat rate used in the shop (prices are provided without vat) + public $lang; // the integer representing the lang in the store + public $debug_api; // usefull if no dialog - $this->url = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace'; - $this->shop_url = 'https://www.dolistore.com/index.php?controller=product&id_product='; - $this->vat_rate = 1.2; // 20% de TVA - $this->debug_api = false; - $langtmp = explode('_', $langs->defaultlang); - $lang = $langtmp[0]; - $lang_array = array('en'=>0, 'fr'=>1, 'es'=>2, 'it'=>3, 'de'=>4); // Into table ps_lang of Prestashop - 1 - if (! in_array($lang, array_keys($lang_array))) $lang = 'en'; - $this->lang = $lang_array[$lang]; - } + /** + * Constructor + */ + function __construct() + { + global $conf, $langs; - /** - * Load data from remote Dolistore market place. - * This fills ->categories - * - * @param array $options Options - * @return void - */ - function getRemoteData($options = array('start' => 0, 'end' => 10, 'per_page' => 50, 'categorie' => 0)) - { - global $conf, $langs; + $this->url = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace'; + $this->shop_url = 'https://www.dolistore.com/index.php?controller=product&id_product='; + $this->vat_rate = 1.2; // 20% de TVA + $this->debug_api = false; - $this->start = $options['start']; - $this->end = $options['end']; - $this->per_page = $options['per_page']; - $this->categorie = $options['categorie']; - $this->search = $options['search']; + $langtmp = explode('_', $langs->defaultlang); + $lang = $langtmp[0]; + $lang_array = array('en'=>0, 'fr'=>1, 'es'=>2, 'it'=>3, 'de'=>4); // Into table ps_lang of Prestashop - 1 + if (! in_array($lang, array_keys($lang_array))) $lang = 'en'; + $this->lang = $lang_array[$lang]; + } - if ($this->end == 0) { - $this->end = $this->per_page; - } + /** + * Load data from remote Dolistore market place. + * This fills ->categories + * + * @param array $options Options + * @return void + */ + function getRemoteData($options = array('start' => 0, 'end' => 10, 'per_page' => 50, 'categorie' => 0)) + { + global $conf, $langs; - try { - $this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, - $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api); + $this->start = $options['start']; + $this->end = $options['end']; + $this->per_page = $options['per_page']; + $this->categorie = $options['categorie']; + $this->search = $options['search']; - // Here we set the option array for the Webservice : we want products resources - $opt = array(); - $opt['resource'] = 'products'; + if ($this->end == 0) { + $this->end = $this->per_page; + } - // make a search to limit the id returned. - if ($this->search != '') { - $opt2 = array(); - $opt2['url'] = $conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'/api/search?query='.$this->search.'&language='.$this->lang; - // Call - $xml = $this->api->get($opt2); - $products = array(); - foreach ($xml->products->children() as $product) { - $products[] = (int) $product['id']; - } - $opt['filter[id]'] = '['.implode('|', $products).']'; - } elseif ($this->categorie != 0) { - $opt2 = array(); - $opt2['resource'] = 'categories'; - $opt2['id'] = $this->categorie; - // Call - $xml = $this->api->get($opt2); - $products = array(); - foreach ($xml->category->associations->products->children() as $product) { - $products[] = (int) $product->id; - } - $opt['filter[id]'] = '['.implode('|', $products).']'; - } - $opt['display'] = '[id,name,id_default_image,id_category_default,reference,price,condition,show_price,date_add,date_upd,description_short,description,module_version,dolibarr_min,dolibarr_max]'; - $opt['sort'] = 'id_desc'; - $opt['filter[active]'] = '[1]'; - $opt['limit'] = "$this->start,$this->end"; + try { + $this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, + $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api); + + // Here we set the option array for the Webservice : we want products resources + $opt = array(); + $opt['resource'] = 'products'; + + // make a search to limit the id returned. + if ($this->search != '') { + $opt2 = array(); + $opt2['url'] = $conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'/api/search?query='.$this->search.'&language='.$this->lang; + // Call + $xml = $this->api->get($opt2); + $products = array(); + foreach ($xml->products->children() as $product) { + $products[] = (int) $product['id']; + } + $opt['filter[id]'] = '['.implode('|', $products).']'; + } elseif ($this->categorie != 0) { + $opt2 = array(); + $opt2['resource'] = 'categories'; + $opt2['id'] = $this->categorie; + // Call + $xml = $this->api->get($opt2); + $products = array(); + foreach ($xml->category->associations->products->children() as $product) { + $products[] = (int) $product->id; + } + $opt['filter[id]'] = '['.implode('|', $products).']'; + } + $opt['display'] = '[id,name,id_default_image,id_category_default,reference,price,condition,show_price,date_add,date_upd,description_short,description,module_version,dolibarr_min,dolibarr_max]'; + $opt['sort'] = 'id_desc'; + $opt['filter[active]'] = '[1]'; + $opt['limit'] = "$this->start,$this->end"; // $opt['filter[id]'] contais list of product id that are result of search - // Call API to get the detail - $xml = $this->api->get($opt); - $this->products = $xml->products->children(); + // Call API to get the detail + $xml = $this->api->get($opt); + $this->products = $xml->products->children(); - // Here we set the option array for the Webservice : we want categories resources - $opt = array(); - $opt['resource'] = 'categories'; - $opt['display'] = '[id,id_parent,nb_products_recursive,active,is_root_category,name,description]'; - $opt['sort'] = 'id_asc'; - // Call - $xml = $this->api->get($opt); - $this->categories = $xml->categories->children(); - } catch (PrestaShopWebserviceException $e) { - // Here we are dealing with errors - $trace = $e->getTrace(); - if ($trace[0]['args'][0] == 404) die('Bad ID'); - else if ($trace[0]['args'][0] == 401) die('Bad auth key'); - else die('Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV); - } - } + // Here we set the option array for the Webservice : we want categories resources + $opt = array(); + $opt['resource'] = 'categories'; + $opt['display'] = '[id,id_parent,nb_products_recursive,active,is_root_category,name,description]'; + $opt['sort'] = 'id_asc'; + // Call + $xml = $this->api->get($opt); + $this->categories = $xml->categories->children(); + } catch (PrestaShopWebserviceException $e) { + // Here we are dealing with errors + $trace = $e->getTrace(); + if ($trace[0]['args'][0] == 404) die('Bad ID'); + else if ($trace[0]['args'][0] == 401) die('Bad auth key'); + else die('Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV); + } + } /** * Return tree of Dolistore categories. $this->categories must have been loaded before. @@ -143,199 +145,199 @@ class Dolistore * @param int $parent Id of parent category * @return string */ - function get_categories($parent = 0) - { - if (!isset($this->categories)) die('not possible'); - if ($parent != 0) { - $html = '
    '; - } else { - $html = ''; - } + function get_categories($parent = 0) + { + if (!isset($this->categories)) die('not possible'); + if ($parent != 0) { + $html = '
      '; + } else { + $html = ''; + } - $nbofcateg = count($this->categories); - for ($i = 0; $i < $nbofcateg; $i++) - { - $cat = $this->categories[$i]; - if ($cat->is_root_category == 1 && $parent == 0) { - $html .= '
    • '.$cat->name->language[$this->lang].' '.$cat->nb_products_recursive.'

      '; - $html .= self::get_categories($cat->id); - $html .= "
    • \n"; - } elseif (trim($cat->id_parent) == $parent && $cat->active == 1 && trim($cat->id_parent) != 0) { // si cat est de ce niveau - $select = ($cat->id == $this->categorie) ? ' selected' : ''; - $html .= '
    • '.$cat->name->language[$this->lang].' '.$cat->nb_products_recursive.''; - $html .= self::get_categories($cat->id); - $html .= "
    • \n"; - } else { + $nbofcateg = count($this->categories); + for ($i = 0; $i < $nbofcateg; $i++) + { + $cat = $this->categories[$i]; + if ($cat->is_root_category == 1 && $parent == 0) { + $html .= '
    • '.$cat->name->language[$this->lang].' '.$cat->nb_products_recursive.'

      '; + $html .= self::get_categories($cat->id); + $html .= "
    • \n"; + } elseif (trim($cat->id_parent) == $parent && $cat->active == 1 && trim($cat->id_parent) != 0) { // si cat est de ce niveau + $select = ($cat->id == $this->categorie) ? ' selected' : ''; + $html .= '
    • '.$cat->name->language[$this->lang].' '.$cat->nb_products_recursive.''; + $html .= self::get_categories($cat->id); + $html .= "
    • \n"; + } else { - } - } + } + } - if ($html == '
        ') { - return ''; - } - if ($parent != 0) { - return $html.'
      '; - } else { - return $html; - } - } + if ($html == '
        ') { + return ''; + } + if ($parent != 0) { + return $html.'
      '; + } else { + return $html; + } + } - /** - * Return list of product formated for output - * - * @return string HTML output - */ - function get_products() - { - global $langs, $conf; - $html = ""; - $parity = "pair"; - $last_month = time() - (30 * 24 * 60 * 60); - foreach ($this->products as $product) { - $parity = ($parity == "impair") ? 'pair' : 'impair'; + /** + * Return list of product formated for output + * + * @return string HTML output + */ + function get_products() + { + global $langs, $conf; + $html = ""; + $parity = "pair"; + $last_month = time() - (30 * 24 * 60 * 60); + foreach ($this->products as $product) { + $parity = ($parity == "impair") ? 'pair' : 'impair'; - // check new product ? - $newapp = ''; - if ($last_month < strtotime($product->date_add)) { - $newapp .= ''.$langs->trans('New').' '; - } + // check new product ? + $newapp = ''; + if ($last_month < strtotime($product->date_add)) { + $newapp .= ''.$langs->trans('New').' '; + } - // check updated ? - if ($last_month < strtotime($product->date_upd) && $newapp == '') { - $newapp .= ''.$langs->trans('Updated').' '; - } + // check updated ? + if ($last_month < strtotime($product->date_upd) && $newapp == '') { + $newapp .= ''.$langs->trans('Updated').' '; + } - // add image or default ? - if ($product->id_default_image != '') { - $image_url = DOL_URL_ROOT.'/admin/dolistore/ajax/image.php?id_product='.$product->id.'&id_image='.$product->id_default_image; - $images = ''. - ''; - } else { - $images = ''; - } + // add image or default ? + if ($product->id_default_image != '') { + $image_url = DOL_URL_ROOT.'/admin/dolistore/ajax/image.php?id_product='.$product->id.'&id_image='.$product->id_default_image; + $images = ''. + ''; + } else { + $images = ''; + } - // free or pay ? - if ($product->price > 0) { - $price = '

      '.price(round((float) $product->price * $this->vat_rate, 2)).' €

      '; - $download_link = ''; - } else { - $price = '

      '.$langs->trans('Free').'

      '; - $download_link = ''; - $download_link.= '

      '; - } + // free or pay ? + if ($product->price > 0) { + $price = '

      '.price(round((float) $product->price * $this->vat_rate, 2)).' €

      '; + $download_link = ''; + } else { + $price = '

      '.$langs->trans('Free').'

      '; + $download_link = ''; + $download_link.= '

      '; + } - //checking versions - if ($this->version_compare($product->dolibarr_min, DOL_VERSION) <= 0) { - if ($this->version_compare($product->dolibarr_max, DOL_VERSION) >= 0) { - //compatible - $version = ''.$langs->trans('CompatibleUpTo', $product->dolibarr_max, - $product->dolibarr_min, $product->dolibarr_max).''; - $compatible = ''; - } else { - //never compatible, module expired - $version = ''.$langs->trans('NotCompatible', DOL_VERSION, - $product->dolibarr_min, $product->dolibarr_max).''; - $compatible = 'NotCompatible'; - } - } else { - //need update - $version = ''.$langs->trans('CompatibleAfterUpdate', DOL_VERSION, - $product->dolibarr_min, $product->dolibarr_max).''; - $compatible = 'NotCompatible'; - } + //checking versions + if ($this->version_compare($product->dolibarr_min, DOL_VERSION) <= 0) { + if ($this->version_compare($product->dolibarr_max, DOL_VERSION) >= 0) { + //compatible + $version = ''.$langs->trans('CompatibleUpTo', $product->dolibarr_max, + $product->dolibarr_min, $product->dolibarr_max).''; + $compatible = ''; + } else { + //never compatible, module expired + $version = ''.$langs->trans('NotCompatible', DOL_VERSION, + $product->dolibarr_min, $product->dolibarr_max).''; + $compatible = 'NotCompatible'; + } + } else { + //need update + $version = ''.$langs->trans('CompatibleAfterUpdate', DOL_VERSION, + $product->dolibarr_min, $product->dolibarr_max).''; + $compatible = 'NotCompatible'; + } - //.'
      '.$langs->trans("SeeInMarkerPlace").' + //.'
      '.$langs->trans("SeeInMarkerPlace").' - //output template - $html .= ' + //output template + $html .= '
      '.$newapp.$images.'

      '.$product->name->language[$this->lang] - .'
      '.$version.'

      + .'
      '.$version.' '.dol_print_date(dol_stringtotime($product->date_upd), 'dayhour').' - '.$langs->trans('Ref').': '.$product->reference.' - '.$langs->trans('Id').': '.$product->id.'

      '.$product->description_short->language[$this->lang].' '.$product->description->language[$this->lang].' '.$price.' '.$download_link.' '; - } - return $html; - } + } + return $html; + } - function get_previous_link($text = '<<') - { - return ''.$text.''; - } + function get_previous_link($text = '<<') + { + return ''.$text.''; + } - function get_next_link($text = '>>') - { - return ''.$text.''; - } + function get_next_link($text = '>>') + { + return ''.$text.''; + } - function get_previous_url() - { - $param_array = array(); - if ($this->start < $this->per_page) { - $sub = 0; - } else { - $sub = $this->per_page; - } - $param_array['start'] = $this->start - $sub; - $param_array['end'] = $this->end - $sub; - if ($this->categorie != 0) { - $param_array['categorie'] = $this->categorie; - } - $param = http_build_query($param_array); - return $this->url."&".$param; - } + function get_previous_url() + { + $param_array = array(); + if ($this->start < $this->per_page) { + $sub = 0; + } else { + $sub = $this->per_page; + } + $param_array['start'] = $this->start - $sub; + $param_array['end'] = $this->end - $sub; + if ($this->categorie != 0) { + $param_array['categorie'] = $this->categorie; + } + $param = http_build_query($param_array); + return $this->url."&".$param; + } - function get_next_url() - { - $param_array = array(); - if (count($this->products) < $this->per_page) { - $add = 0; - } else { - $add = $this->per_page; - } - $param_array['start'] = $this->start + $add; - $param_array['end'] = $this->end + $add; - if ($this->categorie != 0) { - $param_array['categorie'] = $this->categorie; - } - $param = http_build_query($param_array); - return $this->url."&".$param; - } + function get_next_url() + { + $param_array = array(); + if (count($this->products) < $this->per_page) { + $add = 0; + } else { + $add = $this->per_page; + } + $param_array['start'] = $this->start + $add; + $param_array['end'] = $this->end + $add; + if ($this->categorie != 0) { + $param_array['categorie'] = $this->categorie; + } + $param = http_build_query($param_array); + return $this->url."&".$param; + } - function version_compare($v1, $v2) - { - $v1 = explode('.', $v1); - $v2 = explode('.', $v2); - $ret = 0; - $level = 0; - $count1 = count($v1); - $count2 = count($v2); - $maxcount = max($count1, $count2); - while ($level < $maxcount) { - $operande1 = isset($v1[$level]) ? $v1[$level] : 'x'; - $operande2 = isset($v2[$level]) ? $v2[$level] : 'x'; - $level++; - if (strtoupper($operande1) == 'X' || strtoupper($operande2) == 'X' || $operande1 == '*' || $operande2 == '*') { - break; - } - if ($operande1 < $operande2) { - $ret = -$level; - break; - } - if ($operande1 > $operande2) { - $ret = $level; - break; - } - } - //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'
      '."\n"; - return $ret; - } + function version_compare($v1, $v2) + { + $v1 = explode('.', $v1); + $v2 = explode('.', $v2); + $ret = 0; + $level = 0; + $count1 = count($v1); + $count2 = count($v2); + $maxcount = max($count1, $count2); + while ($level < $maxcount) { + $operande1 = isset($v1[$level]) ? $v1[$level] : 'x'; + $operande2 = isset($v2[$level]) ? $v2[$level] : 'x'; + $level++; + if (strtoupper($operande1) == 'X' || strtoupper($operande2) == 'X' || $operande1 == '*' || $operande2 == '*') { + break; + } + if ($operande1 < $operande2) { + $ret = -$level; + break; + } + if ($operande1 > $operande2) { + $ret = $level; + break; + } + } + //print join('.',$versionarray1).'('.count($versionarray1).') / '.join('.',$versionarray2).'('.count($versionarray2).') => '.$ret.'
      '."\n"; + return $ret; + } } diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index 2322ae7a057..256dd08f9a8 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -1,8 +1,8 @@ +/* Copyright (C) 2001-2005 Rodolphe Quiedeville * Copyright (C) 2004-2015 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2016 Juanjo Menent + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2016 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,29 +47,36 @@ if (! $user->admin) accessforbidden(); $action = GETPOST('action','aZ09'); - if (! defined("MAIN_MOTD")) define("MAIN_MOTD",""); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$contextpage=array('adminihm','globaladmin'); +$hookmanager->initHooks($contextpage); + /* * Action */ +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if (GETPOST('cancel','alpha')) { - $action=''; + $action=''; } if ($action == 'removebackgroundlogin' && ! empty($conf->global->MAIN_LOGIN_BACKGROUND)) { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $logofile=$conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; - dol_delete_file($logofile); - dolibarr_del_const($db, "MAIN_LOGIN_BACKGROUND",$conf->entity); - $mysoc->logo=''; + $logofile=$conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; + dol_delete_file($logofile); + dolibarr_del_const($db, "MAIN_LOGIN_BACKGROUND",$conf->entity); + $mysoc->logo=''; - /*$logosmallfile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; + /*$logosmallfile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; dol_delete_file($logosmallfile); dolibarr_del_const($db, "MAIN_INFO_SOCIETE_LOGO_SMALL",$conf->entity); $mysoc->logo_small=''; @@ -89,54 +96,58 @@ if ($action == 'update') $val=GETPOST('THEME_TOPMENU_DISABLE_IMAGE'); if (! $val) dolibarr_del_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', $conf->entity); - else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'),'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'),'chaine',0,'',$conf->entity); $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKBODY'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKBODY', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_BACKBODY', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'),array())))); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TOPMENU_BACK1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1'),array())))); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_VERMENU_BACK1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_VERMENU_BACK1', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_VERMENU_BACK1', $val,'chaine',0,'',$conf->entity); + + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKTITLE1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'),array())))); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val,'chaine',0,'',$conf->entity); - if (GETPOST('THEME_ELDY_USE_HOVER') == '') dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", '0', 'chaine', 0, '', $conf->entity); // If empty, we set to '0' ('000000' is for black) + if (GETPOST('THEME_ELDY_USE_HOVER') == '') dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", '0', 'chaine', 0, '', $conf->entity); // If empty, we set to '0' ('000000' is for black) else dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $_POST["THEME_ELDY_USE_HOVER"], 'chaine', 0, '', $conf->entity); $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTLINK'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTLINK', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val,'chaine',0,'',$conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val,'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", $_POST["main_size_liste_limit"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", $_POST["main_size_shortliste_limit"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_DISABLE_JAVASCRIPT", $_POST["main_disable_javascript"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", $_POST["MAIN_BUTTON_HIDE_UNAUTHORIZED"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_START_WEEK", $_POST["MAIN_START_WEEK"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_DAYS", $_POST["MAIN_DEFAULT_WORKING_DAYS"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_HOURS", $_POST["MAIN_DEFAULT_WORKING_HOURS"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SHOW_LOGO", $_POST["MAIN_SHOW_LOGO"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_FIRSTNAME_NAME_POSITION", $_POST["MAIN_FIRSTNAME_NAME_POSITION"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", $_POST["main_size_liste_limit"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", $_POST["main_size_shortliste_limit"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_JAVASCRIPT", $_POST["main_disable_javascript"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", $_POST["MAIN_BUTTON_HIDE_UNAUTHORIZED"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_START_WEEK", $_POST["MAIN_START_WEEK"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_DAYS", $_POST["MAIN_DEFAULT_WORKING_DAYS"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_HOURS", $_POST["MAIN_DEFAULT_WORKING_HOURS"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SHOW_LOGO", $_POST["MAIN_SHOW_LOGO"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_FIRSTNAME_NAME_POSITION", $_POST["MAIN_FIRSTNAME_NAME_POSITION"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_HELPCENTER_DISABLELINK", $_POST["MAIN_HELPCENTER_DISABLELINK"],'chaine',0,'',0); // Param for all entities dolibarr_set_const($db, "MAIN_MOTD", dol_htmlcleanlastbr($_POST["main_motd"]),'chaine',0,'',$conf->entity); @@ -147,43 +158,43 @@ if ($action == 'update') $varforimage='imagebackground'; $dirforimage=$conf->mycompany->dir_output.'/logos/'; if ($_FILES[$varforimage]["tmp_name"]) { - if (preg_match('/([^\\/:]+)$/i',$_FILES[$varforimage]["name"],$reg)) - { - $original_file=$reg[1]; + if (preg_match('/([^\\/:]+)$/i',$_FILES[$varforimage]["name"],$reg)) + { + $original_file=$reg[1]; - $isimage=image_format_supported($original_file); - if ($isimage >= 0) - { - dol_syslog("Move file ".$_FILES[$varforimage]["tmp_name"]." to ".$dirforimage.$original_file); - if (! is_dir($dirforimage)) - { - dol_mkdir($dirforimage); - } - $result=dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"],$dirforimage.$original_file,1,0,$_FILES[$varforimage]['error']); - if ($result > 0) - { - dolibarr_set_const($db, "MAIN_LOGIN_BACKGROUND",$original_file,'chaine',0,'',$conf->entity); - } - else if (preg_match('/^ErrorFileIsInfectedWithAVirus/',$result)) - { - $error++; - $langs->load("errors"); - $tmparray=explode(':',$result); - setEventMessages($langs->trans('ErrorFileIsInfectedWithAVirus',$tmparray[1]), null, 'errors'); - } - else - { - $error++; - setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); - } - } - else - { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorBadImageFormat"), null, 'errors'); - } - } + $isimage=image_format_supported($original_file); + if ($isimage >= 0) + { + dol_syslog("Move file ".$_FILES[$varforimage]["tmp_name"]." to ".$dirforimage.$original_file); + if (! is_dir($dirforimage)) + { + dol_mkdir($dirforimage); + } + $result=dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"],$dirforimage.$original_file,1,0,$_FILES[$varforimage]['error']); + if ($result > 0) + { + dolibarr_set_const($db, "MAIN_LOGIN_BACKGROUND",$original_file,'chaine',0,'',$conf->entity); + } + else if (preg_match('/^ErrorFileIsInfectedWithAVirus/',$result)) + { + $error++; + $langs->load("errors"); + $tmparray=explode(':',$result); + setEventMessages($langs->trans('ErrorFileIsInfectedWithAVirus',$tmparray[1]), null, 'errors'); + } + else + { + $error++; + setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); + } + } + else + { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorBadImageFormat"), null, 'errors'); + } + } } @@ -214,59 +225,59 @@ print "
      \n"; if ($action == 'edit') // Edit { - //WYSIWYG Editor - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + //WYSIWYG Editor + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - print '
      '; - print ''; - print ''; + print ''; + print ''; + print ''; - clearstatcache(); + clearstatcache(); - print '
      '; - print ''; - print ''; + print '
      '; + print '
      '.$langs->trans("Language").'
      '; + print ''; print ''; print ''; - // Default language - print ''; + // Default language + print ''; print ''; print ''; // Multilingual GUI - print ''; + print ''; print ''; print ''; print '
      '.$langs->trans("Language").' 
      '.$langs->trans("DefaultLanguage").''; - print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT, 'MAIN_LANG_DEFAULT', 1, 0, 0, 0, 0, 'minwidth300'); - print '
      '.$langs->trans("DefaultLanguage").''; + print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT, 'MAIN_LANG_DEFAULT', 1, 0, 0, 0, 0, 'minwidth300'); + print ' 
      '.$langs->trans("EnableMultilangInterface").''; - print $form->selectyesno('MAIN_MULTILANGS',$conf->global->MAIN_MULTILANGS,1); - print '
      '.$langs->trans("EnableMultilangInterface").''; + print $form->selectyesno('MAIN_MULTILANGS',$conf->global->MAIN_MULTILANGS,1); + print ' 

      '."\n"; - // Themes and themes options - show_theme(null,1); - print '
      '; + // Themes and themes options + show_theme(null,1); + print '
      '; - // Other - print ''; - print ''; + // Other + print '
      '.$langs->trans("Parameters").''.$langs->trans("Value").'
      '; + print ''; print ''; print ''; // Max size of lists - print ''; + print ''; print ''; print ''; // Max size of short lists on customer card - print ''; + print ''; print ''; print ''; - // show input border - /* + // show input border + /* print ''; @@ -275,38 +286,38 @@ if ($action == 'edit') // Edit */ // Disable javascript and ajax - print ''; + print ''; print ''; print ''; - // First day for weeks - print ''; + // First day for weeks + print ''; print ''; print ''; - // DefaultWorkingDays - print ''; + // DefaultWorkingDays + print ''; print ''; print ''; - // DefaultWorkingHours - print ''; + // DefaultWorkingHours + print ''; print ''; print ''; // Firstname/Name - print ''; + print $form->selectarray('MAIN_FIRSTNAME_NAME_POSITION',$array,(isset($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?$conf->global->MAIN_FIRSTNAME_NAME_POSITION:0)); + print ''; print ''; print ''; @@ -342,27 +353,27 @@ if ($action == 'edit') // Edit print ''; // Hide wiki link on login page - print ''; + print ''; print ''; print ''; // Message of the day on home page - $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount')); - complete_substitutions_array($substitutionarray, $langs); + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount')); + complete_substitutions_array($substitutionarray, $langs); - print ''."\n"; @@ -379,12 +390,12 @@ if ($action == 'edit') // Edit // Message on login page $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount','user')); - complete_substitutions_array($substitutionarray, $langs); - print ''; @@ -418,31 +429,31 @@ if ($action == 'edit') // Edit print '
      '.$langs->trans("Parameters").''.$langs->trans("Value").' 
      '.$langs->trans("DefaultMaxSizeList").'
      '.$langs->trans("DefaultMaxSizeList").' 
      '.$langs->trans("DefaultMaxSizeShortList").'
      '.$langs->trans("DefaultMaxSizeShortList").' 
      '.$langs->trans("showInputBorder").''; print $form->selectyesno('main_showInputBorder',isset($conf->global->THEME_ELDY_SHOW_BORDER_INPUT)?$conf->global->THEME_ELDY_SHOW_BORDER_INPUT:0,1); print '
      '.$langs->trans("DisableJavascript").''; - print $form->selectyesno('main_disable_javascript',isset($conf->global->MAIN_DISABLE_JAVASCRIPT)?$conf->global->MAIN_DISABLE_JAVASCRIPT:0,1); - print '
      '.$langs->trans("DisableJavascript").''; + print $form->selectyesno('main_disable_javascript',isset($conf->global->MAIN_DISABLE_JAVASCRIPT)?$conf->global->MAIN_DISABLE_JAVASCRIPT:0,1); + print ' 
      '.$langs->trans("WeekStartOnDay").''; - print $formother->select_dayofweek((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'),'MAIN_START_WEEK',0); - print '
      '.$langs->trans("WeekStartOnDay").''; + print $formother->select_dayofweek((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'),'MAIN_START_WEEK',0); + print ' 
      '.$langs->trans("DefaultWorkingDays").''; - print ''; - print '
      '.$langs->trans("DefaultWorkingDays").''; + print ''; + print ' 
      '.$langs->trans("DefaultWorkingHours").''; - print ''; - print '
      '.$langs->trans("DefaultWorkingHours").''; + print ''; + print ' 
      '.$langs->trans("FirstnameNamePosition").''; + print '
      '.$langs->trans("FirstnameNamePosition").''; $array=array(0=>$langs->trans("Firstname").' '.$langs->trans("Lastname"),1=>$langs->trans("Lastname").' '.$langs->trans("Firstname")); - print $form->selectarray('MAIN_FIRSTNAME_NAME_POSITION',$array,(isset($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?$conf->global->MAIN_FIRSTNAME_NAME_POSITION:0)); - print ' 
      '.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; - print $form->selectyesno('MAIN_HELP_DISABLELINK', isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0,1); - print '
      '.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; + print $form->selectyesno('MAIN_HELP_DISABLELINK', isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0,1); + print ' 
      '; - $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
      '; - foreach($substitutionarray as $key => $val) - { - $texthelp.=$key.'
      '; - } - print $form->textwithpicto($langs->trans("MessageOfDay"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessageofday'); + print '
      '; + $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
      '; + foreach($substitutionarray as $key => $val) + { + $texthelp.=$key.'
      '; + } + print $form->textwithpicto($langs->trans("MessageOfDay"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessageofday'); - print '
      '; + print ''; - $doleditor = new DolEditor('main_motd', (isset($conf->global->MAIN_MOTD)?$conf->global->MAIN_MOTD:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); + $doleditor = new DolEditor('main_motd', (isset($conf->global->MAIN_MOTD)?$conf->global->MAIN_MOTD:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); $doleditor->Create(); print '
      '; + complete_substitutions_array($substitutionarray, $langs); + print '
      '; $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
      '; foreach($substitutionarray as $key => $val) { - $texthelp.=$key.'
      '; + $texthelp.=$key.'
      '; } print $form->textwithpicto($langs->trans("MessageLogin"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessagelogin'); print '
      '; @@ -401,16 +412,16 @@ if ($action == 'edit') // Edit // Background print '
      '; - print '
      '; + print '
      '; print ''; if (! empty($conf->global->MAIN_LOGIN_BACKGROUND)) { - print ''.img_delete($langs->trans("Delete")).''; - if (file_exists($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) { - print '   '; - print ''; - } + print ''.img_delete($langs->trans("Delete")).''; + if (file_exists($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) { + print '   '; + print ''; + } } else { - print ''; + print ''; } print '
      '; print '
      '."\n"; - print '
      '; - print ''; - print '   '; - print ''; - print '
      '; + print '
      '; + print ''; + print '   '; + print ''; + print '
      '; - print '
      '; + print ''; } else // Show { - // Language - print ''; - print ''; + // Language + print '
      '.$langs->trans("Language").' 
      '; + print ''; - print ''; + print ''; print ''; print ""; - print ''; + print ''; print ''; print ""; @@ -450,19 +461,19 @@ else // Show // Themes - show_theme(null,0); - print '
      '; + show_theme(null,0); + print '
      '; - // Other - print '
      '.$langs->trans("Language").' 
      '.$langs->trans("DefaultLanguage").''; - $s=picto_from_langcode($conf->global->MAIN_LANG_DEFAULT); - print ($s?$s.' ':''); - print ($conf->global->MAIN_LANG_DEFAULT=='auto'?$langs->trans("AutoDetectLang"):$langs->trans("Language_".$conf->global->MAIN_LANG_DEFAULT)); - print '
      '.$langs->trans("DefaultLanguage").''; + $s=picto_from_langcode($conf->global->MAIN_LANG_DEFAULT); + print ($s?$s.' ':''); + print ($conf->global->MAIN_LANG_DEFAULT=='auto'?$langs->trans("AutoDetectLang"):$langs->trans("Language_".$conf->global->MAIN_LANG_DEFAULT)); + print ''; - if ($user->admin && $conf->global->MAIN_LANG_DEFAULT!='auto') print info_admin($langs->trans("SubmitTranslation".($conf->global->MAIN_LANG_DEFAULT=='en_US'?'ENUS':''),$conf->global->MAIN_LANG_DEFAULT),1); + if ($user->admin && $conf->global->MAIN_LANG_DEFAULT!='auto') print info_admin($langs->trans("SubmitTranslation".($conf->global->MAIN_LANG_DEFAULT=='en_US'?'ENUS':''),$conf->global->MAIN_LANG_DEFAULT),1); print '
      '.$langs->trans("EnableMultilangInterface").'' . yn($conf->global->MAIN_MULTILANGS) . '
      '.$langs->trans("EnableMultilangInterface").'' . yn($conf->global->MAIN_MULTILANGS) . ' 
      '; - print ''; + // Other + print '
      '.$langs->trans("Parameters").''.$langs->trans("Value").'
      '; + print ''; - print ''; + print ''; print ''; print ""; - print ''; + print ''; print ''; print ""; @@ -473,38 +484,38 @@ else // Show print ""; */ - // Disable javascript/ajax - print '"; - print ''; - print ""; + // Disable javascript/ajax + print '"; + print ''; + print ""; // First day for weeks - print ''; + print ''; print ''; print ''; - // DefaultWorkingDays - print ''; + // DefaultWorkingDays + print ''; print ''; print ''; - // DefaultWorkingHours - print ''; + // DefaultWorkingHours + print ''; print ''; print ''; // Firstname / Name position - print ''; + print ''; print ''; print ''; @@ -513,8 +524,8 @@ else // Show print yn((isset($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)?$conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED:0),1); print ''; - // Show logo - print ''; + // Show logo + print ''; print ''; print ""; @@ -527,62 +538,62 @@ else // Show print ''; */ - // Show bugtrack link + // Show bugtrack link print '"; print ''; print ""; - // Link to wiki help - print ''; + // Link to wiki help + print ''; - // Message of the day - print ''."\n"; + // Message of the day + print ''."\n"; - print '
      '.$langs->trans("Parameters").''.$langs->trans("Value").'
      '.$langs->trans("DefaultMaxSizeList").'' . $conf->global->MAIN_SIZE_LISTE_LIMIT . '
      '.$langs->trans("DefaultMaxSizeList").'' . $conf->global->MAIN_SIZE_LISTE_LIMIT . ' 
      '.$langs->trans("DefaultMaxSizeShortList").'' . $conf->global->MAIN_SIZE_SHORTLIST_LIMIT . '
      '.$langs->trans("DefaultMaxSizeShortList").'' . $conf->global->MAIN_SIZE_SHORTLIST_LIMIT . ' 
      '.$langs->trans("DisableJavascript").''; - print yn($conf->global->MAIN_DISABLE_JAVASCRIPT)." 
      '.$langs->trans("DisableJavascript").''; + print yn($conf->global->MAIN_DISABLE_JAVASCRIPT)." 
      '.$langs->trans("WeekStartOnDay").''; - print $langs->trans("Day".(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1')); - print '
      '.$langs->trans("WeekStartOnDay").''; + print $langs->trans("Day".(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1')); + print ' 
      '.$langs->trans("DefaultWorkingDays").''; - print isset($conf->global->MAIN_DEFAULT_WORKING_DAYS)?$conf->global->MAIN_DEFAULT_WORKING_DAYS:'1-5'; - print '
      '.$langs->trans("DefaultWorkingDays").''; + print isset($conf->global->MAIN_DEFAULT_WORKING_DAYS)?$conf->global->MAIN_DEFAULT_WORKING_DAYS:'1-5'; + print ' 
      '.$langs->trans("DefaultWorkingHours").''; - print isset($conf->global->MAIN_DEFAULT_WORKING_HOURS)?$conf->global->MAIN_DEFAULT_WORKING_HOURS:'9-18'; - print '
      '.$langs->trans("DefaultWorkingHours").''; + print isset($conf->global->MAIN_DEFAULT_WORKING_HOURS)?$conf->global->MAIN_DEFAULT_WORKING_HOURS:'9-18'; + print ' 
      '.$langs->trans("FirstnameNamePosition").''; - if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { print $langs->trans("Firstname").' '.$langs->trans("Lastname"); } - else { print $langs->trans("Lastname").' '.$langs->trans("Firstname"); } - print '
      '.$langs->trans("FirstnameNamePosition").''; + if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { print $langs->trans("Firstname").' '.$langs->trans("Lastname"); } + else { print $langs->trans("Lastname").' '.$langs->trans("Firstname"); } + print ' 
      '.$langs->trans("EnableShowLogo").'' . yn($conf->global->MAIN_SHOW_LOGO) . '
      '.$langs->trans("EnableShowLogo").'' . yn($conf->global->MAIN_SHOW_LOGO) . ' 
      '.$langs->trans("ShowBugTrackLink", $langs->transnoentitiesnoconv("FindBug")).''; print yn($conf->global->MAIN_BUGTRACK_ENABLELINK)." 
      '.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; - print yn((isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0),1); - print '
      '.$langs->trans("DisableLinkToHelp",img_picto('',DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/helpdoc.png','',1)).''; + print yn((isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0),1); + print '
      '.$langs->trans("MessageOfDay").''; - if (isset($conf->global->MAIN_MOTD)) print dol_htmlcleanlastbr($conf->global->MAIN_MOTD); - else print ' '; - print '
      '.$langs->trans("MessageOfDay").''; + if (isset($conf->global->MAIN_MOTD)) print dol_htmlcleanlastbr($conf->global->MAIN_MOTD); + else print ' '; + print '
      '."\n"; + print ''."\n"; - print '
      '; + print '
      '; - // Login page - print ''; - print ''; + // Login page + print '
      '.$langs->trans("LoginPage").' 
      '; + print ''; - // Message login - print ''."\n"; + // Message login + print ''."\n"; // Link to help center - print ''; + print ''; - // Background login - print ''; + // Background login + print ''; - print '
      '.$langs->trans("LoginPage").' 
      '.$langs->trans("MessageLogin").''; - if (isset($conf->global->MAIN_HOME)) print dol_htmlcleanlastbr($conf->global->MAIN_HOME); - else print ' '; - print '
      '.$langs->trans("MessageLogin").''; + if (isset($conf->global->MAIN_HOME)) print dol_htmlcleanlastbr($conf->global->MAIN_HOME); + else print ' '; + print '
      '.$langs->trans("DisableLinkToHelpCenter").''; - print yn((isset($conf->global->MAIN_HELPCENTER_DISABLELINK)?$conf->global->MAIN_HELPCENTER_DISABLELINK:0),1); - print '
      '.$langs->trans("DisableLinkToHelpCenter").''; + print yn((isset($conf->global->MAIN_HELPCENTER_DISABLELINK)?$conf->global->MAIN_HELPCENTER_DISABLELINK:0),1); + print '
      '.$langs->trans("BackgroundImageLogin").''; - print '
      '; - print $conf->global->MAIN_LOGIN_BACKGROUND; - if ($conf->global->MAIN_LOGIN_BACKGROUND && is_file($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) - { - print ''; - } - else - { - print ''; - } - print '
      '; - print '
      '.$langs->trans("BackgroundImageLogin").''; + print '
      '; + print $conf->global->MAIN_LOGIN_BACKGROUND; + if ($conf->global->MAIN_LOGIN_BACKGROUND && is_file($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) + { + print ''; + } + else + { + print ''; + } + print '
      '; + print '
      '."\n"; + print ''."\n"; - print '
      '; - print ''.$langs->trans("Modify").''; - print '
      '; + print '
      '; + print ''.$langs->trans("Modify").''; + print '
      '; } diff --git a/htdocs/admin/ldap_members.php b/htdocs/admin/ldap_members.php index cad37cc4ccc..0dccb9967fe 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -1,10 +1,10 @@ - * Copyright (C) 2004 Sebastien Di Cintio - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2005 Regis Houssin - * Copyright (C) 2006-2008 Laurent Destailleur - * Copyright (C) 2011-2013 Juanjo Menent +/* Copyright (C) 2004 Rodolphe Quiedeville + * Copyright (C) 2004 Sebastien Di Cintio + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2006-2008 Laurent Destailleur + * Copyright (C) 2011-2013 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -66,8 +66,9 @@ if ($action == 'setvalue' && $user->admin) if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE',GETPOST("fieldphone"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_PHONE_PERSO',GETPOST("fieldphoneperso"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_MOBILE',GETPOST("fieldmobile"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_FAX',GETPOST("fieldfax"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_COMPANY',GETPOST("fieldcompany"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ADDRESS',GETPOST("fieldaddress"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_ZIP',GETPOST("fieldzip"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_MEMBER_FIELD_TOWN',GETPOST("fieldtown"),'chaine',0,'',$conf->entity)) $error++; @@ -84,22 +85,22 @@ if ($action == 'setvalue' && $user->admin) if (! dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE', GETPOST("fieldlastsubscriptiondate"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT', GETPOST("fieldlastsubscriptionamount"),'chaine',0,'',$conf->entity)) $error++; - // This one must be after the others - $valkey=''; - $key=GETPOST("key"); - if ($key) $valkey=$conf->global->$key; - if (! dolibarr_set_const($db, 'LDAP_KEY_MEMBERS',$valkey,'chaine',0,'',$conf->entity)) $error++; + // This one must be after the others + $valkey=''; + $key=GETPOST("key"); + if ($key) $valkey=$conf->global->$key; + if (! dolibarr_set_const($db, 'LDAP_KEY_MEMBERS',$valkey,'chaine',0,'',$conf->entity)) $error++; - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else - { - $db->rollback(); - dol_print_error($db); - } + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + dol_print_error($db); + } } @@ -282,6 +283,14 @@ print ''.$langs->trans("LDAPFieldFaxExample").''; print ' '; print ''; +// Company + +print ''.$langs->trans("LDAPFieldCompany").''; +print ''; +print ''.$langs->trans("LDAPFieldCompanyExample").''; +print ' '; +print ''; + // Address print ''.$langs->trans("LDAPFieldAddress").''; diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index a0866c1305a..8be03267783 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -63,28 +63,33 @@ if ($action == 'setvalue' && $user->admin) if (! dolibarr_set_const($db, 'LDAP_FIELD_MAIL',GETPOST("fieldmail"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_PHONE',GETPOST("fieldphone"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_MOBILE',GETPOST("fieldmobile"),'chaine',0,'',$conf->entity)) $error++; - if (! dolibarr_set_const($db, 'LDAP_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_SKYPE',GETPOST("fieldskype"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_FAX',GETPOST("fieldfax"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_COMPANY',GETPOST("fieldcompany"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_ADDRESS',GETPOST("fieldaddress"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_ZIP',GETPOST("fieldzip"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_TOWN',GETPOST("fieldtown"),'chaine',0,'',$conf->entity)) $error++; + if (! dolibarr_set_const($db, 'LDAP_FIELD_COUNTRY',GETPOST("fieldcountry"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_DESCRIPTION',GETPOST("fielddescription"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_SID',GETPOST("fieldsid"),'chaine',0,'',$conf->entity)) $error++; if (! dolibarr_set_const($db, 'LDAP_FIELD_TITLE',GETPOST("fieldtitle"),'chaine',0,'',$conf->entity)) $error++; - // This one must be after the others - $valkey=''; - $key=GETPOST("key"); - if ($key) $valkey=$conf->global->$key; - if (! dolibarr_set_const($db, 'LDAP_KEY_USERS',$valkey,'chaine',0,'',$conf->entity)) $error++; + // This one must be after the others + $valkey=''; + $key=GETPOST("key"); + if ($key) $valkey=$conf->global->$key; + if (! dolibarr_set_const($db, 'LDAP_KEY_USERS',$valkey,'chaine',0,'',$conf->entity)) $error++; - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else - { - $db->rollback(); - dol_print_error($db); - } + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + $db->rollback(); + dol_print_error($db); + } } @@ -208,7 +213,7 @@ print ''; print ''.$langs->trans("LDAPFieldPasswordNotCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_PASSWORD)?' checked':'').">"; +print ' '; print ''; // Password crypted @@ -216,7 +221,7 @@ print ''; print ''.$langs->trans("LDAPFieldPasswordCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_PASSWORD_CRYPTED)?' checked':'').">"; +print ' '; print ''; // Mail @@ -259,12 +264,52 @@ print ''.$langs->trans("LDAPFieldFaxExample").''; print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_FAX)?' checked':'').">"; print ''; +// Company + +print ''.$langs->trans("LDAPFieldCompany").''; +print ''; +print ''.$langs->trans("LDAPFieldCompanyExample").''; +print ' '; +print ''; + +// Address + +print ''.$langs->trans("LDAPFieldAddress").''; +print ''; +print ''.$langs->trans("LDAPFieldAddressExample").''; +print ' '; +print ''; + +// ZIP + +print ''.$langs->trans("LDAPFieldZip").''; +print ''; +print ''.$langs->trans("LDAPFieldZipExample").''; +print ' '; +print ''; + +// TOWN + +print ''.$langs->trans("LDAPFieldTown").''; +print ''; +print ''.$langs->trans("LDAPFieldTownExample").''; +print ' '; +print ''; + +// COUNTRY + +print ''.$langs->trans("LDAPFieldCountry").''; +print ''; +print ' '; +print ' '; +print ''; + // Title print ''.$langs->trans("LDAPFieldTitle").''; print ''; print ''.$langs->trans("LDAPFieldTitleExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_TITLE)?' checked':'').">"; +print ' '; print ''; // Note @@ -272,7 +317,7 @@ print ''; print ''.$langs->trans("Note").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").''; -print 'global->LDAP_KEY_USERS && $conf->global->LDAP_KEY_USERS==$conf->global->LDAP_FIELD_DESCRIPTION)?' checked':'').">"; +print ' '; print ''; // Sid @@ -385,7 +430,7 @@ if (function_exists("ldap_connect")) { $required_fields = array( $conf->global->LDAP_KEY_USERS, - $conf->global->LDAP_FIELD_FULLNAME, + $conf->global->LDAP_FIELD_FULLNAME, $conf->global->LDAP_FIELD_NAME, $conf->global->LDAP_FIELD_FIRSTNAME, $conf->global->LDAP_FIELD_LOGIN, @@ -394,7 +439,7 @@ if (function_exists("ldap_connect")) $conf->global->LDAP_FIELD_PASSWORD_CRYPTED, $conf->global->LDAP_FIELD_PHONE, $conf->global->LDAP_FIELD_FAX, - $conf->global->LDAP_FIELD_SKYPE, + $conf->global->LDAP_FIELD_SKYPE, $conf->global->LDAP_FIELD_MOBILE, $conf->global->LDAP_FIELD_MAIL, $conf->global->LDAP_FIELD_TITLE, @@ -402,35 +447,35 @@ if (function_exists("ldap_connect")) $conf->global->LDAP_FIELD_SID ); - // Remove from required_fields all entries not configured in LDAP (empty) and duplicated - $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); + // Remove from required_fields all entries not configured in LDAP (empty) and duplicated + $required_fields=array_unique(array_values(array_filter($required_fields, "dol_validElement"))); - // Get from LDAP database an array of results - $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); - //$ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, '', 1); + // Get from LDAP database an array of results + $ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 1); + //$ldapusers = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, '', 1); - if (is_array($ldapusers)) - { - $liste=array(); - foreach ($ldapusers as $key => $ldapuser) - { - // Define the label string for this user - $label=''; - foreach ($required_fields as $value) - { - if ($value) - { - $label.=$value."=".$ldapuser[$value]." "; - } - } - $liste[$key] = $label; - } + if (is_array($ldapusers)) + { + $liste=array(); + foreach ($ldapusers as $key => $ldapuser) + { + // Define the label string for this user + $label=''; + foreach ($required_fields as $value) + { + if ($value) + { + $label.=$value."=".$ldapuser[$value]." "; + } + } + $liste[$key] = $label; + } - } - else - { - setEventMessages($ldap->error, $ldap->errors, 'errors'); - } + } + else + { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } print "
      \n"; print "LDAP search for user:
      \n"; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index aa859b18a7e..d77f448f811 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -50,7 +50,7 @@ $substitutionarrayfortest=array( '__ID__' => 'RecipientIdRecord', //'__EMAIL__' => 'RecipientEMail', // Done into actions_sendmails '__CHECK_READ__' => (is_object($object) && is_object($object->thirdparty))?'':'', -'__SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), // Done into actions_sendmails +'__USER_SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), // Done into actions_sendmails '__LOGIN__' => 'RecipientLogin', '__LASTNAME__' => 'RecipientLastname', '__FIRSTNAME__' => 'RecipientFirstname', @@ -69,20 +69,20 @@ complete_substitutions_array($substitutionarrayfortest, $langs); if ($action == 'update' && empty($_POST["cancel"])) { - dolibarr_set_const($db, "MAIN_DISABLE_ALL_MAILS", GETPOST("MAIN_DISABLE_ALL_MAILS"),'chaine',0,'',$conf->entity); - // Send mode parameters - dolibarr_set_const($db, "MAIN_MAIL_SENDMODE", GETPOST("MAIN_MAIL_SENDMODE"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT", GETPOST("MAIN_MAIL_SMTP_PORT"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER", GETPOST("MAIN_MAIL_SMTP_SERVER"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID", GETPOST("MAIN_MAIL_SMTPS_ID"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); - // Content parameters - dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", GETPOST("MAIN_MAIL_AUTOCOPY_TO"),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE',GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_ALL_MAILS", GETPOST("MAIN_DISABLE_ALL_MAILS"),'chaine',0,'',$conf->entity); + // Send mode parameters + dolibarr_set_const($db, "MAIN_MAIL_SENDMODE", GETPOST("MAIN_MAIL_SENDMODE"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT", GETPOST("MAIN_MAIL_SMTP_PORT"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER", GETPOST("MAIN_MAIL_SMTP_SERVER"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID", GETPOST("MAIN_MAIL_SMTPS_ID"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); + // Content parameters + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", GETPOST("MAIN_MAIL_AUTOCOPY_TO"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE', GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; @@ -124,27 +124,7 @@ llxHeader('',$langs->trans("Setup"),$wikihelp); print load_fiche_titre($langs->trans("EMailsSetup"),'','title_setup'); - -$h = 0; - -$head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; -$head[$h][1] = $langs->trans("OutGoingEmailSetup"); -$head[$h][2] = 'common'; -$h++; - -if ($conf->mailing->enabled) -{ - $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php"; - $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing"); - $head[$h][2] = 'common_emailing'; - $h++; -} - -$head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; -$head[$h][1] = $langs->trans("DictionaryEMailTemplates"); -$head[$h][2] = 'templates'; -$h++; - +$head = email_admin_prepare_head(); // List of sending methods $listofmethods=array(); @@ -426,19 +406,36 @@ if ($action == 'edit') print ''; - // Default from type + // Default from type + $liste = array(); + $liste['user'] = $langs->trans('UserEmail'); + $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; + /* + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1'; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i=0; + while($i < $num) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + $liste['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; + } + $i++; + } + } + else dol_print_error($db);*/ - $liste = array(); - $liste['user'] = $langs->trans('UserEmail'); - $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; + print ''.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE', $liste, $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE, 0); + print ''; - print ''.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; - print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE',$liste,$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE,0); - print ''; + // Separator - // Separator - - print ' '; + print ' '; // From @@ -452,24 +449,24 @@ if ($action == 'edit') print ''; - print ''; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
      '; - print ''; - print '     '; - print ''; - print '
      '; + print '
      '; + print ''; + print '     '; + print ''; + print '
      '; print ''; } else { - dol_fiche_head($head, 'common', '', -1); + dol_fiche_head($head, 'common', '', -1); - print $langs->trans("EMailsDesc")."
      \n"; - print "
      \n"; + print $langs->trans("EMailsDesc")."
      \n"; + print "
      \n"; $var=true; @@ -569,21 +566,54 @@ else print ''; // Default from type + $liste = array(); + $liste['user'] = $langs->trans('UserEmail'); + $liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?$langs->trans("NotDefined"):$conf->global->MAIN_INFO_SOCIETE_MAIL).')'; + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1'; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i=0; + while($i < $num) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + $liste['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; + } + $i++; + } + } + else dol_print_error($db); - print ''.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; - print ''; - if($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user'){ - print $langs->trans('UserEmail'); - } else { - print $langs->trans('CompanyEmail'); - } - print ''; + print ''.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + print ''; + if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user') + { + print $langs->trans('UserEmail'); + } + else if ($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'company') + { + print $langs->trans('CompanyEmail').' '.dol_escape_htmltag('<'.$mysoc->email.'>'); + } + else { + $id = preg_replace('/senderprofile_/', '', $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE); + if ($id > 0) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php'; + $emailsenderprofile = new EmailSenderProfile($db); + $emailsenderprofile->fetch($id); + print $emailsenderprofile->label.' '.dol_escape_htmltag('<'.$emailsenderprofile->email.'>'); + } + } + print ''; // Separator print ' '; - // Errors To + // Errors To print ''.$langs->trans("MAIN_MAIL_ERRORS_TO").''; print ''.$conf->global->MAIN_MAIL_ERRORS_TO; @@ -610,10 +640,10 @@ else dol_fiche_end(); - if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) - { - print '
      '; - /* + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { + print '
      '; + /* // Warning 1 if ($linuxlike) { @@ -623,9 +653,9 @@ else print info_admin($langs->trans("SendmailOptionNotComplete")); } }*/ - // Warning 2 - print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); - } + // Warning 2 + print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); + } // Boutons actions @@ -657,8 +687,8 @@ else if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && ! in_array($action, array('testconnect', 'test', 'testhtml'))) { - $text = $langs->trans("WarningPHPMail"); - print info_admin($text); + $text = $langs->trans("WarningPHPMail"); + print info_admin($text); } // Run the test to connect @@ -686,7 +716,7 @@ else // Show email send test form if ($action == 'test' || $action == 'testhtml') { - print '
      '; + print '
      '; print load_fiche_titre($action == 'testhtml'?$langs->trans("DoTestSendHTML"):$langs->trans("DoTestSend")); dol_fiche_head(''); @@ -722,7 +752,7 @@ else $formmail->param["returnurl"]=$_SERVER["PHP_SELF"]; // Init list of files - if (GETPOST("mode")=='init') + if (GETPOST("mode")=='init') { $formmail->clear_attached_files(); } diff --git a/htdocs/admin/mails_emailing.php b/htdocs/admin/mails_emailing.php index b98661edab5..1202e9817d3 100644 --- a/htdocs/admin/mails_emailing.php +++ b/htdocs/admin/mails_emailing.php @@ -51,7 +51,7 @@ $substitutionarrayfortest=array( '__EMAIL__' => 'TESTEMail', '__LASTNAME__' => 'TESTLastname', '__FIRSTNAME__' => 'TESTFirstname', -'__SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), +'__USER_SIGNATURE__' => (($user->signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$usersignature:''), //'__PERSONALIZED__' => 'TESTPersonalized' // Hiden because not used yet ); complete_substitutions_array($substitutionarrayfortest, $langs); @@ -114,27 +114,7 @@ llxHeader('',$langs->trans("Setup"),$wikihelp); print load_fiche_titre($langs->trans("EMailsSetup"),'','title_setup'); - -$h = 0; - -$head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; -$head[$h][1] = $langs->trans("OutGoingEmailSetup"); -$head[$h][2] = 'common'; -$h++; - -if ($conf->mailing->enabled) -{ - $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php"; - $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing"); - $head[$h][2] = 'common_emailing'; - $h++; -} - -$head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; -$head[$h][1] = $langs->trans("DictionaryEMailTemplates"); -$head[$h][2] = 'templates'; -$h++; - +$head = email_admin_prepare_head(); // List of sending methods $listofmethods=array(); diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php new file mode 100644 index 00000000000..2190705ea8b --- /dev/null +++ b/htdocs/admin/mails_senderprofile_list.php @@ -0,0 +1,646 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/mails_senderprofile_list.php + * \ingroup core + * \brief Page to adminsiter email sender profiles + */ + +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test done when option MAIN_SECURITY_CSRF_WITH_TOKEN is on. +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) + + +require '../main.inc.php'; +require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php'; + +// Load traductions files requiredby by page +$langs->loadLangs(array("errors","admin","mails","languages")); + +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; +$massaction = GETPOST('massaction','alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files','int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'emailsenderprofilelist'; // To manage different context of search +$backtopage = GETPOST('backtopage','alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss','aZ'); // Option for the css output (always '' except when 'print') + +$id = GETPOST('id','int'); + +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object=new EmailSenderProfile($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->monmodule->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('emailsenderprofilelist')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('emailsenderprofile'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (! $sortfield) $sortfield="t.".key($object->fields); // Set here default search field. By default 1st field in definition. +if (! $sortorder) $sortorder="ASC"; + +// Protection if external user +$socid=0; +if ($user->societe_id > 0) +{ + //$socid = $user->societe_id; + accessforbidden(); +} + +// Initialize array of search criterias +$search_all=trim(GETPOST("search_all",'alpha')); +$search=array(); +foreach($object->fields as $key => $val) +{ + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach($object->fields as $key => $val) +{ + if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; +} + +// Definition of fields for list +$arrayfields=array(); +foreach($object->fields as $key => $val) +{ + // If $val['visible']==0, then we never show the field + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled']); +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } +} + + + + +/* + * Actions + */ + +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) +{ + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + foreach($object->fields as $key => $val) + { + $search[$key]=''; + } + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='EmailSenderProfile'; + $objectlabel='EmailSenderProfile'; + $permtoread = $user->admin; + $permtodelete = $user->admin; + $uploaddir = $conf->admin->dir_output.'/senderprofiles'; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + + +/* + * View + */ + +$form=new Form($db); + +$now=dol_now(); + +//$help_url="EN:Module_EmailSenderProfile|FR:Module_EmailSenderProfile_FR|ES:Módulo_EmailSenderProfile"; +$help_url=''; +$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("EmailSenderProfiles")); + + +llxHeader(); + +$titre=$langs->trans("EMailsSetup"); +$linkback=''; +$titlepicto='title_setup'; + +print load_fiche_titre($titre,$linkback,$titlepicto); + +$head = email_admin_prepare_head(); + +dol_fiche_head($head, 'senderprofiles', '', -1); + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// 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 +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql=preg_replace('/, $/','', $sql); +$sql.= " FROM ".MAIN_DB_PREFIX."c_email_senderprofile as t"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."emailsenderprofile_extrafields as ef on (t.rowid = ef.fk_object)"; +$sql.= " WHERE t.entity IN (".getEntity('emailsenderprofile').")"; +foreach($search as $key => $val) +{ + $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); + if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); +} +if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); +// Add where from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } +} +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +/* If a group by is required +$sql.= " GROUP BY " +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// Add fields from extrafields +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +*/ + +$sql.=$db->order($sortfield,$sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + +$sql.= $db->plimit($limit+1, $offset); + +dol_syslog($script_file, LOG_DEBUG); +$resql=$db->query($sql); +if (! $resql) +{ + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + +// Direct jump if only one record found +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +{ + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/monmodule/emailsenderprofile_card.php?id='.$id); + exit; +} + + +// Example : Adding jquery code +print ''; + +$arrayofselected=is_array($toselect)?$toselect:array(); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); +foreach($search as $key => $val) +{ + $param.= '&search_'.$key.'='.urlencode($search[$key]); +} +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +// List of mass actions available +$arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->monmodule->delete) $arrayofmassactions['delete']=$langs->trans("Delete"); +if ($massaction == 'presend') $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + +print '
      '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +//print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + +$moreforfilter = ''; +/*$moreforfilter.='
      '; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
      ';*/ + +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; + +if (! empty($moreforfilter)) +{ + print '
      '; + print $moreforfilter; + print '
      '; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
      '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Rest of fields search +foreach($object->fields as $key => $val) +{ + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print ''; +} +// Action column +print ''; +print ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print getTitleFieldOfList($langs->trans($extralabels[$key]), 0, $_SERVER["PHP_SELF"], $sortonfield, "", $param, ($align?'align="'.$align.'"':''), $sortfield, $sortorder)."\n"; + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Rest of fields title +foreach($object->fields as $key => $val) +{ + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.=' nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; +} +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine=0; +foreach ($extrafields->attribute_computed as $key => $val) +{ + if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object +} + + +// Loop on record +// -------------------------------------------------------------------- +$i=0; +$totalarray=array(); +while ($i < min($num, $limit)) +{ + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen + + // Store properties in $object + $object->id = $obj->rowid; + foreach($object->fields as $key => $val) + { + if (isset($obj->$key)) $object->$key = $obj->$key; + } + + // Show here line of result + print ''; + foreach($object->fields as $key => $val) + { + if (in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align='center'; + if (in_array($val['type'], array('timestamp'))) $align.='nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); + elseif ($key == 'ref') print $object->getNomUrl(1, '', 0, '', 1); + elseif ($key == 'status') print $object->getLibStatut(3); + else print $obj->$key; + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='ef.'.$tmpkey; + $totalarray['val']['ef.'.$tmpkey] += $obj->$tmpkey; + } + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Rest of fields + foreach($object->fields as $key => $val) + { + if (! in_array($key, array('date_creation', 'tms', 'import_key', 'status'))) continue; + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + if (in_array($val['type'], array('date','datetime','timestamp'))) print dol_print_date($db->jdate($obj->$key), 'dayhour'); + elseif ($key == 'status') print $object->getLibStatut(3); + else print $obj->$key; + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print ''; + + $i++; +} + +// Show total line +if (isset($totalarray['pos'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print ''; + else + { + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + else print ''; + } + } + print ''; +} + +// If no record found +if ($num == 0) +{ + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; +} + + +$db->free($resql); + +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
      '; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; +$searchpicto=$form->showFilterButtons(); +print $searchpicto; +print '
      '; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
      '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
      '.$langs->trans("NoRecordFound").'
      '."\n"; +print '
      '."\n"; + +print '
      '."\n"; + +if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) +{ + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->monmodule->read; + $delallowed=$user->rights->monmodule->read; + + print $formfile->showdocuments('massfilesarea_monmodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
      '.$langs->trans("ShowTempMassFilesArea").''; + } +} + +dol_fiche_end(); + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index 2f440f9f873..4e25e93084b 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -39,21 +39,18 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; 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'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -$langs->load("errors"); -$langs->load("admin"); -$langs->load("main"); -$langs->load("mails"); -$langs->load("languages"); +// Load traductions files requiredby by page +$langs->loadLangs(array("errors","admin","mails","languages")); -$action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; -$confirm=GETPOST('confirm','alpha'); -$id=GETPOST('id','int'); -$rowid=GETPOST('rowid','alpha'); +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation + +$id = GETPOST('id','int'); +$rowid = GETPOST('rowid','alpha'); $search_label=GETPOST('search_label','alpha'); $search_type_template=GETPOST('search_type_template','alpha'); -$search_topic=GETPOST('search_topic','alpha'); $search_lang=GETPOST('search_lang','alpha'); $search_fk_user=GETPOST('search_fk_user','intcomma'); $search_topic=GETPOST('search_topic','alpha'); @@ -67,7 +64,7 @@ $actl[0] = img_picto($langs->trans("Disabled"),'switch_off'); $actl[1] = img_picto($langs->trans("Activated"),'switch_on'); $listoffset=GETPOST('listoffset','alpha'); -$listlimit=GETPOST('listlimit','alpha')>0?GETPOST('listlimit','alpha'):1000; +$listlimit =GETPOST('listlimit','alpha')>0?GETPOST('listlimit','alpha'):1000; $active = 1; $sortfield = GETPOST("sortfield",'alpha'); @@ -94,26 +91,20 @@ $tabsqlsort[25]="label ASC, lang ASC, position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[25]= "label,type_template,lang,fk_user,private,position,topic,content"; +$tabfield[25]= "label,type_template,lang,fk_user,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfield[25].=',content_lines'; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[25]= "label,type_template,fk_user,lang,private,position,topic,content"; +$tabfieldvalue[25]= "label,type_template,fk_user,lang,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldvalue[25].=',content_lines'; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[25]= "label,type_template,fk_user,lang,private,position,topic,content"; +$tabfieldinsert[25]= "label,type_template,fk_user,lang,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldinsert[25].=',content_lines'; $tabfieldinsert[25].=',entity'; // Must be at end because not into other arrays -// Nom du rowid si le champ n'est pas de type autoincrement -// Example: "" if id field is "rowid" and has autoincrement on -// "nameoffield" if id field is not "rowid" or has not autoincrement on -$tabrowid=array(); -$tabrowid[25]= ""; - // Condition to show dictionary in setup page $tabcond=array(); $tabcond[25]= true; @@ -153,7 +144,7 @@ else $tabhelp=array(); -$tabhelp[25] = array('topic'=>$helpsubstit,'content'=>$helpsubstit,'content_lines'=>$helpsubstitforlines,'type_template'=>$langs->trans("TemplateForElement"),'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"), 'position'=>$langs->trans("PositionIntoComboList")); +$tabhelp[25] = array('topic'=>$helpsubstit,'joinfiles'=>$langs->trans('AttachMainDocByDefault'), 'content'=>$helpsubstit,'content_lines'=>$helpsubstitforlines,'type_template'=>$langs->trans("TemplateForElement"),'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"), 'position'=>$langs->trans("PositionIntoComboList")); // List of check for fields (NOT USED YET) $tabfieldcheck=array(); @@ -177,7 +168,8 @@ if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$la if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); if ($conf->adherent->enabled) $elementList['member']=$langs->trans('MailToMember'); if ($conf->contrat->enabled) $elementList['contract']=$langs->trans('MailToSendContract'); -$elementList['all']=$langs->trans('VisibleEverywhere'); +$elementList['user']=$langs->trans('MailToUser'); +$elementList['all'] =$langs->trans('VisibleEverywhere'); $elementList['none']=$langs->trans('VisibleNowhere'); @@ -229,10 +221,12 @@ if (empty($reshook)) $ok=1; foreach ($listfield as $f => $value) { + // Not mandatory fields + if ($value == 'joinfiles') continue; if ($value == 'content') continue; if ($value == 'content_lines') continue; - if ($value == 'content') $value='content-'.$rowid; - if ($value == 'content_lines') $value='content_lines-'.$rowid; + + if (GETPOST('actionmodify') && $value == 'topic') $_POST['topic']=$_POST['topic-'.$rowid]; if ((! isset($_POST[$value]) || $_POST[$value]=='' || $_POST[$value]=='-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position') { @@ -256,34 +250,14 @@ if (empty($reshook)) // Si verif ok et action add, on ajoute la ligne if ($ok && GETPOST('actionadd')) { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid=0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); - - } else { - dol_print_error($db); - } - } - // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $tabrowid[$id].","; $sql.= $tabfieldinsert[$id]; $sql.=",active)"; $sql.= " VALUES("; // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) - $sql.= $newid.","; $i=0; foreach ($listfieldinsert as $f => $value) { @@ -295,7 +269,7 @@ if (empty($reshook)) if ($value == 'fk_user' && ! ($_POST[$keycode] > 0)) $_POST[$keycode]=''; if ($value == 'private' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='0'; if ($value == 'position' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='1'; - if ($_POST[$keycode] == '' || ($keycode == 'langcode' && empty($_POST[$keycode]))) $sql.="null"; // For vat, we want/accept code = '' + if ($_POST[$keycode] == '' && $keycode != 'langcode') $sql.="null"; // lang must be '' if not defined so the unique key that include lang will work else $sql.="'".$db->escape($_POST[$keycode])."'"; $i++; } @@ -322,17 +296,11 @@ if (empty($reshook)) // Si verif ok et action modify, on modifie la ligne if ($ok && GETPOST('actionmodify')) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) - { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; - } $i = 0; foreach ($listfieldmodify as $field) { @@ -340,8 +308,10 @@ if (empty($reshook)) if ($field == 'lang') $keycode='langcode'; if ($field == 'fk_user' && ! ($_POST['fk_user'] > 0)) $_POST['fk_user']=''; + if ($field == 'topic') $_POST['topic']=$_POST['topic-'.$rowid]; + if ($field == 'joinfiles') $_POST['joinfiles']=$_POST['joinfiles-'.$rowid]; if ($field == 'content') $_POST['content']=$_POST['content-'.$rowid]; - if ($field == 'content_lines') $_POST['content_lines']=$_POST['content_lines-'.$rowid]; + if ($field == 'content_lines') $_POST['content_lines']=$_POST['content_lines-'.$rowid]; if ($field == 'entity') $_POST[$keycode] = $conf->entity; if ($i) $sql.=","; $sql.= $field."="; @@ -354,7 +324,11 @@ if (empty($reshook)) dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); - if (! $resql) + if ($resql) + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + } + else { setEventMessages($db->error(), null, 'errors'); } @@ -363,8 +337,7 @@ if (empty($reshook)) if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; @@ -386,15 +359,9 @@ if (empty($reshook)) // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'"; - } + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; $result = $db->query($sql); if (!$result) @@ -406,15 +373,9 @@ if (empty($reshook)) // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + $rowidcol="rowid"; - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; - } - elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'"; - } + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; $result = $db->query($sql); if (!$result) @@ -440,30 +401,7 @@ $titlepicto='title_setup'; print load_fiche_titre($titre,$linkback,$titlepicto); -$h = 0; - - -if ($user->admin && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) -{ - $head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; - $head[$h][1] = $langs->trans("OutGoingEmailSetup"); - $head[$h][2] = 'common'; - $h++; - - if (! empty($conf->mailing->enabled)) - { - $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php"; - $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing"); - $head[$h][2] = 'common_emailing'; - $h++; - } -} - -$head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; -$head[$h][1] = $langs->trans("DictionaryEMailTemplates"); -$head[$h][2] = 'templates'; -$h++; - +$head = email_admin_prepare_head(); dol_fiche_head($head, 'templates', '', -1); @@ -475,7 +413,7 @@ if ($action == 'delete') //var_dump($elementList); -$sql="SELECT rowid as rowid, label, type_template, lang, fk_user, private, position, topic, content_lines, content, active"; +$sql="SELECT rowid as rowid, label, type_template, lang, fk_user, private, position, topic, joinfiles, content_lines, content, active"; $sql.=" FROM ".MAIN_DB_PREFIX."c_email_templates"; $sql.=" WHERE entity IN (".getEntity('email_template').")"; if (! $user->admin) @@ -485,7 +423,7 @@ if (! $user->admin) } if (empty($conf->global->MAIN_MULTILANGS)) { - $sql.= " AND (lang = '".$langs->defaultlang."' OR lang IS NULL)"; + $sql.= " AND (lang = '".$langs->defaultlang."' OR lang IS NULL OR lang = '')"; } if ($search_label) $sql.=natural_search('label', $search_label); if ($search_type_template != '' && $search_type_template != '-1') $sql.=natural_search('type_template', $search_type_template); @@ -541,11 +479,14 @@ foreach ($fieldlist as $field => $value) if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } - if ($fieldlist[$field]=='content') { $valuetoshow=''; } - if ($fieldlist[$field]=='content_lines') { $valuetoshow=''; } if ($fieldlist[$field]=='private') { $align='center'; } if ($fieldlist[$field]=='position') { $align='center'; } + if ($fieldlist[$field]=='topic') { $valuetoshow=''; } + if ($fieldlist[$field]=='joinfiles') { $valuetoshow=''; } + if ($fieldlist[$field]=='content') { $valuetoshow=''; } + if ($fieldlist[$field]=='content_lines') { $valuetoshow=''; } + if ($valuetoshow != '') { print ''; @@ -560,14 +501,11 @@ foreach ($fieldlist as $field => $value) } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; } -print ''; +print ''; print ''; print ''; print ''; -// Line to enter new values (input fields) -print ""; - $obj = new stdClass(); // If data was already input, we define them in obj to populate input fields. if (GETPOST('actionadd')) @@ -587,6 +525,10 @@ $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $error = $hookmanager->error; $errors = $hookmanager->errors; + +// Line to enter new values (input fields) +print ""; + if (empty($reshook)) { if ($action == 'edit') { @@ -596,32 +538,51 @@ if (empty($reshook)) } } -print ''; +print ''; print ''; print ""; -$fieldsforcontent = array('content'); +$fieldsforcontent = array('topic', 'joinfiles', 'content'); if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $fieldsforcontent = array('content','content_lines'); } foreach ($fieldsforcontent as $tmpfieldlist) { - print ''; + print ''; + // Label + if ($tmpfieldlist == 'topic') + { + print '' . $form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + } + if ($tmpfieldlist == 'joinfiles') + { + print '' . $form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + } if ($tmpfieldlist == 'content') - print '' . $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '
      '; + print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist); if ($tmpfieldlist == 'content_lines') - print '' . $form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '
      '; - - if ($context != 'hide') { - // print ''; - $okforextended = true; - if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) - $okforextended = false; - $doleditor = new DolEditor($tmpfieldlist, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 120, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%'); - print $doleditor->Create(1); - } else - print ' '; + print $form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '
      '; + // Input field + if ($tmpfieldlist == 'topic') { + print ''; + } + else if ($tmpfieldlist == 'joinfiles') { + print ''; + } + else + { + if ($context != 'hide') { + // print ''; + $okforextended = true; + if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) + $okforextended = false; + $doleditor = new DolEditor($tmpfieldlist, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 120, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%'); + print $doleditor->Create(1); + } + else + print ' '; + } print ''; - if ($tmpfieldlist == 'content') { - print ''; + if ($tmpfieldlist == 'topic') { + print ''; if ($action != 'edit') { print ''; } @@ -704,7 +665,6 @@ if ($resql) elseif (! in_array($value, array('content', 'content_lines'))) print ''; } if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) print ''; - print ''; // Action column print ''; $searchpicto=$form->showFilterButtons(); @@ -736,11 +696,13 @@ if ($resql) if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } - if ($fieldlist[$field]=='content') { $valuetoshow=$langs->trans("Content"); $showfield=0;} - if ($fieldlist[$field]=='content_lines') { $valuetoshow=$langs->trans("ContentLines"); $showfield=0; } if ($fieldlist[$field]=='private') { $align='center'; } if ($fieldlist[$field]=='position') { $align='center'; } + if ($fieldlist[$field]=='joinfiles') { $valuetoshow=$langs->trans("FilesAttachedToEmail"); $align='center'; } + if ($fieldlist[$field]=='content') { $valuetoshow=$langs->trans("Content"); $showfield=0;} + if ($fieldlist[$field]=='content_lines') { $valuetoshow=$langs->trans("ContentLines"); $showfield=0; } + // Affiche nom du champ if ($showfield) { @@ -755,7 +717,6 @@ if ($resql) print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); print getTitleFieldOfList(''); - print getTitleFieldOfList(''); print ''; if ($num) @@ -777,7 +738,8 @@ if ($resql) // Show fields if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit'); - print ''; + print ''; + print ''; print ''; print ''; print ''; @@ -785,10 +747,10 @@ if ($resql) print ''; print ''; - $fieldsforcontent = array('content'); + $fieldsforcontent = array('topic', 'joinfiles', 'content'); if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { - $fieldsforcontent = array('content', 'content_lines'); + $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines'); } foreach ($fieldsforcontent as $tmpfieldlist) { @@ -799,17 +761,29 @@ if ($resql) $class = 'tddict'; // Show value for field if ($showfield) { - + // Show line for topic, joinfiles and content print ''; - print ''; // To create an artificial CR for the current tr we are on - $okforextended = true; - if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; - $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); - print $doleditor->Create(1); + print ''; + if ($tmpfieldlist == 'topic') + { + print '' . $form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + print ''; + } + if ($tmpfieldlist == 'joinfiles') + { + print '' . $form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . ' '; + print ''; + } + if ($tmpfieldlist == 'content') + { + $okforextended = true; + if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; + $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); + print $doleditor->Create(1); + } print ''; print ''; print ''; - print ''; } } } @@ -856,6 +830,12 @@ if ($resql) { $align="center"; } + if ($value == 'joinfiles') + { + $align="center"; + if ($valuetoshow) $valuetoshow=1; + else $valuetoshow=''; + } $class='tddict'; // Show value for field @@ -880,24 +860,21 @@ if ($resql) if ($param) $url .= '&'.$param; $url.='&'; - // Active + // Status / Active print ''; if ($canbedisabled) print ''.$actl[$obj->active].''; print ""; - // Modify link - if ($canbemodified) print ''.img_edit().''; - else print ''; - - // Delete link + // Modify link / Delete link + print ''; + if ($canbemodified) print ''.img_edit().''; if ($iserasable) { - print ''; - print ''.img_delete().''; + print '   '.img_delete().''; //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - print ''; } - else print ''; + print ''; + /* $fieldsforcontent = array('content'); @@ -1042,7 +1019,9 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') } print ''; } - elseif (in_array($fieldlist[$field], array('content','content_lines'))) continue; + elseif ($context == 'add' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue; + elseif ($context == 'edit' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue; + elseif ($context == 'hide' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue; else { $size=''; $class=''; $classtd=''; diff --git a/htdocs/admin/modulehelp.php b/htdocs/admin/modulehelp.php index e0caaba0a93..ff0f7a58099 100644 --- a/htdocs/admin/modulehelp.php +++ b/htdocs/admin/modulehelp.php @@ -366,7 +366,7 @@ if ($mode == 'desc') if ($mode == 'feature') { $text.='
      '.$langs->trans("DependsOn").': '; - if (count($objMod->requiredby)) $text.=join(',', $objMod->depends); + if (count($objMod->depends)) $text.=join(',', $objMod->depends); else $text.=$langs->trans("None"); $text.='
      '.$langs->trans("RequiredBy").': '; if (count($objMod->requiredby)) $text.=join(',', $objMod->requiredby); diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 06f7af5b8d6..ce5d4ec55eb 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -623,7 +623,7 @@ if ($mode == 'common') $imginfo="info_black"; } - print ''."\n"; + print ''."\n"; // Picto + Name of module print ' '; diff --git a/htdocs/admin/security_file.php b/htdocs/admin/security_file.php index 161ef427265..1053658b191 100644 --- a/htdocs/admin/security_file.php +++ b/htdocs/admin/security_file.php @@ -1,7 +1,7 @@ - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2013 Juanjo Menent +/* Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2017 Regis Houssin + * Copyright (C) 2013 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -54,7 +54,7 @@ if (GETPOST('sendit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) if (preg_match('/set_(.*)/',$action,$reg)) { $code=$reg[1]; - $value=(GETPOST($code) ? GETPOST($code) : 1); + $value=(GETPOST($code, 'alpha') ? GETPOST($code, 'alpha') : 1); if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); @@ -82,10 +82,10 @@ else if (preg_match('/del_(.*)/',$action,$reg)) else if ($action == 'updateform') { - $res3=dolibarr_set_const($db, 'MAIN_UPLOAD_DOC',$_POST["MAIN_UPLOAD_DOC"],'chaine',0,'',$conf->entity); - $res4=dolibarr_set_const($db, "MAIN_UMASK", $_POST["MAIN_UMASK"],'chaine',0,'',$conf->entity); - $res5=dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", $_POST["MAIN_ANTIVIRUS_COMMAND"],'chaine',0,'',$conf->entity); - $res6=dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", $_POST["MAIN_ANTIVIRUS_PARAM"],'chaine',0,'',$conf->entity); + $res3=dolibarr_set_const($db, 'MAIN_UPLOAD_DOC',GETPOST('MAIN_UPLOAD_DOC','alpha'),'chaine',0,'',$conf->entity); + $res4=dolibarr_set_const($db, "MAIN_UMASK", GETPOST('MAIN_UMASK','alpha'),'chaine',0,'',$conf->entity); + $res5=dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", trim(GETPOST('MAIN_ANTIVIRUS_COMMAND','none')),'chaine',0,'',$conf->entity); // Use GETPOST none because we must accept " + $res6=dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", trim(GETPOST('MAIN_ANTIVIRUS_PARAM','none')),'chaine',0,'',$conf->entity); // Use GETPOST none because we must accept " if ($res3 && $res4 && $res5 && $res6) setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } @@ -178,7 +178,7 @@ if (ini_get('safe_mode') && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) dol_syslog("safe_mode is on, basedir is ".$basedir.", safe_mode_exec_dir is ".ini_get('safe_mode_exec_dir'), LOG_WARNING); } } -print ''; +print ''; print ""; print ''; @@ -189,7 +189,7 @@ print ''.$langs->trans("AntiVirusParam").'
      '; print $langs->trans("AntiVirusParamExample"); print ''; print ''; -print ''; +print ''; print ""; print ''; diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index 36260c0a228..5daaca5e29e 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -54,7 +54,7 @@ if ($action == 'getlastversion') $sfurl = simplexml_load_string($result['content']); } - + /* * View */ @@ -107,19 +107,21 @@ if (function_exists('curl_init')) } // Show version - print $langs->trans("LastStableVersion").' : '. (($version != '0.0')?$version:$langs->trans("Unknown")) .'
      '; + print $langs->trans("LastStableVersion").' : '. (($version != '0.0')?$version:$langs->trans("Unknown")) .''; } else { - print $langs->trans("LastStableVersion").' : ' .$langs->trans("UpdateServerOffline").'
      '; + print $langs->trans("LastStableVersion").' : ' .$langs->trans("UpdateServerOffline").''; } } else { - print $langs->trans("LastStableVersion").' : ' .$langs->trans("Check").'
      '; + print $langs->trans("LastStableVersion").' : ' .$langs->trans("Check").''; } } +print '     -     '; +print ''.$langs->trans("SeeChangeLog").''; print ''."\n"; print ''.$langs->trans("VersionLastUpgrade").' ('.$langs->trans("Database").')'.$conf->global->MAIN_VERSION_LAST_UPGRADE.''."\n"; print ''.$langs->trans("VersionLastInstall").''.$conf->global->MAIN_VERSION_LAST_INSTALL.''."\n"; @@ -343,7 +345,7 @@ foreach($configfileparameters as $key => $value) { $newkey = preg_replace('/^\?/','',$key); - if (preg_match('/^\?/',$key) && empty(${$newkey})) + if (preg_match('/^\?/',$key) && empty(${$newkey})) { if ($newkey != 'multicompany_transverse_mode' || empty($conf->multicompany->enabled)) continue; // We discard parameters starting with ? diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index e2d2db9e659..f38406c3df5 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -1,6 +1,7 @@ * Copyright (C) 2009-2017 Regis Houssin + * Copyright (C) 2017 Frédéric France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -170,7 +171,7 @@ if ($action == 'add') else { setEventMessages($db->lasterror(), null, 'errors'); - } + } $action=''; } } @@ -208,25 +209,34 @@ llxHeader('',$langs->trans("Setup"),$wikihelp); $param='&mode='.$mode; -$enabledisablehtml = $langs->trans("EnableOverwriteTranslation").' '; +$enabledisablehtml=''; +if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $enabledisablehtml.= $langs->trans("EnableOverwriteTranslation").' '; if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { // Button off, click to enable $enabledisablehtml.=''; - $enabledisablehtml.=img_picto($langs->trans("Disabled"),'switch_off'); + //$enabledisablehtml.=img_picto($langs->trans("Disabled"),'switch_off'); + $enabledisablehtml.=''; + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $enabledisablehtml.=$langs->trans("EnableOverwriteTranslation"); + $enabledisablehtml.=''; $enabledisablehtml.=''; } else { // Button on, click to disable $enabledisablehtml.=''; - $enabledisablehtml.=img_picto($langs->trans("Activated"),'switch_on'); + //$enabledisablehtml.=img_picto($langs->trans("Activated"),'switch_on'); + $enabledisablehtml.=''; + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $enabledisablehtml.=$langs->trans("DisableOverwriteTranslation"); + $enabledisablehtml.=''; $enabledisablehtml.=''; } print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup'); +//print ''; print $langs->trans("TranslationDesc")."
      \n"; +//print '
      '; print "
      \n"; $current_language_code=$langs->defaultlang; @@ -259,11 +269,14 @@ if ($mode == 'overwrite') { //print load_fiche_titre($langs->trans("TranslationOverwriteKey"), '', '')."\n"; + print '
      '; print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); $urlwikitranslatordoc='https://wiki.dolibarr.org/index.php/Translator_documentation'; - print ' ('.$langs->trans("SeeAlso").': '.$urlwikitranslatordoc.')
      '; + print ' ('.$langs->trans("SeeAlso").': '.$langs->trans("Here").')
      '; print $langs->trans("TranslationOverwriteDesc",$langs->transnoentitiesnoconv("Language"),$langs->transnoentitiesnoconv("Key"),$langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
      \n"; + print '
      '; + print '
      '; @@ -291,9 +304,9 @@ if ($mode == 'overwrite') print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit?1:0, 'maxwidthonsmartphone', 1); print ''."\n"; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; // Limit to superadmin /*if (! empty($conf->multicompany->enabled) && !$user->entity) @@ -319,7 +332,7 @@ if ($mode == 'overwrite') $sql = "SELECT rowid, entity, lang, transkey, transvalue"; $sql.= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; $sql.= " WHERE 1 = 1"; - //$sql.= " AND entity IN (".$user->entity.",".$conf->entity.")"; + $sql.= " AND entity IN (".getEntity('overwrite_trans').")"; $sql.= $db->order($sortfield, $sortorder); dol_syslog("translation::select from table", LOG_DEBUG); @@ -483,7 +496,7 @@ if ($mode == 'searchkey') //} print ''; // Action column - print ''; + print ''; $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); print $searchpicto; print ''; @@ -508,9 +521,36 @@ if ($mode == 'searchkey') { if ($val != $newlangfileonly->tab_translate[$key]) { + // retrieve rowid + $sql = "SELECT rowid"; + $sql.= " FROM " . MAIN_DB_PREFIX . "overwrite_trans"; + $sql.= " WHERE transkey = '".$key."'"; + $sql.= " AND entity IN (" . getEntity('overwrite_trans') . ")"; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + } + print '' . img_edit() . ''; + print '  '; + print '' . img_delete() . ''; + print '  '; $htmltext = $langs->trans("OriginalValueWas", $newlangfileonly->tab_translate[$key]); print $form->textwithpicto('', $htmltext, 1, 'info'); } + else if (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) + { + //print $key.'-'.$val; + print '' . img_edit_add($langs->trans("Overwrite")) . ''; + } + + if (! empty($conf->global->MAIN_FEATURES_LEVEL)) + { + $transifexlangfile='$'; // $ means 'All' + $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; + print '   '.img_picto('FixOnTransifex', 'object_globe').''; + } } else { diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index dcda8255e7c..f8f8d37ce17 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -56,9 +56,14 @@ class DolibarrApi $this->db = $db; $production_mode = ( empty($conf->global->API_PRODUCTION_MODE) ? false : true ); $this->r = new Restler($production_mode, $refreshCache); + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - $this->r->setBaseUrls(DOL_MAIN_URL_ROOT, $urlwithroot); + + $urlwithouturlrootautodetect=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim(DOL_MAIN_URL_ROOT)); + $urlwithrootautodetect=$urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url + + $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect); $this->r->setAPIVersion(1); } @@ -131,6 +136,9 @@ class DolibarrApi unset($object->table_element_line); unset($object->picto); + unset($object->skip_update_total); + unset($object->context); + // Remove the $oldcopy property because it is not supported by the JSON // encoder. The following error is generated when trying to serialize // it: "Error encoding/decoding JSON: Type is not supported" diff --git a/htdocs/api/class/api_access.class.php b/htdocs/api/class/api_access.class.php index b2dcfefa49f..176c816d18c 100644 --- a/htdocs/api/class/api_access.class.php +++ b/htdocs/api/class/api_access.class.php @@ -69,7 +69,7 @@ class DolibarrApiAccess implements iAuthenticate */ public function __isAllowed() { - global $db; + global $conf, $db; $login = ''; $stored_key = ''; @@ -83,10 +83,10 @@ class DolibarrApiAccess implements iAuthenticate // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx $api_key = ''; - if (isset($_GET['api_key'])) + if (isset($_GET['api_key'])) // For backward compatibility { // TODO Add option to disable use of api key on url. Return errors if used. - $api_key = $_GET['api_key']; // For backward compatibility + $api_key = $_GET['api_key']; } if (isset($_GET['DOLAPIKEY'])) { @@ -100,11 +100,14 @@ class DolibarrApiAccess implements iAuthenticate if ($api_key) { + $userentity = 0; + $sql = "SELECT u.login, u.datec, u.api_key, "; $sql.= " u.tms as date_modification, u.entity"; $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE u.api_key = '".$db->escape($api_key)."'"; - + // TODO Check if 2 users has same API key. + $result = $db->query($sql); if ($result) { @@ -113,24 +116,31 @@ class DolibarrApiAccess implements iAuthenticate $obj = $db->fetch_object($result); $login = $obj->login; $stored_key = $obj->api_key; + $userentity = $obj->entity; + + if (! defined("DOLENTITY")) // If API was not forced with HTTP_DOLENTITY, we set entity to entity of user + { + $conf->entity = ($obj->entity?$obj->entity:1); + } } } else { throw new RestException(503, 'Error when fetching user api_key :'.$db->error_msg); } - if ($stored_key != $api_key) { + if ($stored_key != $api_key) { // This should not happen since we did a search on api_key $userClass::setCacheIdentifier($api_key); return false; } if (! $login) { - throw new RestException(503, 'Error when searching logn user fro mapi key'); + throw new RestException(503, 'Error when searching login user from api key'); } $fuser = new User($db); - if(! $fuser->fetch('',$login)) { - throw new RestException(503, 'Error when fetching user :'.$fuser->error); + $result = $fuser->fetch('', $login, '', 0, (empty($userentity) ? -1 : $conf->entity)); // If user is not entity 0, we search in working entity $conf->entity (that may have been forced to a different value than user entity) + if ($result <= 0) { + throw new RestException(503, 'Error when fetching user :'.$fuser->error.' (conf->entity='.$conf->entity.')'); } $fuser->getrights(); static::$user = $fuser; @@ -143,14 +153,14 @@ class DolibarrApiAccess implements iAuthenticate } else { - throw new RestException(401, "Failed to login to API. No parameter 'DOLAPIKEY' on HTTP header (neither in URL)."); + throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL)."); } - $userClass::setCacheIdentifier(static::$role); - Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; - $requirefortest = static::$requires; - if (! is_array($requirefortest)) $requirefortest=explode(',',$requirefortest); - return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; + $userClass::setCacheIdentifier(static::$role); + Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; + $requirefortest = static::$requires; + if (! is_array($requirefortest)) $requirefortest=explode(',',$requirefortest); + return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; } /** diff --git a/htdocs/api/class/api_dictionary.class.php b/htdocs/api/class/api_dictionary.class.php new file mode 100644 index 00000000000..b0d5bb00b0a --- /dev/null +++ b/htdocs/api/class/api_dictionary.class.php @@ -0,0 +1,519 @@ + + * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2017 Regis Houssin + * Copyright (C) 2017 Neil Orley + * + * + * 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.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; + +/** + * API class for dictionaries + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Dictionary extends DolibarrApi +{ + private $translations = null; + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of payments types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" + * + * @url GET payment/types + * + * @return array [List of payment types] + * + * @throws 400 RestException + * @throws 200 OK + */ + function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; + $sql.= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of countries. + * + * The names of the countries will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by country ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $lang Code of the language the label of the countries must be translated to + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of countries + * + * @url GET countries + * + * @throws RestException + */ + function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql.=" WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $country = new Ccountry($this->db); + if ($country->fetch($obj->rowid) > 0) { + // Translate the name of the country if needed + // and then apply the filter if there is one. + $this->translateLabel($country, $lang); + + if (empty($filter) || stripos($country->label, $filter) !== FALSE) { + $list[] = $this->_cleanObjectDatas($country); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of countries : '.$country->error); + } + + return $list; + } + + /** + * Get country by ID. + * + * @param int $id ID of country + * @param string $lang Code of the language the name of the + * country must be translated to + * + * @url GET countries/{id} + * + * @throws RestException + */ + function getCountryByID($id, $lang = '') + { + $country = new Ccountry($this->db); + + if ($country->fetch($id) < 0) { + throw new RestException(503, 'Error when retrieving country : '.$country->error); + } + else if ($country->fetch($id) == 0) { + throw new RestException(404, 'country not found'); + } + + $this->translateLabel($country, $lang); + + return $this->_cleanObjectDatas($country); + } + + /** + * 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->error); + unset($object->errors); + + return $object; + } + + /** + * Translate the name of the country to the given language. + * + * @param Ccountry $country Country + * @param string $lang Code of the language the name of the + * country must be translated to + */ + private function translateLabel($country, $lang) + { + if (!empty($lang)) { + // Load the translations if this is a new language. + if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { + global $conf; + $this->translations = new Translate('', $conf); + $this->translations->setDefaultLang($lang); + $this->translations->load('dict'); + } + if ($country->code) { + $key = 'Country'.$country->code; + $translation = $this->translations->trans($key); + if ($translation != $key) { + $country->label = html_entity_decode($translation); + } + } + } + } + + /** + * Get the list of events types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of event + * @param string $module To filter on module events + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of events types + * + * @url GET events + * + * @throws RestException + */ + function getListOfEvents($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; + $sql.= " WHERE t.active = 1"; + if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; + if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of extra fields. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" + * @return List of events types + * + * @url GET extrafields + * + * @throws RestException + */ + function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') + { + $list = array(); + + if ($type == 'thirdparty') $type='societe'; + if ($type == 'contact') $type='socpeople'; + + $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.ishidden, t.fielddefault, t.fieldcomputed"; + $sql.= " FROM ".MAIN_DB_PREFIX."extrafields as t"; + $sql.= " WHERE t.entity IN (".getEntity('extrafields').")"; + if (! empty($type)) $sql.= " AND t.elementtype = '".$this->db->escape($type)."'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $this->db->order($sortfield, $sortorder); + + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + while ($tab = $this->db->fetch_object($resql)) + { + // New usage + $list[$tab->elementtype][$tab->name]['type']=$tab->type; + $list[$tab->elementtype][$tab->name]['label']=$tab->label; + $list[$tab->elementtype][$tab->name]['size']=$tab->size; + $list[$tab->elementtype][$tab->name]['elementtype']=$tab->elementtype; + $list[$tab->elementtype][$tab->name]['default']=$tab->fielddefault; + $list[$tab->elementtype][$tab->name]['computed']=$tab->fieldcomputed; + $list[$tab->elementtype][$tab->name]['unique']=$tab->fieldunique; + $list[$tab->elementtype][$tab->name]['required']=$tab->fieldrequired; + $list[$tab->elementtype][$tab->name]['param']=($tab->param ? unserialize($tab->param) : ''); + $list[$tab->elementtype][$tab->name]['pos']=$tab->pos; + $list[$tab->elementtype][$tab->name]['alwayseditable']=$tab->alwayseditable; + $list[$tab->elementtype][$tab->name]['perms']=$tab->perms; + $list[$tab->elementtype][$tab->name]['list']=$tab->list; + $list[$tab->elementtype][$tab->name]['ishidden']=$tab->ishidden; + } + } + } + else + { + throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); + } + + if (! count($list)) + { + throw new RestException(404, 'No extrafield found'); + } + + return $list; + } + + + /** + * Get the list of towns. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $zipcode To filter on zipcode + * @param string $town To filter on city name + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return List of towns + * + * @url GET towns + * + * @throws RestException + */ + function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql.= " WHERE t.active = 1"; + if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'"; + if ($town) $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments terms. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET payment/terms + * + * @return array List of payment terms + * + * @throws 400 RestException + * @throws 200 OK + */ + function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql.= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + +} diff --git a/htdocs/api/class/api_dictionarycountries.class.php b/htdocs/api/class/api_dictionarycountries.class.php deleted file mode 100644 index 070be509a8a..00000000000 --- a/htdocs/api/class/api_dictionarycountries.class.php +++ /dev/null @@ -1,184 +0,0 @@ - - * 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.'/main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; - -/** - * API class for countries - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryCountries extends DolibarrApi -{ - private $translations = null; - - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of countries. - * - * The names of the countries will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by country ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $lang Code of the language the label of the countries must be translated to - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return List of countries - * - * @throws RestException - */ - function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; - $sql.=" WHERE 1 = 1"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $country = new Ccountry($this->db); - if ($country->fetch($obj->rowid) > 0) { - // Translate the name of the country if needed - // and then apply the filter if there is one. - $this->translateLabel($country, $lang); - - if (empty($filter) || stripos($country->label, $filter) !== FALSE) { - $list[] = $this->_cleanObjectDatas($country); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of countries : '.$country->error); - } - - return $list; - } - - /** - * Get country by ID. - * - * @param int $id ID of country - * @param string $lang Code of the language the name of the - * country must be translated to - * - * @throws RestException - */ - function get($id, $lang = '') - { - $country = new Ccountry($this->db); - - if ($country->fetch($id) < 0) { - throw new RestException(503, 'Error when retrieving country : '.$country->error); - } - else if ($country->fetch($id) == 0) { - throw new RestException(404, 'country not found'); - } - - $this->translateLabel($country, $lang); - - return $this->_cleanObjectDatas($country); - } - - /** - * 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->error); - unset($object->errors); - - return $object; - } - - /** - * Translate the name of the country to the given language. - * - * @param Ccountry $country Country - * @param string $lang Code of the language the name of the - * country must be translated to - */ - private function translateLabel($country, $lang) - { - if (!empty($lang)) { - // Load the translations if this is a new language. - if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { - global $conf; - $this->translations = new Translate('', $conf); - $this->translations->setDefaultLang($lang); - $this->translations->load('dict'); - } - if ($country->code) { - $key = 'Country'.$country->code; - $translation = $this->translations->trans($key); - if ($translation != $key) { - $country->label = html_entity_decode($translation); - } - } - } - } -} diff --git a/htdocs/api/class/api_dictionaryevents.class.php b/htdocs/api/class/api_dictionaryevents.class.php deleted file mode 100644 index 23d7e8e5dba..00000000000 --- a/htdocs/api/class/api_dictionaryevents.class.php +++ /dev/null @@ -1,100 +0,0 @@ - - * - * 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.'/main.inc.php'; - -/** - * API class for events type (content of the actioncomm dictionary) - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryEvents extends DolibarrApi -{ - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of events types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of event - * @param string $module To filter on module events - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return List of events types - * - * @throws RestException - */ - function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; - $sql.= " WHERE t.active = 1"; - if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'"; - if ($module) $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); - } - - return $list; - } - -} diff --git a/htdocs/api/class/api_dictionaryextrafields.class.php b/htdocs/api/class/api_dictionaryextrafields.class.php deleted file mode 100644 index 69f574797c7..00000000000 --- a/htdocs/api/class/api_dictionaryextrafields.class.php +++ /dev/null @@ -1,112 +0,0 @@ - - * - * 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 . '/core/class/extrafields.class.php'; - -/** - * API class for extra fields (content of the extrafields) - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryExtraFields extends DolibarrApi -{ - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of extra fields. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" - * @return List of events types - * - * @throws RestException - */ - function index($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') - { - $list = array(); - - if ($type == 'thirdparty') $type='societe'; - if ($type == 'contact') $type='socpeople'; - - $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.ishidden, t.fielddefault, t.fieldcomputed"; - $sql.= " FROM ".MAIN_DB_PREFIX."extrafields as t"; - $sql.= " WHERE t.entity IN (".getEntity('extrafields').")"; - if (! empty($type)) $sql.= " AND t.elementtype = '".$this->db->escape($type)."'"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql.= $this->db->order($sortfield, $sortorder); - - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - while ($tab = $this->db->fetch_object($resql)) - { - // New usage - $list[$tab->elementtype][$tab->name]['type']=$tab->type; - $list[$tab->elementtype][$tab->name]['label']=$tab->label; - $list[$tab->elementtype][$tab->name]['size']=$tab->size; - $list[$tab->elementtype][$tab->name]['elementtype']=$tab->elementtype; - $list[$tab->elementtype][$tab->name]['default']=$tab->fielddefault; - $list[$tab->elementtype][$tab->name]['computed']=$tab->fieldcomputed; - $list[$tab->elementtype][$tab->name]['unique']=$tab->fieldunique; - $list[$tab->elementtype][$tab->name]['required']=$tab->fieldrequired; - $list[$tab->elementtype][$tab->name]['param']=($tab->param ? unserialize($tab->param) : ''); - $list[$tab->elementtype][$tab->name]['pos']=$tab->pos; - $list[$tab->elementtype][$tab->name]['alwayseditable']=$tab->alwayseditable; - $list[$tab->elementtype][$tab->name]['perms']=$tab->perms; - $list[$tab->elementtype][$tab->name]['list']=$tab->list; - $list[$tab->elementtype][$tab->name]['ishidden']=$tab->ishidden; - } - } - } - else - { - throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); - } - - if (! count($list)) - { - throw new RestException(404, 'No extrafield found'); - } - - return $list; - } - -} diff --git a/htdocs/api/class/api_dictionarytowns.class.php b/htdocs/api/class/api_dictionarytowns.class.php deleted file mode 100644 index 0ebcfbe0b17..00000000000 --- a/htdocs/api/class/api_dictionarytowns.class.php +++ /dev/null @@ -1,102 +0,0 @@ - - * 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.'/main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; - -/** - * API class for towns (content of the ziptown dictionary) - * - * @access protected - * @class DolibarrApiAccess {@requires user,external} - */ -class DictionaryTowns extends DolibarrApi -{ - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of towns. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $zipcode To filter on zipcode - * @param string $town To filter on city name - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return List of towns - * - * @throws RestException - */ - function index($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; - $sql.= " WHERE t.active = 1"; - if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'"; - if ($town) $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'"; - // Add sql filters - if ($sqlfilters) - { - if (! DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - - $sql.= $this->db->order($sortfield, $sortorder); - - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); - } - - return $list; - } - -} diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index e26486981fa..92b48dfd0c6 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -22,6 +22,9 @@ use Luracast\Restler\Format\UploadFormat; require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; /** * API class for receive files @@ -32,173 +35,356 @@ require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; class Documents extends DolibarrApi { - /** - * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object - */ - static $DOCUMENT_FIELDS = array( - 'modulepart' - ); + /** + * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object + */ + static $DOCUMENT_FIELDS = array( + 'modulepart' + ); - /** - * Constructor - */ - function __construct() - { - global $db; - $this->db = $db; - } + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } - - /** - * Return list of documents. - * - * @param string $module_part Name of module or area concerned by file download ('facture', ...) - * @param string $ref Reference of object (This will define subdir automatically) - * @param string $subdir Subdirectory (Only if ref not provided) - * @return array List of documents - * - * @throws RestException - */ - public function index($module_part, $ref='', $subdir='') { - return array('note'=>'FeatureNotYetAvailable'); - } - - - /** - * Return a document. - * - * @param int $id ID of document - * @return array Array with data of file - * - * @throws RestException - */ - /* + + /** + * Returns a document. Note that, this API is similar to using the wrapper link "documents.php" to download + * a file (used for internal HTML links of documents into application), but with no need to be into a logged session (no need to post the session cookie). + * + * @param string $module_part Name of module or area concerned by file download ('facture', ...) + * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf) + * @param int $regeneratedoc If requested document is the main document of an object, setting this to 1 ask API to regenerate document before returning it (supported for some module_part only). It is no effect in other cases. + * Also, note that setting this to 1 nead write access on object. + * @return array List of documents + * + * @throws 500 + * @throws 501 + * @throws 400 + * @throws 401 + * @throws 200 + */ + public function index($module_part, $original_file='', $regeneratedoc=0) + { + global $conf, $langs; + + if (empty($module_part)) { + throw new RestException(400, 'bad value for parameter modulepart'); + } + if (empty($original_file)) { + throw new RestException(400, 'bad value for parameter ref or subdir'); + } + + //--- Finds and returns the document + $entity=$conf->entity; + + $check_access = dol_check_secure_access_document($module_part, $original_file, $entity, DolibarrApiAccess::$user, '', ($regeneratedoc ? 'write' : 'read')); + $accessallowed = $check_access['accessallowed']; + $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; + $original_file = $check_access['original_file']; + + if (preg_match('/\.\./',$original_file) || preg_match('/[<>|]/',$original_file)) + { + throw new RestException(401); + } + if (!$accessallowed) { + throw new RestException(401); + } + + // --- Generates the document + if ($regeneratedoc) + { + $hidedetails = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 0 : 1; + $hidedesc = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 0 : 1; + $hideref = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 0 : 1; + + if ($module_part == 'facture' || $module_part == 'invoice') + { + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $this->invoice = new Facture($this->db); + $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + $result = $this->invoice->generateDocument($this->invoice->modelpdf, $langs, $hidedetails, $hidedesc, $hideref); + if( $result <= 0 ) { + throw new RestException(500, 'Error generating document'); + } + } + } + + $filename = basename($original_file); + $original_file_osencoded=dol_osencode($original_file); // New file name encoded in OS encoding charset + + if (! file_exists($original_file_osencoded)) + { + throw new RestException(404, 'File not found'); + } + + $file_content=file_get_contents($original_file_osencoded); + return array('filename'=>$filename, 'content'=>base64_encode($file_content), 'encoding'=>'MIME base64 (base64_encode php function, http://php.net/manual/en/function.base64-encode.php)' ); + } + + /** + * Return the list of documents of a dedicated element (from its ID or Ref) + * + * @param string $modulepart Name of module or area concerned ('facture', 'project', 'member', ...) + * @param int $id ID of element + * @param string $ref Ref of element + * @param string $sortfield Sort criteria ('','fullname','relativename','name','date','size') + * @param string $sortorder Sort order ('asc' or 'desc') + * @return array Array of documents with path + * + * @throws RestException + * + * @url GET list + */ + function getDocumentsListByElement($modulepart, $id=0, $ref='', $sortfield='', $sortorder='') + { + global $conf; + + if (empty($modulepart)) { + throw new RestException(400, 'bad value for parameter modulepart'); + } + + if (empty($id) && empty($ref)) { + throw new RestException(400, 'bad value for parameter id or ref'); + } + + $id = (empty($id)?0:$id); + + if ($modulepart == 'societe' || $modulepart == 'thirdparty') + { + if (!DolibarrApiAccess::$user->rights->societe->lire) { + throw new RestException(401); + } + + $object = new Societe($this->db); + $result=$object->fetch($id, $ref); + if ( ! $result ) { + throw new RestException(404, 'Thirdparty not found'); + } + + $upload_dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id; + } + else if ($modulepart == 'adherent' || $modulepart == 'member') + { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } + + $object = new Adherent($this->db); + $result=$object->fetch($id, $ref); + if ( ! $result ) { + throw new RestException(404, 'Member not found'); + } + + $upload_dir = $conf->adherent->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'member'); + } + else + { + throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); + } + + $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + if (empty($filearray)) { + throw new RestException(404, 'Modulepart '.$modulepart.' with Id '.$object->id.(! empty($object->Ref)?' and Ref '.$object->ref:'').' does not have any documents.'); + } + + return $filearray; + } + + + /** + * Return a document. + * + * @param int $id ID of document + * @return array Array with data of file + * + * @throws RestException + */ + /* public function get($id) { return array('note'=>'xxx'); }*/ - - - /** - * Push a file. - * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. - * Test sample 2: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "mysubdir1/mysubdir2", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. - * - * @param string $filename Name of file to create ('FA1705-0123') - * @param string $modulepart Name of module or area concerned by file upload ('facture', ...) - * @param string $ref Reference of object (This will define subdir automatically and store submited file into it) - * @param string $subdir Subdirectory (Only if ref not provided) - * @param string $filecontent File content (string with file content. An empty file will be created if this parameter is not provided) - * @param string $fileencoding File encoding (''=no encoding, 'base64'=Base 64) - * @param int $overwriteifexists Overwrite file if exists (1 by default) - * @return bool State of copy - * @throws RestException - */ - public function post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0) - { - global $db, $conf; - - /*var_dump($modulepart); + + + /** + * Push a file. + * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. + * Test sample 2: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "mysubdir1/mysubdir2", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. + * + * @param string $filename Name of file to create ('FA1705-0123') + * @param string $modulepart Name of module or area concerned by file upload ('facture', 'project', 'project_task', ...) + * @param string $ref Reference of object (This will define subdir automatically and store submited file into it) + * @param string $subdir Subdirectory (Only if ref not provided) + * @param string $filecontent File content (string with file content. An empty file will be created if this parameter is not provided) + * @param string $fileencoding File encoding (''=no encoding, 'base64'=Base 64) + * @param int $overwriteifexists Overwrite file if exists (1 by default) + * @return bool State of copy + * @throws RestException + */ + public function post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0) + { + global $db, $conf; + + /*var_dump($modulepart); var_dump($filename); var_dump($filecontent); exit;*/ - - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - if (!DolibarrApiAccess::$user->rights->ecm->upload) { - throw new RestException(401); - } + if(empty($modulepart)) + { + throw new RestException(400, 'Modulepart not provided.'); + } - $newfilecontent = ''; - if (empty($fileencoding)) $newfilecontent = $filecontent; - if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); + if (!DolibarrApiAccess::$user->rights->ecm->upload) { + throw new RestException(401); + } + + $newfilecontent = ''; + if (empty($fileencoding)) $newfilecontent = $filecontent; + if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); $original_file = dol_sanitizeFileName($filename); // Define $uploadir $object = null; - $entity = $user->entity; + $entity = DolibarrApiAccess::$user->entity; if ($ref) { - if ($modulepart == 'facture' || $modulepart == 'invoice') - { - $modulepart='facture'; - $object=new Facture($db); - $result = $object->fetch('', $ref); - } - - if (! ($object->id > 0)) - { - throw new RestException(500, 'The object '.$modulepart." with ref '".$ref."' was not found."); - } + $tmpreldir=''; - $tmp = dol_check_secure_access_document($modulepart, $tmpreldir.$object->ref, $entity, DolibarrApiAccess::$user, $ref, 'write'); - $upload_dir = $tmp['original_file']; - - if (empty($upload_dir) || $upload_dir == '/') - { - throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); - } + if ($modulepart == 'facture' || $modulepart == 'invoice') + { + $modulepart='facture'; + $object = new Facture($this->db); + } + elseif ($modulepart == 'project') + { + $object = new Project($this->db); + } + elseif ($modulepart == 'task' || $modulepart == 'project_task') + { + $modulepart = 'project_task'; + $object = new Task($this->db); + + $task_result = $object->fetch('', $ref); + + // Fetching the tasks project is required because its out_dir might be a subdirectory of the project + if($task_result > 0) + { + $project_result = $object->fetch_projet(); + + if($project_result >= 0) + { + $tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; + } + } + else + { + throw new RestException(500, 'Error while fetching Task '.$ref); + } + } + // TODO Implement additional moduleparts + else + { + throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); + } + + if(is_object($object)) + { + $result = $object->fetch('', $ref); + + if($result == 0) + { + throw new RestException(500, "Object with ref '".$ref.'" was not found.'); + } + elseif ($result < 0) + { + throw new RestException(500, 'Error while fetching object.'); + } + } + + if (! ($object->id > 0)) + { + throw new RestException(500, 'The object '.$modulepart." with ref '".$ref."' was not found."); + } + + $tmp = dol_check_secure_access_document($modulepart, $tmpreldir.dol_sanitizeFileName($object->ref), $entity, DolibarrApiAccess::$user, $ref, 'write'); + $upload_dir = $tmp['original_file']; + + if (empty($upload_dir) || $upload_dir == '/') + { + throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); + } } else { - if ($modulepart == 'invoice') $modulepart ='facture'; - - $tmp = dol_check_secure_access_document($modulepart, $subdir, $entity, DolibarrApiAccess::$user, '', 'write'); - $upload_dir = $tmp['original_file']; + if ($modulepart == 'invoice') $modulepart ='facture'; - if (empty($upload_dir) || $upload_dir == '/') - { - throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); - } + $tmp = dol_check_secure_access_document($modulepart, $subdir, $entity, DolibarrApiAccess::$user, '', 'write'); + $upload_dir = $tmp['original_file']; + + if (empty($upload_dir) || $upload_dir == '/') + { + throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); + } } - - + + $upload_dir = dol_sanitizePathName($upload_dir); - + $destfile = $upload_dir . '/' . $original_file; $destfiletmp = DOL_DATA_ROOT.'/admin/temp/' . $original_file; dol_delete_file($destfiletmp); - - if (!dol_is_dir($upload_dir)) { - throw new RestException(401,'Directory not exists : '.$upload_dir); - } - if (! $overwriteifexists && dol_is_file($destfile)) - { - throw new RestException(500, "File with name '".$original_file."' already exists."); - } - - $fhandle = @fopen($destfiletmp, 'w'); - if ($fhandle) - { - $nbofbyteswrote = fwrite($fhandle, $newfilecontent); - fclose($fhandle); - @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK)); - } - else - { - throw new RestException(500, "Failed to open file '".$destfiletmp."' for write"); - } - - $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1); - - return $result; - } + if (!dol_is_dir($upload_dir)) { + throw new RestException(401,'Directory not exists : '.$upload_dir); + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - function _validate_file($data) { - $result = array(); - foreach (Documents::$DOCUMENT_FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $result[$field] = $data[$field]; - } - return $result; - } + if (! $overwriteifexists && dol_is_file($destfile)) + { + throw new RestException(500, "File with name '".$original_file."' already exists."); + } + + $fhandle = @fopen($destfiletmp, 'w'); + if ($fhandle) + { + $nbofbyteswrote = fwrite($fhandle, $newfilecontent); + fclose($fhandle); + @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK)); + } + else + { + throw new RestException(500, "Failed to open file '".$destfiletmp."' for write"); + } + + $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1); + + return $result; + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate_file($data) { + $result = array(); + foreach (Documents::$DOCUMENT_FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $result[$field] = $data[$field]; + } + return $result; + } } diff --git a/htdocs/api/index.php b/htdocs/api/index.php index 2730c6c0242..248b1541f6c 100644 --- a/htdocs/api/index.php +++ b/htdocs/api/index.php @@ -241,6 +241,7 @@ if (! empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/resources.json' else { $classfile = str_replace('_', '', $module); + if ($module == 'contracts') $moduledirforclass = 'contrat'; if ($module == 'supplierinvoices') $classfile = 'supplier_invoices'; if ($module == 'supplierorders') $classfile = 'supplier_orders'; $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php'); diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 8a1508b7a04..4bce16fb796 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -21,13 +21,15 @@ class BlockedLog { - /** * Id of the log * @var int */ public $id; + public $error = ''; + public $errors = array(); + /** * Unique fingerprint of the log * @var string @@ -78,7 +80,7 @@ class BlockedLog public $object_data = null; - public $error = 0; + /** * Constructor @@ -126,7 +128,7 @@ class BlockedLog /** * try to retrieve user author - */ + */ public function getUser() { global $langs, $cachedUser; @@ -188,8 +190,6 @@ class BlockedLog $this->object_data->amounts = $object->amounts; } - - } /** @@ -231,7 +231,7 @@ class BlockedLog $this->action = $obj->action; $this->element = $obj->element; - $this->fk_object = trim($obj->fk_object); + $this->fk_object = $obj->fk_object; $this->date_object = $this->db->jdate($obj->date_object); $this->ref_object = $obj->ref_object; @@ -432,10 +432,10 @@ class BlockedLog /** * return log object for a element. * - * @param string $element element to search - * @param int $fk_object id of object to search - * @param int $limit max number of element, 0 for all - * @param string $order sort of query + * @param string $element element to search + * @param int $fk_object id of object to search + * @param int $limit max number of element, 0 for all + * @param string $order sort of query * @return array array of object log */ public function getLog($element, $fk_object, $limit = 0, $order = -1) { diff --git a/htdocs/bookmarks/card.php b/htdocs/bookmarks/card.php index 2c3b200b4e4..dcc6d8cdeab 100644 --- a/htdocs/bookmarks/card.php +++ b/htdocs/bookmarks/card.php @@ -65,7 +65,7 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') if (GETPOST('cancel','alpha')) { - if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); + if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url) && ! preg_match('/^http/i', $url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); header("Location: ".$backtopage); exit; } @@ -98,7 +98,7 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') if ($res > 0) { - if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); + if (empty($backtopage)) $backtopage=($urlsource?$urlsource:((! empty($url) && ! preg_match('/^http/i', $url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); header("Location: ".$backtopage); exit; } diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index c9387561837..0e642bdcc14 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -35,7 +35,7 @@ $toselect = GETPOST('toselect', 'array'); // Security check if (! $user->rights->bookmark->lire) { - restrictedArea($user, 'bookmarks'); + restrictedArea($user, 'bookmarks'); } $optioncss = GETPOST('optioncss','alpha'); @@ -50,7 +50,7 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='position'; if (! $sortorder) $sortorder='ASC'; -$id = GETPOST("bid",'int'); +$id = GETPOST("id",'int'); /* @@ -59,17 +59,17 @@ $id = GETPOST("bid",'int'); if ($action == 'delete') { - $bookmark=new Bookmark($db); - $res=$bookmark->remove($id); - if ($res > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } - else - { - setEventMessages($bookmark->error, $bookmark->errors, 'errors'); - } + $bookmark=new Bookmark($db); + $res=$bookmark->remove($id); + if ($res > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + setEventMessages($bookmark->error, $bookmark->errors, 'errors'); + } } @@ -83,7 +83,7 @@ llxHeader('', $langs->trans("ListOfBookmarks")); print load_fiche_titre($langs->trans("ListOfBookmarks")); -$sql = "SELECT b.fk_soc as rowid, b.dateb, b.rowid as bid, b.fk_user, b.url, b.target, b.title, b.favicon, b.position,"; +$sql = "SELECT b.rowid, b.dateb, b.fk_user, b.url, b.target, b.title, b.favicon, b.position,"; $sql.= " u.login, u.lastname, u.firstname"; $sql.= " FROM ".MAIN_DB_PREFIX."bookmark as b LEFT JOIN ".MAIN_DB_PREFIX."user as u ON b.fk_user=u.rowid"; $sql.= " WHERE 1=1"; @@ -95,126 +95,112 @@ $sql.= $db->plimit($limit, $offset); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $param = ""; - if ($optioncss != '') $param ='&optioncss='.$optioncss; + $num = $db->num_rows($resql); + $i = 0; + $param = ""; + if ($optioncss != '') $param ='&optioncss='.$optioncss; - $moreforfilter=''; + $moreforfilter=''; - print '
      '; - print ''."\n"; + print '
      '; + print '
      '."\n"; - print ""; - //print ""; - print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"bid","", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"title","", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Link",'',''); - print_liste_field_titre("Target",'','','','','align="center"'); - print_liste_field_titre("Owner",$_SERVER["PHP_SELF"],"u.lastname","", $param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"b.dateb","", $param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre("Position",$_SERVER["PHP_SELF"],"b.position","", $param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre(''); - print "\n"; + print ""; + //print ""; + print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"rowid","", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Title",$_SERVER["PHP_SELF"],"title","", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Link",'',''); + print_liste_field_titre("Target",'','','','','align="center"'); + print_liste_field_titre("Owner",$_SERVER["PHP_SELF"],"u.lastname","", $param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"b.dateb","", $param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Position",$_SERVER["PHP_SELF"],"b.position","", $param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre(''); + print "\n"; - $var=True; - while ($i < $num) - { - $obj = $db->fetch_object($resql); + $var=True; + while ($i < $num) + { + $obj = $db->fetch_object($resql); - print ''; + print ''; - // Id - print ''; + // Id + print ''; - $linkintern=0; - $title=$obj->title; - $link=$obj->url; + $linkintern=0; + $title=$obj->title; + $link=$obj->url; - // Title - print "\n"; + // Title + print "\n"; - // Url - print '\n"; + // Url + print '\n"; - // Target - print '\n"; + // Target + print '\n"; - // Author - print '\n"; + print "\n"; - // Date creation - print '"; + // Date creation + print '"; - // Position - print '"; + // Position + print '"; - // Actions - print '"; - print "\n"; - $i++; - } - print "
       
       
      '; - print "bid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->bid.""; - print ''; + print "rowid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->rowid.""; + print '"; - if ($obj->rowid) - { - // Lien interne societe - $linkintern=1; - $link="Dolibarr"; - if (! $obj->title) - { - // For compatibility with old Dolibarr bookmarks - require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $societe=new Societe($db); - $societe->fetch($obj->rowid); - $obj->title=$societe->name; - } - $title=img_object($langs->trans("ShowCompany"),"company").' '.$obj->title; - } - if ($linkintern) print "url."\">"; - print $title; - if ($linkintern) print ""; - print ""; + $linkintern=1; + if ($linkintern) print "url."\">"; + print $title; + if ($linkintern) print ""; + print "'; - if (! $linkintern) print 'target?' target="newlink"':'').'>'; - print $link; - if (! $linkintern) print ''; - print "'; + if (! $linkintern) print 'target?' target="newlink"':'').'>'; + print $link; + if (! $linkintern) print ''; + print "'; - if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); - if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); - print "'; + if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); + if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); + print "'; + // Author + print ''; if ($obj->fk_user) { - $userstatic->id=$obj->fk_user; - $userstatic->lastname=$obj->login; + $userstatic->id=$obj->fk_user; + $userstatic->lastname=$obj->login; print $userstatic->getNomUrl(1); } else { print $langs->trans("Public"); } - print "'.dol_print_date($db->jdate($obj->dateb),'day')."'.dol_print_date($db->jdate($obj->dateb),'day')."'.$obj->position."'.$obj->position."'; - if ($user->rights->bookmark->creer) - { - print "bid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()." "; - } - if ($user->rights->bookmark->supprimer) - { - print "bid\">".img_delete().""; - } - else - { - print " "; - } - print "
      "; - print '
      '; + // Actions + print ''; + if ($user->rights->bookmark->creer) + { + print "rowid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()." "; + } + if ($user->rights->bookmark->supprimer) + { + print "rowid\">".img_delete().""; + } + else + { + print " "; + } + print ""; + print "\n"; + $i++; + } + print ""; + print ''; - $db->free($resql); + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } @@ -223,7 +209,7 @@ print "
      \n"; if ($user->rights->bookmark->creer) { - print ''.$langs->trans("NewBookmark").''; + print ''.$langs->trans("NewBookmark").''; } print '
      '; 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/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index 1b870d30f73..399e2984ea8 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -136,7 +136,7 @@ switch ($action) $cond_reglement_id = 0; break; case 'ESP': - $mode_reglement_id = dol_getIdFromCode($db,'LIQ','c_paiement'); + $mode_reglement_id = dol_getIdFromCode($db,'LIQ','c_paiement','code','id',1); $cond_reglement_id = 0; $note .= $langs->trans("Cash")."\n"; $note .= $langs->trans("Received").' : '.$obj_facturation->montantEncaisse()." ".$conf->currency."\n"; @@ -145,11 +145,11 @@ switch ($action) $note .= '--------------------------------------'."\n\n"; break; case 'CB': - $mode_reglement_id = dol_getIdFromCode($db,'CB','c_paiement'); + $mode_reglement_id = dol_getIdFromCode($db,'CB','c_paiement','code','id',1); $cond_reglement_id = 0; break; case 'CHQ': - $mode_reglement_id = dol_getIdFromCode($db,'CHQ','c_paiement'); + $mode_reglement_id = dol_getIdFromCode($db,'CHQ','c_paiement','code','id',1); $cond_reglement_id = 0; break; } diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index ed10e337f7b..1c8d9fcfe50 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -23,13 +23,13 @@ /** * API class for categories * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class Categories 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( 'label', @@ -44,7 +44,7 @@ class Categories extends DolibarrApi 4 => 'contact', 5 => 'account', ); - + /** * @var Categorie $category {@type Categorie} */ @@ -67,20 +67,20 @@ class Categories extends DolibarrApi * * @param int $id ID of category * @return array|mixed data without useless information - * + * * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } - + $result = $this->category->fetch($id); if( ! $result ) { throw new RestException(404, 'category not found'); } - + if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -90,7 +90,7 @@ class Categories extends DolibarrApi /** * List categories - * + * * Get a list of categories * * @param string $sortfield Sort field @@ -105,13 +105,13 @@ class Categories extends DolibarrApi */ function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type = '', $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - + if(! DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } - + $sql = "SELECT t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."categorie as t"; $sql.= ' WHERE t.entity IN ('.getEntity('category').')'; @@ -120,7 +120,7 @@ class Categories extends DolibarrApi $sql.= ' AND t.type='.array_search($type,Categories::$TYPES); } // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -129,93 +129,6 @@ class Categories extends DolibarrApi $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); - } - - $result = $db->query($sql); - if ($result) - { - $i=0; - $num = $db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $db->fetch_object($result); - $category_static = new Categorie($db); - if($category_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($category_static); - } - $i++; - } - } - else { - throw new RestException(503, 'Error when retrieve category list : '.$db->lasterror()); - } - if( ! count($obj_ret)) { - throw new RestException(404, 'No category found'); - } - return $obj_ret; - } - - /** - * List categories of an entity - * - * Note: This method is not directly exposed in the API, it is used - * in the GET /xxx/{id}/categories requests. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @param int $item Id of the item to get categories for - * @return array Array of category objects - * - * @access private - */ - function getListForItem($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type='customer', $item = 0) { - global $db, $conf; - - $obj_ret = array(); - - if(! DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - //if ($type == "") { - //$type="product"; - //} - $sub_type = $type; - $subcol_name = "fk_".$type; - if ($type=="customer" || $type=="supplier") { - $sub_type="societe"; - $subcol_name="fk_soc"; - } - if ($type=="contact") { - $subcol_name="fk_socpeople"; - } - $sql = "SELECT s.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as s"; - $sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub "; - $sql.= ' WHERE s.entity IN ('.getEntity('category').')'; - $sql.= ' AND s.type='.array_search($type,Categories::$TYPES); - $sql.= ' AND s.rowid = sub.fk_categorie'; - $sql.= ' AND sub.'.$subcol_name.' = '.$item; - - $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - } $sql.= $db->order($sortfield, $sortorder); if ($limit) { @@ -250,13 +163,12 @@ class Categories extends DolibarrApi if( ! count($obj_ret)) { throw new RestException(404, 'No category found'); } - return $obj_ret; } /** * Create category object - * + * * @param array $request_data Request data * @return int ID of category */ @@ -268,7 +180,7 @@ class Categories extends DolibarrApi // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->category->$field = $value; } @@ -280,22 +192,22 @@ class Categories extends DolibarrApi /** * Update category - * + * * @param int $id Id of category to update - * @param array $request_data Datas - * @return int + * @param array $request_data Datas + * @return int */ function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); } - + $result = $this->category->fetch($id); if( ! $result ) { throw new RestException(404, 'category not found'); } - + if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -304,13 +216,13 @@ class Categories extends DolibarrApi if ($field == 'id') continue; $this->category->$field = $value; } - + if($this->category->update(DolibarrApiAccess::$user)) return $this->get ($id); - + return false; } - + /** * Delete category * @@ -326,15 +238,15 @@ class Categories extends DolibarrApi if( ! $result ) { throw new RestException(404, 'category not found'); } - + if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if (! $this->category->delete(DolibarrApiAccess::$user)) { throw new RestException(401,'error when delete category'); } - + return array( 'success' => array( 'code' => 200, @@ -342,8 +254,8 @@ class Categories extends DolibarrApi ) ); } - - + + /** * Clean sensible object datas * @@ -351,9 +263,9 @@ class Categories extends DolibarrApi * @return array Array of cleaned object properties */ function _cleanObjectDatas($object) { - + $object = parent::_cleanObjectDatas($object); - + // Remove fields not relevent to categories unset($object->country); unset($object->country_id); @@ -394,16 +306,16 @@ class Categories extends DolibarrApi unset($object->fk_project); unset($object->note); unset($object->statut); - + return $object; } - + /** * Validate fields before create or update object - * + * * @param array|null $data Data to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 5cbe56554dd..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 @@ -879,6 +879,100 @@ class Categorie extends CommonObject } } + /** + * List categories of an element id + * + * @param int $id Id of element + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @return array Array of categories + */ + function getListForItem($id, $type='customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + global $conf; + + $categories = array(); + + $sub_type = $type; + $subcol_name = "fk_".$type; + if ($type=="customer" || $type=="supplier") { + $sub_type="societe"; + $subcol_name="fk_soc"; + } + if ($type=="contact") { + $subcol_name="fk_socpeople"; + } + $sql = "SELECT s.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."categorie as s"; + $sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub "; + $sql.= ' WHERE s.entity IN ('.getEntity('category').')'; + $sql.= ' AND s.type='.array_search($type, self::$MAP_ID_TO_CODE); + $sql.= ' AND s.rowid = sub.fk_categorie'; + $sql.= ' AND sub.'.$subcol_name.' = '.$id; + + $nbtotalofrecords = ''; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + { + $result = $this->db->query($sql); + $nbtotalofrecords = $this->db->num_rows($result); + } + + $sql.= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $this->db->plimit($limit + 1, $offset); + } + + $result = $this->db->query($sql); + if ($result) + { + $i=0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $category_static = new Categorie($this->db); + if ($category_static->fetch($obj->rowid)) + { + $categories[$i]['id'] = $category_static->id; + $categories[$i]['fk_parent'] = $category_static->fk_parent; + $categories[$i]['label'] = $category_static->label; + $categories[$i]['description'] = $category_static->description; + $categories[$i]['color'] = $category_static->color; + $categories[$i]['socid'] = $category_static->socid; + $categories[$i]['visible'] = $category_static->visible; + $categories[$i]['type'] = $category_static->type; + $categories[$i]['entity'] = $category_static->entity; + $categories[$i]['array_options'] = $category_static->array_options; + + // multilangs + if (! empty($conf->global->MAIN_MULTILANGS)) { + $categories[$i]['multilangs'] = $category_static->multilangs; + } + } + $i++; + } + } + else { + $this->error = $this->db->lasterror(); + return -1; + } + if ( ! count($categories)) { + return 0; + } + + return $categories; + } + /** * Return childs of a category * @@ -1233,6 +1327,7 @@ class Categorie extends CommonObject { $w = array(); $i = 0; + $forced_color=''; foreach ($way as $cat) { $i++; @@ -1246,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'; } } } @@ -1508,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/categories/viewcat.php b/htdocs/categories/viewcat.php index 75a9215e18d..a3ca8053281 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -319,7 +319,7 @@ else // List of products or services (type is type of category) -if ($object->type == Categorie::TYPE_PRODUCT) +if ($type == Categorie::TYPE_PRODUCT) { $prods = $object->getObjectsInCateg("product"); if ($prods < 0) @@ -391,7 +391,7 @@ if ($object->type == Categorie::TYPE_PRODUCT) } } -if ($object->type == Categorie::TYPE_SUPPLIER) +if ($type == Categorie::TYPE_SUPPLIER) { $socs = $object->getObjectsInCateg("supplier"); if ($socs < 0) @@ -440,7 +440,7 @@ if ($object->type == Categorie::TYPE_SUPPLIER) } } -if($object->type == Categorie::TYPE_CUSTOMER) +if($type == Categorie::TYPE_CUSTOMER) { $socs = $object->getObjectsInCateg("customer"); if ($socs < 0) @@ -494,7 +494,7 @@ if($object->type == Categorie::TYPE_CUSTOMER) } // List of members -if ($object->type == Categorie::TYPE_MEMBER) +if ($type == Categorie::TYPE_MEMBER) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; @@ -547,7 +547,7 @@ if ($object->type == Categorie::TYPE_MEMBER) } // Categorie contact -if($object->type == Categorie::TYPE_CONTACT) +if ($type == Categorie::TYPE_CONTACT) { $contacts = $object->getObjectsInCateg("contact"); if ($contacts < 0) @@ -600,7 +600,7 @@ if($object->type == Categorie::TYPE_CONTACT) } // List of accounts -if ($object->type == Categorie::TYPE_ACCOUNT) +if ($type == Categorie::TYPE_ACCOUNT) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -653,7 +653,7 @@ if ($object->type == Categorie::TYPE_ACCOUNT) } // List of Project -if ($object->type == Categorie::TYPE_PROJECT) +if ($type == Categorie::TYPE_PROJECT) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index 7f08beff955..bcc12c0a341 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -24,49 +24,6 @@ define('NOSCANPOSTFORINJECTION',1); define('NOSTYLECHECK',1); - -/** - * Show HTML header HTML + BODY + Top menu + left menu + DIV - * - * @param string $head Optionnal head lines - * @param string $title HTML title - * @param string $help_url Url links to help page - * Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage - * For other external page: http://server/url - * @param string $target Target to use on links - * @param int $disablejs More content into html header - * @param int $disablehead More content into html header - * @param array $arrayofjs Array of complementary js files - * @param array $arrayofcss Array of complementary css files - * @param string $morequerystring Query string to add to the link "print" to get same parameters (set this only if autodetect fails) - * @return void - */ -function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='') -{ - global $conf; - - // html header - top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); - - print ''; - - // top menu and left menu area - if (empty($conf->dol_hide_topmenu)) - { - top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url); - } - if (empty($conf->dol_hide_leftmenu)) - { - left_menu('', $help_url, '', '', 1, $title, 1); - } - - // main area - //main_area($title); - print ''."\n".'
      '."\n"; -} - - - require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -79,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; @@ -114,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 { @@ -154,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); + } } @@ -198,13 +155,13 @@ $form = new Form($db); $help_url=''; -llxHeader('', $langs->trans("WebsiteSetup"), $help_url); +llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', ''."\n".'
      '); print "\n".'
      '; print ''; if ($action == 'create') { - print ''; + print ''; } @@ -217,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.'/websites/'.$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/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 ''; + //} - 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/websites/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=''; } @@ -480,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 02a16af3c17..0cfa31e12c8 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) @@ -771,9 +771,9 @@ if ($action == 'create') $events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); //For external user force the company to user company if (!empty($user->societe_id)) { - print $form->select_thirdparty_list($user->societe_id, 'socid', '', 1, 1, 0, $events); + print $form->select_company($user->societe_id, 'socid', '', 1, 1, 0, $events); } else { - print $form->select_thirdparty_list('', 'socid', '', 'SelectThirdParty', 1, 0, $events); + print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, $events); } } @@ -781,7 +781,7 @@ if ($action == 'create') // Related contact print ''.$langs->trans("ActionOnContact").''; - $form->select_contacts(GETPOST('socid','int'), GETPOST('contactid'), 'contactid', 1, '', '', 0, 'minwidth200'); + $form->selectcontacts(GETPOST('socid','int'), GETPOST('contactid'), 'contactid', 1, '', '', 0, 'minwidth200'); print ''; @@ -1202,14 +1202,13 @@ if ($id > 0) // Link to other agenda views $out=''; - $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; - $out.='
      '; - $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; - $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; - $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index ec1c84dd652..cf380871926 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -911,55 +911,62 @@ class ActionComm extends CommonObject /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * - * @param User $user Objet user + * @param User $user Objet user + * @param int $load_state_board Charge indicateurs this->nb de tableau de bord * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ - function load_board($user) + function load_board($user, $load_state_board=0) { - global $conf, $langs; + global $conf, $langs; - $sql = "SELECT a.id, a.datep as dp"; - $sql.= " FROM (".MAIN_DB_PREFIX."actioncomm as a"; - $sql.= ")"; - if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - $sql.= " WHERE a.percent >= 0 AND a.percent < 100"; - $sql.= " AND a.entity IN (".getEntity('agenda').")"; - 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 . ")"; + if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp"; + else { + $this->nb=array(); + $sql = "SELECT count(a.id) as nb"; + } + $sql.= " FROM (".MAIN_DB_PREFIX."actioncomm as a"; + $sql.= ")"; + if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; + $sql.= " WHERE 1"; + if(empty($load_state_board)) $sql.= " AND a.percent >= 0 AND a.percent < 100"; + $sql.= " AND a.entity IN (".getEntity('agenda').")"; + 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) - { - $agenda_static = new ActionComm($this->db); + $resql=$this->db->query($sql); + if ($resql) + { + if(empty($load_state_board)) { + $agenda_static = new ActionComm($this->db); + $response = new WorkboardResponse(); + $response->warning_delay = $conf->agenda->warning_delay/60/60/24; + $response->label = $langs->trans("ActionsToDo"); + $response->url = DOL_URL_ROOT.'/comm/action/listactions.php?status=todo&mainmenu=agenda'; + if ($user->rights->agenda->allactions->read) $response->url.='&filtert=-1'; + $response->img = img_object('',"action",'class="inline-block valigntextmiddle"'); + } + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + if(empty($load_state_board)) { + $response->nbtodo++; + $agenda_static->datep = $this->db->jdate($obj->dp); + if ($agenda_static->hasDelay()) $response->nbtodolate++; + } else $this->nb["actionscomm"]=$obj->nb; + } - $response = new WorkboardResponse(); - $response->warning_delay = $conf->agenda->warning_delay/60/60/24; - $response->label = $langs->trans("ActionsToDo"); - $response->url = DOL_URL_ROOT.'/comm/action/listactions.php?status=todo&mainmenu=agenda'; - if ($user->rights->agenda->allactions->read) $response->url.='&filtert=-1'; - $response->img = img_object('',"action",'class="inline-block valigntextmiddle"'); - - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - - $agenda_static->datep = $this->db->jdate($obj->dp); - - if ($agenda_static->hasDelay()) { - $response->nbtodolate++; - } - } - - return $response; - } - else - { - $this->error=$this->db->error(); - return -1; - } + $this->db->free($resql); + if(empty($load_state_board)) return $response; + else return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } } diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 1e54db9d449..68a36844e39 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -128,14 +128,13 @@ if ($object->id > 0) // Link to other agenda views $out=''; - $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; - $out.='
      '; - $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; - $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; - $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.='
    • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; diff --git a/htdocs/comm/action/info.php b/htdocs/comm/action/info.php index 7bee5550453..9bcf1d2b9cd 100644 --- a/htdocs/comm/action/info.php +++ b/htdocs/comm/action/info.php @@ -51,6 +51,8 @@ $result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions| * View */ +$form=new Form($db); + $help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('',$langs->trans("Agenda"),$help_url); @@ -66,14 +68,13 @@ $linkback.= ''.$langs->trans("B // Link to other agenda views $out=''; -$out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); +$out.='
    • '.img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewPerUser").''; -$out.='
      '; -$out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); +$out.='
    • '.img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewCal").''; -$out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); +$out.='
    • '.img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewWeek").''; -$out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); +$out.='
    • '.img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); $out.=''.$langs->trans("ViewDay").''; $linkback.=$out; diff --git a/htdocs/comm/action/listactions.php b/htdocs/comm/action/listactions.php index 78e73fe0717..982974b3d7a 100644 --- a/htdocs/comm/action/listactions.php +++ b/htdocs/comm/action/listactions.php @@ -357,7 +357,7 @@ if ($resql) //$param='month='.$monthshown.'&year='.$year; $hourminsec='100000'; $link = ''; - $link.= $langs->trans("NewAction"); + $link.= $langs->trans("AddAction"); $link.= ''; } @@ -372,9 +372,9 @@ if ($resql) print ''; print ''; print ''; + print ''; print ''; - print ''; - print ''; + print ''; print $form->select_date($datestart, 'datestart', 0, 0, 1, '', 1, 0, 1); print ''; print ''; @@ -396,9 +396,9 @@ if ($resql) print ''; print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"a.id",$param,"","",$sortfield,$sortorder); print_liste_field_titre("ActionsOwnedByShort",$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder); - print_liste_field_titre("Label",$_SERVER["PHP_SELF"],"a.label",$param,"","",$sortfield,$sortorder); //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"c.libelle",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"c.libelle",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Label",$_SERVER["PHP_SELF"],"a.label",$param,"","",$sortfield,$sortorder); print_liste_field_titre("DateStart",$_SERVER["PHP_SELF"],"a.datep",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre("DateEnd",$_SERVER["PHP_SELF"],"a.datep2",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom",$param,"","",$sortfield,$sortorder); @@ -452,11 +452,6 @@ if ($resql) else print ' '; print ''; - // Label - print ''; - print $actionstatic->label; - print ''; - // Type print ''; if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) @@ -475,6 +470,11 @@ if ($resql) print dol_trunc($labeltype,28); print ''; + // Label + print ''; + print $actionstatic->label; + print ''; + // Start date print ''; print dol_print_date($db->jdate($obj->dp),"dayhour"); diff --git a/htdocs/comm/action/rapport/index.php b/htdocs/comm/action/rapport/index.php index dcda4e0cf04..5994f692cc8 100644 --- a/htdocs/comm/action/rapport/index.php +++ b/htdocs/comm/action/rapport/index.php @@ -116,7 +116,7 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("Actions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_agenda', 0, '', '', $limit); + print_barre_liste($langs->trans("EventReports"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_agenda', 0, '', '', $limit); $moreforfilter=''; diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index 9f67db88bbb..c8338d22379 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -203,7 +203,7 @@ if (empty($reshook)) $targetobject = null; // Not defined with mass emailing $parameters=array('mode'=>'emailing'); - $substitutionarray=getCommonSubstitutionArray($langs, 2, array('object','objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) $substitutionarray['__ID__'] = $obj->source_id; @@ -216,7 +216,8 @@ if (empty($reshook)) $substitutionarray['__OTHER3__'] = $other3; $substitutionarray['__OTHER4__'] = $other4; $substitutionarray['__OTHER5__'] = $other5; - $substitutionarray['__SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) + $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) + $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility $substitutionarray['__CHECK_READ__'] = ''; $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 4fc1eebb66d..48756a8828c 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -231,8 +231,8 @@ if (empty($reshook)) // Validation else if ($action == 'confirm_validate' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) ) { $result = $object->valid($user); @@ -294,15 +294,15 @@ 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'); } } // 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')); + } // Create proposal else if ($action == 'add' && $user->rights->propal->creer) @@ -346,11 +346,11 @@ if (empty($reshook)) $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->fk_delivery_address = GETPOST('fk_address'); - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->duree_validite = $duration; $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->remise_percent = GETPOST('remise_percent'); $object->remise_absolue = GETPOST('remise_absolue'); $object->socid = GETPOST('socid'); @@ -377,11 +377,11 @@ if (empty($reshook)) $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->fk_delivery_address = GETPOST('fk_address'); - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->duree_validite = GETPOST('duree_validite'); $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->contactid = GETPOST('contactid'); $object->fk_project = GETPOST('projectid'); $object->modelpdf = GETPOST('model'); @@ -527,7 +527,7 @@ if (empty($reshook)) // Hooks $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if ($reshook < 0) $error ++; } else { @@ -561,23 +561,23 @@ if (empty($reshook)) { $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; + // 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); - } + $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); + } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); exit(); @@ -647,7 +647,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails - $actiontypecode='AC_OTH_AUTO'; + $actiontypecode='AC_OTH_AUTO'; $trigger_name='PROPAL_SENTBYMAIL'; $autocopy='MAIN_MAIL_AUTOCOPY_PROPOSAL_TO'; $trackid='pro'.$object->id; @@ -756,7 +756,7 @@ if (empty($reshook)) $db->begin(); - // $tva_tx can be 'x.x (XXX)' + // $tva_tx can be 'x.x (XXX)' // Ecrase $pu par celui du produit // Ecrase $desc par celui du produit @@ -781,7 +781,7 @@ if (empty($reshook)) // On defini prix unitaire if (! empty($conf->global->PRODUIT_MULTIPRICES) && $object->thirdparty->price_level) { - $pu_ht = $prod->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]; @@ -801,7 +801,7 @@ if (empty($reshook)) $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); if ($result) { - // If there is some prices specific to the customer + // If there is some prices specific to the customer if (count($prodcustprice->lines) > 0) { $pu_ht = price($prodcustprice->lines[0]->price); $pu_ttc = price($prodcustprice->lines[0]->price_ttc); @@ -949,18 +949,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 { $db->rollback(); @@ -1159,12 +1159,12 @@ if (empty($reshook)) // bank account else if ($action == 'setbankaccount' && $user->rights->propal->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } // shipping method else if ($action == 'setshippingmethod' && $user->rights->propal->creer) { - $result=$object->setShippingMethod(GETPOST('shipping_method_id', 'int')); + $result=$object->setShippingMethod(GETPOST('shipping_method_id', 'int')); } else if ($action == 'update_extras') { @@ -1225,10 +1225,10 @@ if (empty($reshook)) } } - // Actions to build doc - $upload_dir = $conf->propal->dir_output; - $permissioncreate=$user->rights->propal->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->propal->dir_output; + $permissioncreate=$user->rights->propal->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -1252,7 +1252,7 @@ $now = dol_now(); // Add new proposal if ($action == 'create') { - $currency_code = $conf->currency; + $currency_code = $conf->currency; print load_fiche_titre($langs->trans("NewProp")); @@ -1317,14 +1317,14 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled)) { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; } } } else { - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; } $object = new Propal($db); @@ -1359,9 +1359,9 @@ if ($action == 'create') print $soc->getNomUrl(1); print ''; print ''; - if (! empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD) && ! empty($soc->shipping_method_id)) { - $shipping_method_id = $soc->shipping_method_id; - } + if (! empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD) && ! empty($soc->shipping_method_id)) { + $shipping_method_id = $soc->shipping_method_id; + } } else { print ''; print $form->select_company('', 'socid', '(s.client = 1 OR s.client = 2 OR s.client = 3) AND status=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); @@ -1427,12 +1427,12 @@ if ($action == 'create') $form->select_types_paiements($soc->mode_reglement_id, 'mode_reglement_id'); print ''; - // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - print '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; - } + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { + print '' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; + } // What trigger creation print '' . $langs->trans('Source') . ''; @@ -1444,12 +1444,12 @@ if ($action == 'create') $form->selectAvailabilityDelay('', '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 ''; + } // Delivery date (or manufacturing) print '' . $langs->trans("DeliveryDate") . ''; @@ -1485,8 +1485,8 @@ if ($action == 'create') { print ''; print ''; - print ''; - print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms)?$soc->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms)?$soc->location_incoterms:'')); print ''; } @@ -1503,8 +1503,8 @@ if ($action == 'create') { print ''; print ''.fieldLabel('Currency','multicurrency_code').''; - print ''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code', 0); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code', 0); print ''; } @@ -1522,7 +1522,7 @@ if ($action == 'create') print ''; print '' . $langs->trans('NotePrivate') . ''; print ''; - $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); + $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); // print ' @@ -1530,13 +1530,7 @@ if ($action == 'create') } // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $object->showOptionals($extrafields, 'edit'); - } - + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; // Lines from source if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) @@ -1593,7 +1587,7 @@ if ($action == 'create') if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { - print '
      '; + print '
      '; // For backward compatibility print ''; @@ -1696,7 +1690,15 @@ if ($action == 'create') //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)); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('SetAcceptedRefused'), '', 'setstatut', $formquestion, '', 1, 250); + if (! empty($conf->notification->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + $notify = new Notify($db); + $formquestion = array_merge($formquestion, array( + array('type' => 'onecolumn', 'value' => $notify->confirmMessage('PROPAL_CLOSE_SIGNED', $object->socid, $object)), + )); + } + + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('SetAcceptedRefused'), $text, 'setstatut', $formquestion, '', 1, 250); } @@ -1763,50 +1765,50 @@ if ($action == 'create') // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.='
      '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Thirdparty + $morehtmlref.='
      '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherProposals").')'; - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
      '.$langs->trans('Project') . ' '; - if ($user->rights->propal->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->propal->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); - print '
      '; - print '
      '; - print '
      '; + print '
      '; + print '
      '; + print '
      '; print '
      '; @@ -1939,24 +1941,24 @@ if ($action == 'create') print ''; print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } // Origin of demand print ''; - print ''; + // Bank Account + print ''; + print ''; } // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print ''; + print ''; + print ''; } // Other attributes @@ -2103,25 +2105,25 @@ if ($action == 'create') print '
      '; print '
      '; - print '
      '; - print ''; - if ($action != 'editshippingmethod' && $user->rights->propal->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->propal->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 '
      '; @@ -2052,36 +2054,36 @@ if ($action == 'create') if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { - // Bank Account - print '
      '; - print ''; - if ($action != 'editbankaccount' && $user->rights->propal->creer) - print ''; - print '
      '; - print $langs->trans('BankAccount'); - 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 ''; + if ($action != 'editbankaccount' && $user->rights->propal->creer) + print ''; + print '
      '; + print $langs->trans('BankAccount'); + 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 $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->propal->creer) print ''.img_edit().''; - else print ' '; - print '
      '; - print '
      '; + print '
      '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->propal->creer) print ''.img_edit().''; + else print ' '; + print '
      '; + print '
      '; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2090,7 +2092,7 @@ if ($action == 'create') { 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 '
      '; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { - // Multicurrency Amount HT - print ''; - print ''; - print ''; + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // 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 HT print ''; @@ -2136,15 +2138,15 @@ if ($action == 'create') // Amount Local Taxes if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // Amount TTC @@ -2160,7 +2162,7 @@ if ($action == 'create') // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print ''; @@ -2199,7 +2201,7 @@ if ($action == 'create') include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - 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') . '
      ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
      ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
      ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
      ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
      '; if (! empty($object->lines)) @@ -2221,7 +2223,7 @@ if ($action == 'create') } print '
      '; - print '
    • '; + print '
      '; print "\n"; @@ -2235,7 +2237,7 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { if ($action != 'editline') @@ -2243,12 +2245,12 @@ if ($action == 'create') // Validate if ($object->statut == Propal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) - { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) + { print ''; - } - else + } + else print ''; } // Create event @@ -2282,6 +2284,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"); diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 42dbdbf9d2c..b49baf164ca 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -30,482 +30,518 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; class Proposals extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid' + ); - /** - * @var propal $propal {@type propal} - */ - public $propal; + /** + * @var propal $propal {@type propal} + */ + public $propal; - /** - * Constructor - */ - function __construct() - { + /** + * Constructor + */ + function __construct() + { global $db, $conf; $this->db = $db; - $this->propal = new Propal($this->db); - } + $this->propal = new Propal($this->db); + } - /** - * Get properties of a commercial proposal object - * - * Return an array with commercial proposal informations - * - * @param int $id ID of commercial proposal - * @return array|mixed data without useless information + /** + * Get properties of a commercial proposal object * - * @throws RestException - */ - function get($id) - { + * Return an array with commercial proposal informations + * + * @param int $id ID of commercial proposal + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { if(! DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $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); } - $this->propal->fetchObjectLinked(); + $this->propal->fetchObjectLinked(); return $this->_cleanObjectDatas($this->propal); - } + } - /** - * List commercial proposals - * - * Get a list of commercial proposals - * - * @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 commercial proposal 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.datec:<:'20160101')" - * @return array Array of order objects - */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { - global $db, $conf; + /** + * List commercial proposals + * + * Get a list of commercial proposals + * + * @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 commercial proposal 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.datec:<:'20160101')" + * @return array Array of order objects + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + global $db, $conf; - $obj_ret = array(); + $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; + // 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; + // 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."propal as t"; + $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."propal 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 + 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('propal').')'; - 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.= ' WHERE t.entity IN ('.getEntity('propal').')'; + 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->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); - } + $sql.= $db->plimit($limit + 1, $offset); + } - $result = $db->query($sql); + $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); - $propal_static = new Propal($db); - if($propal_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($propal_static); - } - $i++; - } - } - else { - throw new RestException(503, 'Error when retrieve propal list : '.$db->lasterror()); - } - if( ! count($obj_ret)) { - throw new RestException(404, 'No order found'); - } + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $db->fetch_object($result); + $propal_static = new Propal($db); + if($propal_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($propal_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve propal list : '.$db->lasterror()); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No order found'); + } return $obj_ret; - } + } - /** - * Create commercial proposal object - * - * @param array $request_data Request data - * @return int ID of propal - */ - function post($request_data = NULL) - { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Create commercial proposal object + * + * @param array $request_data Request data + * @return int ID of propal + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401, "Insuffisant rights"); } - // Check mandatory fields - $result = $this->_validate($request_data); + // Check mandatory fields + $result = $this->_validate($request_data); - foreach($request_data as $field => $value) { - $this->propal->$field = $value; - } - /*if (isset($request_data["lines"])) { + foreach($request_data as $field => $value) { + $this->propal->$field = $value; + } + /*if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { array_push($lines, (object) $line); } $this->propal->lines = $lines; }*/ - if ($this->propal->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating order", array_merge(array($this->propal->error), $this->propal->errors)); - } + if ($this->propal->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating order", array_merge(array($this->propal->error), $this->propal->errors)); + } - return $this->propal->id; - } + return $this->propal->id; + } - /** - * Get lines of a commercial proposal - * - * @param int $id Id of commercial proposal - * - * @url GET {id}/lines - * - * @return int - */ - function getLines($id) { - if(! DolibarrApiAccess::$user->rights->propal->lire) { + /** + * Get lines of a commercial proposal + * + * @param int $id Id of commercial proposal + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $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); - } - $this->propal->getLinesArray(); - $result = array(); - foreach ($this->propal->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } + } + $this->propal->getLinesArray(); + $result = array(); + foreach ($this->propal->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Add a line to given commercial proposal - * - * @param int $id Id of commercial proposal to update - * @param array $request_data Commercial proposal line data - * - * @url POST {id}/lines - * - * @return int - */ - function postLine($id, $request_data = NULL) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Add a line to given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param array $request_data Commercial proposal line data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) + { + 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'); - } + $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); - } - $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->pu_ht_devise, - $request_data->fk_remise_except - ); - - if ($updateRes > 0) { - return $this->get($id)->line->rowid; - - } - return false; - } - - /** - * Update a line of given commercial proposal - * - * @param int $id Id of commercial proposal to update - * @param int $lineid Id of line to update - * @param array $request_data Commercial proposal line data - * - * @url PUT {id}/lines/{lineid} - * - * @return object - */ - function putLine($id, $lineid, $request_data = NULL) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } - - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Proposal not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->propal->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $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->fk_unit - ); - - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - } - - /** - * Delete a line of given commercial proposal - * - * - * @param int $id Id of commercial proposal to update - * @param int $lineid Id of line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return int - */ - function delLine($id, $lineid) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } - - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Proposal not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->propal->deleteline($lineid); - if ($updateRes == 1) { - return $this->get($id); - } - return false; - } - - /** - * Update commercial proposal general fields (won't touch lines of commercial proposal) - * - * @param int $id Id of commercial proposal to update - * @param array $request_data Datas - * - * @return int - */ - function put($id, $request_data = NULL) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } - - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Proposal not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + if (! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) + { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach($request_data as $field => $value) { - if ($field == 'id') continue; - $this->propal->$field = $value; - } - if($this->propal->update($id, DolibarrApiAccess::$user,1,'','','update')) - return $this->get($id); + $request_data = (object) $request_data; - return false; - } + $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 + ); - /** - * Delete commercial proposal - * - * @param int $id Commercial proposal ID - * - * @return array - */ - function delete($id) - { - if(! DolibarrApiAccess::$user->rights->propal->supprimer) { + if ($updateRes > 0) { + return $updateRes; + + } + return false; + } + + /** + * Update a line of given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param int $lineid Id of line to update + * @param array $request_data Commercial proposal line data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) + { + 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'); - } + + $result = $this->propal->fetch($id); + if($result <= 0) { + throw new RestException(404, 'Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + + $propalline = new PropaleLigne($this->db); + $result = $propalline->fetch($lineid); + if ($result <= 0) { + throw new RestException(404, 'Proposal line not found'); + } + + $updateRes = $this->propal->updateline( + $lineid, + isset($request_data->subprice)?$request_data->subprice:$propalline->subprice, + isset($request_data->qty)?$request_data->qty:$propalline->qty, + isset($request_data->remise_percent)?$request_data->remise_percent:$propalline->remise_percent, + isset($request_data->tva_tx)?$request_data->tva_tx:$propalline->tva_tx, + isset($request_data->localtax1_tx)?$request_data->localtax1_tx:$propalline->localtax1_tx, + isset($request_data->localtax2_tx)?$request_data->localtax2_tx:$propalline->localtax2_tx, + isset($request_data->desc)?$request_data->desc:$propalline->desc, + 'HT', + isset($request_data->info_bits)?$request_data->info_bits:$propalline->info_bits, + isset($request_data->special_code)?$request_data->special_code:$propalline->special_code, + isset($request_data->fk_parent_line)?$request_data->fk_parent_line:$propalline->fk_parent_line, + 0, + isset($request_data->fk_fournprice)?$request_data->fk_fournprice:$propalline->fk_fournprice, + isset($request_data->pa_ht)?$request_data->pa_ht:$propalline->pa_ht, + isset($request_data->label)?$request_data->label:$propalline->label, + isset($request_data->product_type)?$request_data->product_type:$propalline->product_type, + isset($request_data->date_start)?$request_data->date_start:$propalline->date_start, + isset($request_data->date_end)?$request_data->date_end:$propalline->date_end, + isset($request_data->array_options)?$request_data->array_options:$propalline->array_options, + isset($request_data->fk_unit)?$request_data->fk_unit:$propalline->fk_unit, + isset($request_data->multicurrency_subprice)?$request_data->multicurrency_subprice:$propalline->subprice + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + + /** + * Delete a line of given commercial proposal + * + * + * @param int $id Id of commercial proposal 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->propal->creer) { + throw new RestException(401); + } + + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + $updateRes = $this->propal->deleteline($lineid); + if ($updateRes > 0) { + return $this->get($id); + } + return false; + } + + /** + * Update commercial proposal general fields (won't touch lines of commercial proposal) + * + * @param int $id Id of commercial proposal to update + * @param array $request_data Datas + * + * @return int + */ + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + foreach($request_data as $field => $value) { + if ($field == 'id') continue; + $this->propal->$field = $value; + } - if( ! $this->propal->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error); - } + if($this->propal->update($id, DolibarrApiAccess::$user,1,'','','update')) + return $this->get($id); - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Commercial Proposal deleted' - ) - ); + return false; + } - } - - /** - * Validate a commercial proposal - * - * @param int $id Commercial proposal ID - * @param int $notrigger Use {} - * - * @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 - * { - * "notrigger": 0 - * } - */ - function validate($id, $notrigger=0) - { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + /** + * Delete commercial proposal + * + * @param int $id Commercial proposal ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->propal->supprimer) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $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->valid(DolibarrApiAccess::$user, $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 Commercial Proposal: '.$this->propal->error); - } + if( ! $this->propal->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Commercial Proposal validated (Ref='.$this->propal->ref.')' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal deleted' + ) + ); - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - function _validate($data) - { - $propal = array(); - foreach (Proposals::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $propal[$field] = $data[$field]; + } - } - return $propal; - } + /** + * Validate a commercial proposal + * + * @param int $id Commercial proposal ID + * @param int $notrigger Use {} + * + * @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 + * { + * "notrigger": 0 + * } + */ + function validate($id, $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->valid(DolibarrApiAccess::$user, $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 Commercial Proposal: '.$this->propal->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal validated (Ref='.$this->propal->ref.')' + ) + ); + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $propal = array(); + foreach (Proposals::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $propal[$field] = $data[$field]; + + } + return $propal; + } + + /** + * 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->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->address); + + return $object; + } } diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index a2e9cc6c36a..cd5f81783b7 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -44,40 +44,40 @@ require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php'; */ class Propal extends CommonObject { - public $element='propal'; - public $table_element='propal'; - public $table_element_line='propaldet'; - public $fk_element='fk_propal'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - public $picto='propal'; + public $element='propal'; + public $table_element='propal'; + public $table_element_line='propaldet'; + public $fk_element='fk_propal'; + protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $picto='propal'; - /** - * {@inheritdoc} - */ - protected $table_ref_field = 'ref'; + /** + * {@inheritdoc} + */ + protected $table_ref_field = 'ref'; /** * ID of the client * @var int */ - public $socid; + public $socid; - public $contactid; - public $author; - public $ref_client; + public $contactid; + public $author; + public $ref_client; /** * Status of the quote * @var int * @see Propal::STATUS_DRAFT, Propal::STATUS_VALIDATED, Propal::STATUS_SIGNED, Propal::STATUS_NOTSIGNED, Propal::STATUS_BILLED */ - public $statut; + public $statut; /** * @deprecated * @see date_creation */ - public $datec; + public $datec; /** * Creation date @@ -89,7 +89,7 @@ class Propal extends CommonObject * @deprecated * @see date_validation */ - public $datev; + public $datev; /** * Validation date @@ -101,62 +101,62 @@ class Propal extends CommonObject * Date of the quote * @var */ - public $date; + public $date; /** * @deprecated * @see date */ - public $datep; - public $date_livraison; - public $fin_validite; + public $datep; + public $date_livraison; + public $fin_validite; - public $user_author_id; - public $user_valid_id; - public $user_close_id; + public $user_author_id; + public $user_valid_id; + public $user_close_id; /** * @deprecated * @see total_ht */ - public $price; + public $price; /** * @deprecated * @see total_tva */ - public $tva; + public $tva; /** * @deprecated * @see total_ttc */ - public $total; + public $total; - public $cond_reglement_code; - public $mode_reglement_code; - public $remise; - public $remise_percent; - public $remise_absolue; - public $fk_address; - public $address_type; - public $address; - public $availability_id; - public $availability_code; - public $demand_reason_id; - public $demand_reason_code; + public $cond_reglement_code; + public $mode_reglement_code; + public $remise; + public $remise_percent; + public $remise_absolue; + public $fk_address; + public $address_type; + public $address; + public $availability_id; + public $availability_code; + public $demand_reason_id; + public $demand_reason_code; - public $products=array(); - public $extraparams=array(); + public $products=array(); + public $extraparams=array(); /** * @var PropaleLigne[] */ - public $lines = array(); - public $line; + public $lines = array(); + public $line; - public $labelstatut=array(); - public $labelstatut_short=array(); + public $labelstatut=array(); + public $labelstatut_short=array(); - public $specimen; + public $specimen; // Multicurrency public $fk_multicurrency; @@ -189,256 +189,256 @@ class Propal extends CommonObject */ const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ? - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param int $socid Id third party - * @param int $propalid Id proposal - */ - function __construct($db, $socid="", $propalid=0) - { - global $conf,$langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param int $socid Id third party + * @param int $propalid Id proposal + */ + function __construct($db, $socid="", $propalid=0) + { + global $conf,$langs; - $this->db = $db; - $this->socid = $socid; - $this->id = $propalid; - $this->products = array(); - $this->remise = 0; - $this->remise_percent = 0; - $this->remise_absolue = 0; + $this->db = $db; + $this->socid = $socid; + $this->id = $propalid; + $this->products = array(); + $this->remise = 0; + $this->remise_percent = 0; + $this->remise_absolue = 0; - $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; + $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; - $langs->load("propal"); - $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft")); - $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated")); - $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned")); - $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned")); - $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled")); - $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort")); - $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened")); - $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort")); - $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort")); - $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort")); - } + $langs->load("propal"); + $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft")); + $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated")); + $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned")); + $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned")); + $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled")); + $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort")); + $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened")); + $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort")); + $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort")); + $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort")); + } - /** - * Add line into array products - * $this->thirdparty should be loaded - * - * @param int $idproduct Product Id to add - * @param int $qty Quantity - * @param int $remise_percent Discount effected on Product - * @return int <0 if KO, >0 if OK - * - * TODO Replace calls to this function by generation objet Ligne - * inserted into table $this->products - */ - function add_product($idproduct, $qty, $remise_percent=0) - { - global $conf, $mysoc; + /** + * Add line into array products + * $this->thirdparty should be loaded + * + * @param int $idproduct Product Id to add + * @param int $qty Quantity + * @param int $remise_percent Discount effected on Product + * @return int <0 if KO, >0 if OK + * + * TODO Replace calls to this function by generation objet Ligne + * inserted into table $this->products + */ + function add_product($idproduct, $qty, $remise_percent=0) + { + global $conf, $mysoc; - if (! $qty) $qty = 1; + if (! $qty) $qty = 1; - dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); - if ($idproduct > 0) - { - $prod=new Product($this->db); - $prod->fetch($idproduct); + dol_syslog(get_class($this)."::add_product $idproduct, $qty, $remise_percent"); + if ($idproduct > 0) + { + $prod=new Product($this->db); + $prod->fetch($idproduct); - $productdesc = $prod->description; + $productdesc = $prod->description; - $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id); - $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id); - if (empty($tva_tx)) $tva_npr=0; - $vat_src_code = ''; // May be defined into tva_tx + $tva_tx = get_default_tva($mysoc,$this->thirdparty,$prod->id); + $tva_npr = get_default_npr($mysoc,$this->thirdparty,$prod->id); + if (empty($tva_tx)) $tva_npr=0; + $vat_src_code = ''; // May be defined into tva_tx - $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr); - $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr); + $localtax1_tx = get_localtax($tva_tx,1,$mysoc,$this->thirdparty,$tva_npr); + $localtax2_tx = get_localtax($tva_tx,2,$mysoc,$this->thirdparty,$tva_npr); - // multiprices - if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) - { - $price = $prod->multiprices[$this->thirdparty->price_level]; - } - else - { - $price = $prod->price; - } + // multiprices + if($conf->global->PRODUIT_MULTIPRICES && $this->thirdparty->price_level) + { + $price = $prod->multiprices[$this->thirdparty->price_level]; + } + else + { + $price = $prod->price; + } - $line = new PropaleLigne($this->db); + $line = new PropaleLigne($this->db); - $line->fk_product=$idproduct; - $line->desc=$productdesc; - $line->qty=$qty; - $line->subprice=$price; - $line->remise_percent=$remise_percent; - $line->vat_src_code=$vat_src_code; - $line->tva_tx=$tva_tx; - $line->fk_unit=$prod->fk_unit; + $line->fk_product=$idproduct; + $line->desc=$productdesc; + $line->qty=$qty; + $line->subprice=$price; + $line->remise_percent=$remise_percent; + $line->vat_src_code=$vat_src_code; + $line->tva_tx=$tva_tx; + $line->fk_unit=$prod->fk_unit; if ($tva_npr) $line->info_bits = 1; - $this->lines[]=$line; - } - } + $this->lines[]=$line; + } + } - /** - * Adding line of fixed discount in the proposal in DB - * - * @param int $idremise Id of fixed discount - * @return int >0 if OK, <0 if KO - */ - function insert_discount($idremise) - { - global $langs; + /** + * Adding line of fixed discount in the proposal in DB + * + * @param int $idremise Id of fixed discount + * @return int >0 if OK, <0 if KO + */ + function insert_discount($idremise) + { + global $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; - $this->db->begin(); + $this->db->begin(); - $remise=new DiscountAbsolute($this->db); - $result=$remise->fetch($idremise); + $remise=new DiscountAbsolute($this->db); + $result=$remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_facture) // Protection against multiple submission - { - $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); - $this->db->rollback(); - return -5; - } + if ($result > 0) + { + if ($remise->fk_facture) // Protection against multiple submission + { + $this->error=$langs->trans("ErrorDiscountAlreadyUsed"); + $this->db->rollback(); + return -5; + } - $line=new PropaleLigne($this->db); + $line=new PropaleLigne($this->db); - $this->line->context = $this->context; + $this->line->context = $this->context; - $line->fk_propal=$this->id; - $line->fk_remise_except=$remise->id; - $line->desc=$remise->description; // Description ligne - $line->vat_src_code=$remise->vat_src_code; - $line->tva_tx=$remise->tva_tx; - $line->subprice=-$remise->amount_ht; - $line->fk_product=0; // Id produit predefined - $line->qty=1; - $line->remise=0; - $line->remise_percent=0; - $line->rang=-1; - $line->info_bits=2; + $line->fk_propal=$this->id; + $line->fk_remise_except=$remise->id; + $line->desc=$remise->description; // Description ligne + $line->vat_src_code=$remise->vat_src_code; + $line->tva_tx=$remise->tva_tx; + $line->subprice=-$remise->amount_ht; + $line->fk_product=0; // Id produit predefined + $line->qty=1; + $line->remise=0; + $line->remise_percent=0; + $line->rang=-1; + $line->info_bits=2; - // TODO deprecated - $line->price=-$remise->amount_ht; + // TODO deprecated + $line->price=-$remise->amount_ht; - $line->total_ht = -$remise->amount_ht; - $line->total_tva = -$remise->amount_tva; - $line->total_ttc = -$remise->amount_ttc; + $line->total_ht = -$remise->amount_ht; + $line->total_tva = -$remise->amount_tva; + $line->total_ttc = -$remise->amount_ttc; - $result=$line->insert(); - if ($result > 0) - { - $result=$this->update_price(1); - if ($result > 0) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$line->error; - $this->db->rollback(); - return -2; - } - } - else - { - $this->db->rollback(); - return -2; - } - } + $result=$line->insert(); + if ($result > 0) + { + $result=$this->update_price(1); + if ($result > 0) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$line->error; + $this->db->rollback(); + return -2; + } + } + else + { + $this->db->rollback(); + return -2; + } + } - /** - * Add a proposal line into database (linked to product/service or not) - * The parameters are already supposed to be appropriate and with final values to the call - * of this method. Also, for the VAT rate, it must have already been defined - * by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product) - * and desc must already have the right value (it's up to the caller to manage multilanguage) - * - * @param string $desc Description de la ligne - * @param float $pu_ht Prix unitaire - * @param float $qty Quantite - * @param float $txtva Taux de tva - * @param float $txlocaltax1 Local tax 1 rate - * @param float $txlocaltax2 Local tax 2 rate - * @param int $fk_product Id du produit/service predefini - * @param float $remise_percent Pourcentage de remise de la ligne - * @param string $price_base_type HT or TTC - * @param float $pu_ttc Prix unitaire TTC - * @param int $info_bits Bits de type de lignes - * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used. - * @param int $rang Position of line - * @param int $special_code Special code (also used by externals modules!) - * @param int $fk_parent_line Id of parent line - * @param int $fk_fournprice Id supplier price - * @param int $pa_ht Buying price without tax - * @param string $label ??? - * @param int $date_start Start date of the line - * @param int $date_end End date of the line - * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $origin 'order', ... - * @param int $origin_id Id of origin object - * @param double $pu_ht_devise Unit price in currency - * @param int $fk_remise_except Id discount if line is from a discount - * @return int >0 if OK, <0 if KO - * @see add_product - */ + /** + * Add a proposal line into database (linked to product/service or not) + * The parameters are already supposed to be appropriate and with final values to the call + * of this method. Also, for the VAT rate, it must have already been defined + * by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product) + * and desc must already have the right value (it's up to the caller to manage multilanguage) + * + * @param string $desc Description de la ligne + * @param float $pu_ht Prix unitaire + * @param float $qty Quantite + * @param float $txtva Taux de tva + * @param float $txlocaltax1 Local tax 1 rate + * @param float $txlocaltax2 Local tax 2 rate + * @param int $fk_product Id du produit/service predefini + * @param float $remise_percent Pourcentage de remise de la ligne + * @param string $price_base_type HT or TTC + * @param float $pu_ttc Prix unitaire TTC + * @param int $info_bits Bits de type de lignes + * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used. + * @param int $rang Position of line + * @param int $special_code Special code (also used by externals modules!) + * @param int $fk_parent_line Id of parent line + * @param int $fk_fournprice Id supplier price + * @param int $pa_ht Buying price without tax + * @param string $label ??? + * @param int $date_start Start date of the line + * @param int $date_end End date of the line + * @param array $array_options extrafields array + * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $origin 'order', ... + * @param int $origin_id Id of origin object + * @param double $pu_ht_devise Unit price in currency + * @param int $fk_remise_except Id discount if line is from a discount + * @return int >0 if OK, <0 if KO + * @see add_product + */ function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $fk_product=0, $remise_percent=0.0, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=0, $pa_ht=0, $label='',$date_start='', $date_end='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0, $pu_ht_devise=0, $fk_remise_except=0) - { - global $mysoc, $conf, $langs; + { + global $mysoc, $conf, $langs; - dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + dol_syslog(get_class($this)."::addline propalid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_except=$remise_percent, price_base_type=$price_base_type, pu_ttc=$pu_ttc, info_bits=$info_bits, type=$type, fk_remise_except=".$fk_remise_except); + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - // Clean parameters - if (empty($remise_percent)) $remise_percent=0; - if (empty($qty)) $qty=0; - if (empty($info_bits)) $info_bits=0; - if (empty($rang)) $rang=0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0; + // Clean parameters + if (empty($remise_percent)) $remise_percent=0; + if (empty($qty)) $qty=0; + if (empty($info_bits)) $info_bits=0; + if (empty($rang)) $rang=0; + if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0; - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu_ht=price2num($pu_ht); - $pu_ttc=price2num($pu_ttc); - $txtva=price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if ($price_base_type=='HT') - { - $pu=$pu_ht; - } - else - { - $pu=$pu_ttc; - } + $remise_percent=price2num($remise_percent); + $qty=price2num($qty); + $pu_ht=price2num($pu_ht); + $pu_ttc=price2num($pu_ttc); + $txtva=price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + $txlocaltax1=price2num($txlocaltax1); + $txlocaltax2=price2num($txlocaltax2); + $pa_ht=price2num($pa_ht); + if ($price_base_type=='HT') + { + $pu=$pu_ht; + } + else + { + $pu=$pu_ttc; + } - // Check parameters - if ($type < 0) return -1; + // Check parameters + if ($type < 0) return -1; - if ($this->statut == self::STATUS_DRAFT) - { - $this->db->begin(); + if ($this->statut == self::STATUS_DRAFT) + { + $this->db->begin(); - $product_type=$type; + $product_type=$type; if (!empty($fk_product)) { $product=new Product($this->db); @@ -446,389 +446,390 @@ class Propal extends CommonObject $product_type=$product->type; if (! empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_PROPOSAL) && $product_type == 0 && $product->stock_reel < $qty) { - $langs->load("errors"); - $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref); + $langs->load("errors"); + $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnProposal', $product->ref); $this->db->rollback(); return -3; } } // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - // 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. + } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; $pu_ht = $tabprice[3]; $pu_tva = $tabprice[4]; $pu_ttc = $tabprice[5]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - // Rang to use - $rangtouse = $rang; - if ($rangtouse == -1) - { - $rangmax = $this->line_max($fk_parent_line); - $rangtouse = $rangmax + 1; - } + // Rang to use + $rangtouse = $rang; + if ($rangtouse == -1) + { + $rangmax = $this->line_max($fk_parent_line); + $rangtouse = $rangmax + 1; + } - // TODO A virer - // Anciens indicateurs: $price, $remise (a ne plus utiliser) - $price = $pu; - $remise = 0; - if ($remise_percent > 0) - { - $remise = round(($pu * $remise_percent / 100), 2); - $price = $pu - $remise; - } + // TODO A virer + // Anciens indicateurs: $price, $remise (a ne plus utiliser) + $price = $pu; + $remise = 0; + if ($remise_percent > 0) + { + $remise = round(($pu * $remise_percent / 100), 2); + $price = $pu - $remise; + } - // Insert line - $this->line=new PropaleLigne($this->db); + // Insert line + $this->line=new PropaleLigne($this->db); - $this->line->context = $this->context; + $this->line->context = $this->context; - $this->line->fk_propal=$this->id; - $this->line->label=$label; - $this->line->desc=$desc; - $this->line->qty=$qty; + $this->line->fk_propal=$this->id; + $this->line->label=$label; + $this->line->desc=$desc; + $this->line->qty=$qty; $this->line->vat_src_code=$vat_src_code; - $this->line->tva_tx=$txtva; - $this->line->localtax1_tx=$txlocaltax1; - $this->line->localtax2_tx=$txlocaltax2; + $this->line->tva_tx=$txtva; + $this->line->localtax1_tx=$txlocaltax1; + $this->line->localtax2_tx=$txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->fk_product=$fk_product; - $this->line->product_type=$type; - $this->line->fk_remise_except=$fk_remise_except; - $this->line->remise_percent=$remise_percent; - $this->line->subprice=$pu_ht; - $this->line->rang=$rangtouse; - $this->line->info_bits=$info_bits; - $this->line->total_ht=$total_ht; - $this->line->total_tva=$total_tva; - $this->line->total_localtax1=$total_localtax1; - $this->line->total_localtax2=$total_localtax2; - $this->line->total_ttc=$total_ttc; - $this->line->special_code=$special_code; - $this->line->fk_parent_line=$fk_parent_line; - $this->line->fk_unit=$fk_unit; + $this->line->fk_product=$fk_product; + $this->line->product_type=$type; + $this->line->fk_remise_except=$fk_remise_except; + $this->line->remise_percent=$remise_percent; + $this->line->subprice=$pu_ht; + $this->line->rang=$rangtouse; + $this->line->info_bits=$info_bits; + $this->line->total_ht=$total_ht; + $this->line->total_tva=$total_tva; + $this->line->total_localtax1=$total_localtax1; + $this->line->total_localtax2=$total_localtax2; + $this->line->total_ttc=$total_ttc; + $this->line->special_code=$special_code; + $this->line->fk_parent_line=$fk_parent_line; + $this->line->fk_unit=$fk_unit; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start=$date_start; + $this->line->date_end=$date_end; $this->line->fk_fournprice = $fk_fournprice; $this->line->pa_ht = $pa_ht; - $this->line->origin_id = $origin_id; - $this->line->origin = $origin; + $this->line->origin_id = $origin_id; + $this->line->origin = $origin; // Multicurrency $this->line->fk_multicurrency = $this->fk_multicurrency; $this->line->multicurrency_code = $this->multicurrency_code; $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - // Mise en option de la ligne - if (empty($qty) && empty($special_code)) $this->line->special_code=3; + // Mise en option de la ligne + if (empty($qty) && empty($special_code)) $this->line->special_code=3; - // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + // TODO deprecated + $this->line->price=$price; + $this->line->remise=$remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; - } + if (is_array($array_options) && count($array_options)>0) { + $this->line->array_options=$array_options; + } - $result=$this->line->insert(); - if ($result > 0) - { - // Reorder if child line - if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); + $result=$this->line->insert(); + if ($result > 0) + { + // 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; + } + } + } - /** - * Update a proposal line - * - * @param int $rowid Id de la ligne - * @param float $pu Prix unitaire (HT ou TTC selon price_base_type) - * @param float $qty Quantity - * @param float $remise_percent Remise effectuee sur le produit - * @param float $txtva Taux de TVA - * @param float $txlocaltax1 Local tax 1 rate - * @param float $txlocaltax2 Local tax 2 rate - * @param string $desc Description - * @param string $price_base_type HT ou TTC - * @param int $info_bits Miscellaneous informations - * @param int $special_code Special code (also used by externals modules!) - * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines). - * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules) - * @param int $fk_fournprice Id of origin supplier price - * @param int $pa_ht Price (without tax) of product when it was bought - * @param string $label ??? - * @param int $type 0/1=Product/service - * @param int $date_start Start date of the line - * @param int $date_end End date of the line + /** + * Update a proposal line + * + * @param int $rowid Id de la ligne + * @param float $pu Prix unitaire (HT ou TTC selon price_base_type) + * @param float $qty Quantity + * @param float $remise_percent Remise effectuee sur le produit + * @param float $txtva Taux de TVA + * @param float $txlocaltax1 Local tax 1 rate + * @param float $txlocaltax2 Local tax 2 rate + * @param string $desc Description + * @param string $price_base_type HT ou TTC + * @param int $info_bits Miscellaneous informations + * @param int $special_code Special code (also used by externals modules!) + * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines). + * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules) + * @param int $fk_fournprice Id of origin supplier price + * @param int $pa_ht Price (without tax) of product when it was bought + * @param string $label ??? + * @param int $type 0/1=Product/service + * @param int $date_start Start date of the line + * @param int $date_end End date of the line * @param array $array_options extrafields array - * @param string $fk_unit Code of the unit to use. Null to use the default one + * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency * @param int $notrigger disable line update trigger - * @return int 0 if OK, <0 if KO - */ + * @return int 0 if OK, <0 if KO + */ function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0, $txlocaltax2=0.0, $desc='', $price_base_type='HT', $info_bits=0, $special_code=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=0, $pa_ht=0, $label='', $type=0, $date_start='', $date_end='', $array_options=0, $fk_unit=null, $pu_ht_devise = 0, $notrigger=0) - { - global $mysoc; + { + global $mysoc; - dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent, + dol_syslog(get_class($this)."::updateLine rowid=$rowid, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, desc=$desc, price_base_type=$price_base_type, info_bits=$info_bits, special_code=$special_code, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, type=$type, date_start=$date_start, date_end=$date_end"); - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - // Clean parameters - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - $pu = price2num($pu); - $txtva = price2num($txtva); - $txlocaltax1=price2num($txlocaltax1); - $txlocaltax2=price2num($txlocaltax2); - $pa_ht=price2num($pa_ht); - if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag - if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag + // Clean parameters + $remise_percent=price2num($remise_percent); + $qty=price2num($qty); + $pu = price2num($pu); + $txtva = price2num($txtva); + $txlocaltax1=price2num($txlocaltax1); + $txlocaltax2=price2num($txlocaltax2); + $pa_ht=price2num($pa_ht); + if (empty($qty) && empty($special_code)) $special_code=3; // Set option tag + if (! empty($qty) && $special_code == 3) $special_code=0; // Remove option tag + if (empty($type)) $type=0; - if ($this->statut == self::STATUS_DRAFT) - { - $this->db->begin(); + if ($this->statut == self::STATUS_DRAFT) + { + $this->db->begin(); - // Calcul du total TTC et de la TVA pour la ligne a partir de - // qty, pu, remise_percent et txtva - // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker - // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. + // Calcul du total TTC et de la TVA pour la ligne a partir de + // qty, pu, remise_percent et txtva + // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker + // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - // 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. + } - $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); - $total_ht = $tabprice[0]; - $total_tva = $tabprice[1]; - $total_ttc = $tabprice[2]; - $total_localtax1 = $tabprice[9]; - $total_localtax2 = $tabprice[10]; + $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise); + $total_ht = $tabprice[0]; + $total_tva = $tabprice[1]; + $total_ttc = $tabprice[2]; + $total_localtax1 = $tabprice[9]; + $total_localtax2 = $tabprice[10]; $pu_ht = $tabprice[3]; $pu_tva = $tabprice[4]; $pu_ttc = $tabprice[5]; // MultiCurrency $multicurrency_total_ht = $tabprice[16]; - $multicurrency_total_tva = $tabprice[17]; - $multicurrency_total_ttc = $tabprice[18]; + $multicurrency_total_tva = $tabprice[17]; + $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - // Anciens indicateurs: $price, $remise (a ne plus utiliser) - $price = $pu; - if ($remise_percent > 0) - { - $remise = round(($pu * $remise_percent / 100), 2); - $price = $pu - $remise; - } + // Anciens indicateurs: $price, $remise (a ne plus utiliser) + $price = $pu; + if ($remise_percent > 0) + { + $remise = round(($pu * $remise_percent / 100), 2); + $price = $pu - $remise; + } - //Fetch current line from the database and then clone the object and set it in $oldline property - $line = new PropaleLigne($this->db); - $line->fetch($rowid); + //Fetch current line from the database and then clone the object and set it in $oldline property + $line = new PropaleLigne($this->db); + $line->fetch($rowid); $line->fetch_optionals(); // Fetch extrafields for oldcopy $staticline = clone $line; - $line->oldline = $staticline; - $this->line = $line; - $this->line->context = $this->context; + $line->oldline = $staticline; + $this->line = $line; + $this->line->context = $this->context; - // Reorder if fk_parent_line change - if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) - { - $rangmax = $this->line_max($fk_parent_line); - $this->line->rang = $rangmax + 1; - } + // Reorder if fk_parent_line change + if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) + { + $rangmax = $this->line_max($fk_parent_line); + $this->line->rang = $rangmax + 1; + } - $this->line->rowid = $rowid; - $this->line->label = $label; - $this->line->desc = $desc; - $this->line->qty = $qty; - $this->line->product_type = $type; - $this->line->vat_src_code = $vat_src_code; - $this->line->tva_tx = $txtva; - $this->line->localtax1_tx = $txlocaltax1; - $this->line->localtax2_tx = $txlocaltax2; + $this->line->rowid = $rowid; + $this->line->label = $label; + $this->line->desc = $desc; + $this->line->qty = $qty; + $this->line->product_type = $type; + $this->line->vat_src_code = $vat_src_code; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = $txlocaltax1; + $this->line->localtax2_tx = $txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->remise_percent = $remise_percent; - $this->line->subprice = $pu_ht; - $this->line->info_bits = $info_bits; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $pu_ht; + $this->line->info_bits = $info_bits; - $this->line->total_ht = $total_ht; - $this->line->total_tva = $total_tva; - $this->line->total_localtax1 = $total_localtax1; - $this->line->total_localtax2 = $total_localtax2; - $this->line->total_ttc = $total_ttc; - $this->line->special_code = $special_code; - $this->line->fk_parent_line = $fk_parent_line; - $this->line->skip_update_total = $skip_update_total; - $this->line->fk_unit = $fk_unit; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1 = $total_localtax1; + $this->line->total_localtax2 = $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->special_code = $special_code; + $this->line->fk_parent_line = $fk_parent_line; + $this->line->skip_update_total = $skip_update_total; + $this->line->fk_unit = $fk_unit; $this->line->fk_fournprice = $fk_fournprice; - $this->line->pa_ht = $pa_ht; + $this->line->pa_ht = $pa_ht; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; + $this->line->date_start=$date_start; + $this->line->date_end=$date_end; - // TODO deprecated - $this->line->price=$price; - $this->line->remise=$remise; + // TODO deprecated + $this->line->price=$price; + $this->line->remise=$remise; - if (is_array($array_options) && count($array_options)>0) { - $this->line->array_options=$array_options; - } + if (is_array($array_options) && count($array_options)>0) { + $this->line->array_options=$array_options; + } // Multicurrency $this->line->multicurrency_subprice = $pu_ht_devise; $this->line->multicurrency_total_ht = $multicurrency_total_ht; - $this->line->multicurrency_total_tva = $multicurrency_total_tva; - $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; + $this->line->multicurrency_total_tva = $multicurrency_total_tva; + $this->line->multicurrency_total_ttc = $multicurrency_total_ttc; - $result=$this->line->update($notrigger); - if ($result > 0) - { - // Reorder if child line - if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); + $result=$this->line->update($notrigger); + if ($result > 0) + { + // Reorder if child line + if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); - $this->update_price(1); + $this->update_price(1); - $this->fk_propal = $this->id; - $this->rowid = $rowid; + $this->fk_propal = $this->id; + $this->rowid = $rowid; - $this->db->commit(); - return $result; - } - else - { - $this->error=$this->line->error; + $this->db->commit(); + return $result; + } + else + { + $this->error=$this->line->error; - $this->db->rollback(); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action"); - return -2; - } - } + $this->db->rollback(); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::updateline Erreur -2 Propal en mode incompatible pour cette action"); + return -2; + } + } - /** - * Delete detail line - * - * @param int $lineid Id of line to delete - * @return int >0 if OK, <0 if KO - */ - function deleteline($lineid) - { - if ($this->statut == self::STATUS_DRAFT) - { - $line=new PropaleLigne($this->db); + /** + * Delete detail line + * + * @param int $lineid Id of line to delete + * @return int >0 if OK, <0 if KO + */ + function deleteline($lineid) + { + if ($this->statut == self::STATUS_DRAFT) + { + $line=new PropaleLigne($this->db); - // For triggers - $line->fetch($lineid); + // For triggers + $line->fetch($lineid); - if ($line->delete() > 0) - { - $this->update_price(1); + if ($line->delete() > 0) + { + $this->update_price(1); - return 1; - } - else - { - return -1; - } - } - else - { - return -2; - } - } + return 1; + } + else + { + return -1; + } + } + else + { + return -2; + } + } - /** - * Create commercial proposal into database - * this->ref can be set or empty. If empty, we will use "(PROVid)" - * - * @param User $user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >=0 if OK - */ - function create($user, $notrigger=0) - { - global $conf,$hookmanager; - $error=0; + /** + * Create commercial proposal into database + * this->ref can be set or empty. If empty, we will use "(PROVid)" + * + * @param User $user User that create + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >=0 if OK + */ + function create($user, $notrigger=0) + { + global $conf,$hookmanager; + $error=0; - $now=dol_now(); + $now=dol_now(); - // Clean parameters - if (empty($this->date)) $this->date=$this->datep; - $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); - if (empty($this->availability_id)) $this->availability_id=0; - if (empty($this->demand_reason_id)) $this->demand_reason_id=0; + // Clean parameters + if (empty($this->date)) $this->date=$this->datep; + $this->fin_validite = $this->date + ($this->duree_validite * 24 * 3600); + if (empty($this->availability_id)) $this->availability_id=0; + if (empty($this->demand_reason_id)) $this->demand_reason_id=0; // Multicurrency if (!empty($this->multicurrency_code)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); @@ -839,18 +840,18 @@ class Propal extends CommonObject $this->multicurrency_tx = 1; } - dol_syslog(get_class($this)."::create"); + dol_syslog(get_class($this)."::create"); - // Check parameters - $result=$this->fetch_thirdparty(); - if ($result < 0) - { - $this->error="Failed to fetch company"; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -3; - } + // Check parameters + $result=$this->fetch_thirdparty(); + if ($result < 0) + { + $this->error="Failed to fetch company"; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -3; + } - // Check parameters + // Check parameters if (! empty($this->ref)) // We check that ref is not already used { $result=self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used @@ -863,111 +864,111 @@ class Propal extends CommonObject } } - if (empty($this->date)) - { - $this->error="Date of proposal is required"; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -4; - } + if (empty($this->date)) + { + $this->error="Date of proposal is required"; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -4; + } - $this->db->begin(); + $this->db->begin(); - // Insert into database - $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal ("; - $sql.= "fk_soc"; - $sql.= ", price"; - $sql.= ", remise"; - $sql.= ", remise_percent"; - $sql.= ", remise_absolue"; - $sql.= ", tva"; - $sql.= ", total"; - $sql.= ", datep"; - $sql.= ", datec"; - $sql.= ", ref"; - $sql.= ", fk_user_author"; - $sql.= ", note_private"; - $sql.= ", note_public"; - $sql.= ", model_pdf"; - $sql.= ", fin_validite"; - $sql.= ", fk_cond_reglement"; - $sql.= ", fk_mode_reglement"; - $sql.= ", fk_account"; - $sql.= ", ref_client"; - $sql.= ", date_livraison"; - $sql.= ", fk_shipping_method"; - $sql.= ", fk_availability"; - $sql.= ", fk_input_reason"; - $sql.= ", fk_projet"; - $sql.= ", fk_incoterms"; - $sql.= ", location_incoterms"; - $sql.= ", entity"; - $sql.= ", fk_multicurrency"; - $sql.= ", multicurrency_code"; - $sql.= ", multicurrency_tx"; - $sql.= ") "; - $sql.= " VALUES ("; - $sql.= $this->socid; - $sql.= ", 0"; - $sql.= ", ".$this->remise; - $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL'); - $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL'); - $sql.= ", 0"; - $sql.= ", 0"; - $sql.= ", '".$this->db->idate($this->date)."'"; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ", '(PROV)'"; - $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL"); - $sql.= ", '".$this->db->escape($this->note_private)."'"; - $sql.= ", '".$this->db->escape($this->note_public)."'"; - $sql.= ", '".$this->db->escape($this->modelpdf)."'"; - $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL"); - $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); - $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); - $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); - $sql.= ", '".$this->db->escape($this->ref_client)."'"; - $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL"); - $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); - $sql.= ", ".$this->availability_id; - $sql.= ", ".$this->demand_reason_id; - $sql.= ", ".($this->fk_project?$this->fk_project:"null"); - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; - $sql.= ", ".$conf->entity; + // Insert into database + $sql = "INSERT INTO ".MAIN_DB_PREFIX."propal ("; + $sql.= "fk_soc"; + $sql.= ", price"; + $sql.= ", remise"; + $sql.= ", remise_percent"; + $sql.= ", remise_absolue"; + $sql.= ", tva"; + $sql.= ", total"; + $sql.= ", datep"; + $sql.= ", datec"; + $sql.= ", ref"; + $sql.= ", fk_user_author"; + $sql.= ", note_private"; + $sql.= ", note_public"; + $sql.= ", model_pdf"; + $sql.= ", fin_validite"; + $sql.= ", fk_cond_reglement"; + $sql.= ", fk_mode_reglement"; + $sql.= ", fk_account"; + $sql.= ", ref_client"; + $sql.= ", date_livraison"; + $sql.= ", fk_shipping_method"; + $sql.= ", fk_availability"; + $sql.= ", fk_input_reason"; + $sql.= ", fk_projet"; + $sql.= ", fk_incoterms"; + $sql.= ", location_incoterms"; + $sql.= ", entity"; + $sql.= ", fk_multicurrency"; + $sql.= ", multicurrency_code"; + $sql.= ", multicurrency_tx"; + $sql.= ") "; + $sql.= " VALUES ("; + $sql.= $this->socid; + $sql.= ", 0"; + $sql.= ", ".$this->remise; + $sql.= ", ".($this->remise_percent?$this->db->escape($this->remise_percent):'NULL'); + $sql.= ", ".($this->remise_absolue?$this->db->escape($this->remise_absolue):'NULL'); + $sql.= ", 0"; + $sql.= ", 0"; + $sql.= ", '".$this->db->idate($this->date)."'"; + $sql.= ", '".$this->db->idate($now)."'"; + $sql.= ", '(PROV)'"; + $sql.= ", ".($user->id > 0 ? "'".$user->id."'":"NULL"); + $sql.= ", '".$this->db->escape($this->note_private)."'"; + $sql.= ", '".$this->db->escape($this->note_public)."'"; + $sql.= ", '".$this->db->escape($this->modelpdf)."'"; + $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"NULL"); + $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL'); + $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL'); + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); + $sql.= ", '".$this->db->escape($this->ref_client)."'"; + $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"NULL"); + $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); + $sql.= ", ".$this->availability_id; + $sql.= ", ".$this->demand_reason_id; + $sql.= ", ".($this->fk_project?$this->fk_project:"null"); + $sql.= ", ".(int) $this->fk_incoterms; + $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql.= ", ".$conf->entity; $sql.= ", ".(int) $this->fk_multicurrency; $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql.= ", ".(double) $this->multicurrency_tx; - $sql.= ")"; + $sql.= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."propal"); - if ($this->id) - { - $this->ref='(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + if ($this->id) + { + $this->ref='(PROV'.$this->id.')'; + $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $error++; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $error++; - /* + /* * 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++) - { - // Reset fk_parent_line for line that are not child lines or special product - if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { - $fk_parent_line = 0; - } + for ($i=0;$i<$num;$i++) + { + // Reset fk_parent_line for line that are not child lines or special product + if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { + $fk_parent_line = 0; + } $result = $this->addline( $this->lines[$i]->desc, @@ -988,168 +989,168 @@ class Propal extends CommonObject $this->lines[$i]->fk_fournprice, $this->lines[$i]->pa_ht, $this->lines[$i]->label, - $this->lines[$i]->date_start, + $this->lines[$i]->date_start, $this->lines[$i]->date_end, $this->lines[$i]->array_options, $this->lines[$i]->fk_unit, - $this->element, - $this->lines[$i]->id + $this->element, + $this->lines[$i]->id ); - if ($result < 0) - { - $error++; - $this->error=$this->db->error; - dol_print_error($this->db); - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $this->lines[$i]->product_type == 9) { - $fk_parent_line = $result; - } - } - } + if ($result < 0) + { + $error++; + $this->error=$this->db->error; + dol_print_error($this->db); + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $this->lines[$i]->product_type == 9) { + $fk_parent_line = $result; + } + } + } - // Add linked object - if (! $error && $this->origin && $this->origin_id) - { - $ret = $this->add_object_linked(); - if (! $ret) dol_print_error($this->db); - } + // Add linked object + if (! $error && $this->origin && $this->origin_id) + { + $ret = $this->add_object_linked(); + if (! $ret) dol_print_error($this->db); + } - // Set delivery address - if (! $error && $this->fk_delivery_address) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address; - $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'"; - $sql.= " AND entity = ".$conf->entity; + // Set delivery address + if (! $error && $this->fk_delivery_address) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET fk_delivery_address = ".$this->fk_delivery_address; + $sql.= " WHERE ref = '".$this->db->escape($this->ref)."'"; + $sql.= " AND entity = ".$conf->entity; - $result=$this->db->query($sql); - } + $result=$this->db->query($sql); + } - if (! $error) - { - // Mise a jour infos denormalisees - $resql=$this->update_price(1); - if ($resql) - { - $action='update'; - - // 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('socid'=>$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 (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('PROPAL_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - else + if (! $error) + { + // Mise a jour infos denormalisees + $resql=$this->update_price(1); + if ($resql) { - $this->error=$this->db->lasterror(); - $error++; - } - } - } - else + $action='update'; + + // 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('socid'=>$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 (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + else + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + else { - $this->error=$this->db->lasterror(); - $error++; - } + $this->error=$this->db->lasterror(); + $error++; + } - if (! $error) - { - $this->db->commit(); - dol_syslog(get_class($this)."::create done id=".$this->id); - return $this->id; - } - else - { - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + if (! $error) + { + $this->db->commit(); + dol_syslog(get_class($this)."::create done id=".$this->id); + return $this->id; + } + else + { + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Insert into DB a proposal object completely defined by its data members (ex, results from copy). - * - * @param User $user User that create - * @return int Id of the new object if ok, <0 if ko - * @see create - */ - function create_from($user) - { - // i love this function because $this->products is not used in create function... - $this->products=$this->lines; + /** + * Insert into DB a proposal object completely defined by its data members (ex, results from copy). + * + * @param User $user User that create + * @return int Id of the new object if ok, <0 if ko + * @see create + */ + function create_from($user) + { + // i love this function because $this->products is not used in create function... + $this->products=$this->lines; - return $this->create($user); - } + return $this->create($user); + } - /** - * Load an object from its id and create a new one in database - * - * @param int $socid Id of thirdparty - * @return int New id of clone - */ - function createFromClone($socid=0) - { - global $user,$conf,$hookmanager; + /** + * Load an object from its id and create a new one in database + * + * @param int $socid Id of thirdparty + * @return int New id of clone + */ + function createFromClone($socid=0) + { + global $user,$conf,$hookmanager; dol_include_once('/projet/class/project.class.php'); - $this->context['createfromclone']='createfromclone'; + $this->context['createfromclone']='createfromclone'; - $error=0; - $now=dol_now(); + $error=0; + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); // get extrafields so they will be clone foreach($this->lines as $line) $line->fetch_optionals($line->rowid); - // Load dest object - $clonedObj = clone $this; + // Load dest object + $clonedObj = clone $this; - $objsoc=new Societe($this->db); + $objsoc=new Societe($this->db); - // Change socid if needed - if (! empty($socid) && $socid != $clonedObj->socid) - { - if ($objsoc->fetch($socid) > 0) - { - $clonedObj->socid = $objsoc->id; - $clonedObj->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - $clonedObj->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $clonedObj->fk_delivery_address = ''; + // Change socid if needed + if (! empty($socid) && $socid != $clonedObj->socid) + { + if ($objsoc->fetch($socid) > 0) + { + $clonedObj->socid = $objsoc->id; + $clonedObj->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + $clonedObj->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $clonedObj->fk_delivery_address = ''; - /*if (!empty($conf->projet->enabled)) + /*if (!empty($conf->projet->enabled)) { $project = new Project($db); if ($this->fk_project > 0 && $project->fetch($this->fk_project)) { @@ -1159,189 +1160,189 @@ class Propal extends CommonObject $clonedObj->fk_project = ''; } }*/ - $clonedObj->fk_project = ''; // A cloned proposal is set by default to no project. - } + $clonedObj->fk_project = ''; // A cloned proposal is set by default to no project. + } - // reset ref_client - $clonedObj->ref_client = ''; + // reset ref_client + $clonedObj->ref_client = ''; - // TODO Change product price if multi-prices - } - else - { - $objsoc->fetch($clonedObj->socid); - } + // TODO Change product price if multi-prices + } + else + { + $objsoc->fetch($clonedObj->socid); + } - $clonedObj->id=0; - $clonedObj->ref=''; - $clonedObj->statut=self::STATUS_DRAFT; + $clonedObj->id=0; + $clonedObj->ref=''; + $clonedObj->statut=self::STATUS_DRAFT; - // Clear fields - $clonedObj->user_author = $user->id; - $clonedObj->user_valid = ''; - $clonedObj->date = $now; - $clonedObj->datep = $now; // deprecated - $clonedObj->fin_validite = $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600); - if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client = ''; + // Clear fields + $clonedObj->user_author = $user->id; + $clonedObj->user_valid = ''; + $clonedObj->date = $now; + $clonedObj->datep = $now; // deprecated + $clonedObj->fin_validite = $clonedObj->date + ($clonedObj->duree_validite * 24 * 3600); + if (empty($conf->global->MAIN_KEEP_REF_CUSTOMER_ON_CLONING)) $clonedObj->ref_client = ''; - // Create clone + // Create clone - $result=$clonedObj->create($user); - if ($result < 0) $error++; - else - { + $result=$clonedObj->create($user); + if ($result < 0) $error++; + else + { // copy internal contacts - if ($clonedObj->copy_linked_contact($this, 'internal') < 0) - $error++; + if ($clonedObj->copy_linked_contact($this, 'internal') < 0) + $error++; - // copy external contacts if same company - elseif ($this->socid == $clonedObj->socid) - { - if ($clonedObj->copy_linked_contact($this, 'external') < 0) + // copy external contacts if same company + elseif ($this->socid == $clonedObj->socid) + { + if ($clonedObj->copy_linked_contact($this, 'external') < 0) $error++; - } - } + } + } - if (! $error) - { - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; - } + if (! $error) + { + // Hook of thirdparty module + if (is_object($hookmanager)) + { + $parameters=array('objFrom'=>$this,'clonedObj'=>$clonedObj); + $action=''; + $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } - // Call trigger - $result=$clonedObj->call_trigger('PROPAL_CLONE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result=$clonedObj->call_trigger('PROPAL_CLONE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (! $error) - { - $this->db->commit(); - return $clonedObj->id; - } - else - { - $this->db->rollback(); - return -1; - } - } + // End + if (! $error) + { + $this->db->commit(); + return $clonedObj->id; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Load a proposal from database and its ligne array - * - * @param int $rowid id of object to load - * @param string $ref Ref of proposal - * @return int >0 if OK, <0 if KO - */ - function fetch($rowid,$ref='') - { + /** + * Load a proposal from database and its ligne array + * + * @param int $rowid id of object to load + * @param string $ref Ref of proposal + * @return int >0 if OK, <0 if KO + */ + function fetch($rowid,$ref='') + { - $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; - $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; - $sql.= ", p.datec"; - $sql.= ", p.date_valid as datev"; - $sql.= ", p.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.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"; - $sql.= ", p.fk_delivery_address"; - $sql.= ", p.fk_availability"; - $sql.= ", p.fk_input_reason"; - $sql.= ", p.fk_cond_reglement"; - $sql.= ", p.fk_mode_reglement"; - $sql.= ', p.fk_account'; - $sql.= ", p.fk_shipping_method"; - $sql.= ", p.fk_incoterms, p.location_incoterms"; + $sql = "SELECT p.rowid, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; + $sql.= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; + $sql.= ", p.datec"; + $sql.= ", p.date_valid as datev"; + $sql.= ", p.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.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"; + $sql.= ", p.fk_delivery_address"; + $sql.= ", p.fk_availability"; + $sql.= ", p.fk_input_reason"; + $sql.= ", p.fk_cond_reglement"; + $sql.= ", p.fk_mode_reglement"; + $sql.= ', p.fk_account'; + $sql.= ", p.fk_shipping_method"; + $sql.= ", p.fk_incoterms, p.location_incoterms"; $sql.= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc"; - $sql.= ", i.libelle as libelle_incoterms"; - $sql.= ", c.label as statut_label"; - $sql.= ", ca.code as availability_code, ca.label as availability"; - $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; - $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; - $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; + $sql.= ", i.libelle as libelle_incoterms"; + $sql.= ", c.label as statut_label"; + $sql.= ", ca.code as availability_code, ca.label as availability"; + $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; + $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; + $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; - $sql.= " WHERE p.fk_statut = c.id"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - if ($ref) $sql.= " AND p.ref='".$ref."'"; - else $sql.= " AND p.rowid=".$rowid; + $sql.= " WHERE p.fk_statut = c.id"; + $sql.= " AND p.entity IN (".getEntity('propal').")"; + if ($ref) $sql.= " AND p.ref='".$ref."'"; + else $sql.= " AND p.rowid=".$rowid; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->ref_client = $obj->ref_client; - $this->remise = $obj->remise; - $this->remise_percent = $obj->remise_percent; - $this->remise_absolue = $obj->remise_absolue; - $this->total = $obj->total; // TODO deprecated - $this->total_ht = $obj->total_ht; - $this->total_tva = $obj->tva; - $this->total_localtax1 = $obj->localtax1; - $this->total_localtax2 = $obj->localtax2; - $this->total_ttc = $obj->total; - $this->socid = $obj->fk_soc; - $this->fk_project = $obj->fk_projet; - $this->modelpdf = $obj->model_pdf; - $this->note = $obj->note_private; // TODO deprecated - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->statut = (int) $obj->fk_statut; - $this->statut_libelle = $obj->statut_label; + $this->ref = $obj->ref; + $this->ref_client = $obj->ref_client; + $this->remise = $obj->remise; + $this->remise_percent = $obj->remise_percent; + $this->remise_absolue = $obj->remise_absolue; + $this->total = $obj->total; // TODO deprecated + $this->total_ht = $obj->total_ht; + $this->total_tva = $obj->tva; + $this->total_localtax1 = $obj->localtax1; + $this->total_localtax2 = $obj->localtax2; + $this->total_ttc = $obj->total; + $this->socid = $obj->fk_soc; + $this->fk_project = $obj->fk_projet; + $this->modelpdf = $obj->model_pdf; + $this->note = $obj->note_private; // TODO deprecated + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->statut = (int) $obj->fk_statut; + $this->statut_libelle = $obj->statut_label; - $this->datec = $this->db->jdate($obj->datec); // TODO deprecated - $this->datev = $this->db->jdate($obj->datev); // TODO deprecated - $this->date_creation = $this->db->jdate($obj->datec); //Creation date - $this->date_validation = $this->db->jdate($obj->datev); //Validation date - $this->date = $this->db->jdate($obj->dp); // Proposal date - $this->datep = $this->db->jdate($obj->dp); // deprecated - $this->fin_validite = $this->db->jdate($obj->dfv); - $this->date_livraison = $this->db->jdate($obj->date_livraison); - $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; - $this->availability_id = $obj->fk_availability; - $this->availability_code = $obj->availability_code; - $this->availability = $obj->availability; - $this->demand_reason_id = $obj->fk_input_reason; - $this->demand_reason_code = $obj->demand_reason_code; - $this->demand_reason = $obj->demand_reason; - $this->fk_address = $obj->fk_delivery_address; + $this->datec = $this->db->jdate($obj->datec); // TODO deprecated + $this->datev = $this->db->jdate($obj->datev); // TODO deprecated + $this->date_creation = $this->db->jdate($obj->datec); //Creation date + $this->date_validation = $this->db->jdate($obj->datev); //Validation date + $this->date = $this->db->jdate($obj->dp); // Proposal date + $this->datep = $this->db->jdate($obj->dp); // deprecated + $this->fin_validite = $this->db->jdate($obj->dfv); + $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; + $this->availability_id = $obj->fk_availability; + $this->availability_code = $obj->availability_code; + $this->availability = $obj->availability; + $this->demand_reason_id = $obj->fk_input_reason; + $this->demand_reason_code = $obj->demand_reason_code; + $this->demand_reason = $obj->demand_reason; + $this->fk_address = $obj->fk_delivery_address; - $this->mode_reglement_id = $obj->fk_mode_reglement; - $this->mode_reglement_code = $obj->mode_reglement_code; - $this->mode_reglement = $obj->mode_reglement; - $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; - $this->cond_reglement_id = $obj->fk_cond_reglement; - $this->cond_reglement_code = $obj->cond_reglement_code; - $this->cond_reglement = $obj->cond_reglement; - $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->mode_reglement_id = $obj->fk_mode_reglement; + $this->mode_reglement_code = $obj->mode_reglement_code; + $this->mode_reglement = $obj->mode_reglement; + $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; + $this->cond_reglement_id = $obj->fk_cond_reglement; + $this->cond_reglement_code = $obj->cond_reglement_code; + $this->cond_reglement = $obj->cond_reglement; + $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; - $this->extraparams = (array) json_decode($obj->extraparams, true); + $this->extraparams = (array) json_decode($obj->extraparams, true); - $this->user_author_id = $obj->fk_user_author; - $this->user_valid_id = $obj->fk_user_valid; - $this->user_close_id = $obj->fk_user_cloture; + $this->user_author_id = $obj->fk_user_author; + $this->user_valid_id = $obj->fk_user_valid; + $this->user_close_id = $obj->fk_user_cloture; //Incoterms $this->fk_incoterms = $obj->fk_incoterms; @@ -1356,43 +1357,43 @@ class Propal extends CommonObject $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($obj->fk_statut == self::STATUS_DRAFT) - { - $this->brouillon = 1; - } + if ($obj->fk_statut == self::STATUS_DRAFT) + { + $this->brouillon = 1; + } - // Retreive all extrafield for invoice - // fetch optionals attributes and labels - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + // Retreive all extrafield for invoice + // fetch optionals attributes and labels + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); - $this->db->free($resql); + $this->db->free($resql); - $this->lines = array(); + $this->lines = array(); - /* + /* * Lines */ - $result=$this->fetch_lines(); - if ($result < 0) - { - return -3; - } + $result=$this->fetch_lines(); + if ($result < 0) + { + return -3; + } - return 1; - } + return 1; + } - $this->error="Record Not Found"; - return 0; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + $this->error="Record Not Found"; + return 0; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } /** * Load array lines @@ -1504,103 +1505,103 @@ 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; + /** + * 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; + $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++; + // 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; - } + { + return 1; + } + else + { + return -1; + } - } + } - /** - * Set status to validated - * - * @param User $user Object user that validate - * @param int $notrigger 1=Does not execute triggers, 0=execute triggers - * @return int <0 if KO, 0=Nothing done, >=0 if OK - */ - function valid($user, $notrigger=0) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Set status to validated + * + * @param User $user Object user that validate + * @param int $notrigger 1=Does not execute triggers, 0=execute triggers + * @return int <0 if KO, 0=Nothing done, >=0 if OK + */ + function valid($user, $notrigger=0) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - global $conf; + global $conf; - $error=0; + $error=0; - // Protection - if ($this->statut == self::STATUS_VALIDATED) - { - dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); - return 0; - } + // Protection + if ($this->statut == self::STATUS_VALIDATED) + { + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); + return 0; + } - if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))) - { - $this->error='ErrorPermissionDenied'; - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); - return -1; - } + if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))) + { + $this->error='ErrorPermissionDenied'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + } - $now=dol_now(); + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); - // Numbering module definition - $soc = new Societe($this->db); - $soc->fetch($this->socid); + // Numbering module definition + $soc = new Societe($this->db); + $soc->fetch($this->socid); - // Define new ref - if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { - $num = $this->getNextNumRef($soc); - } - else - { - $num = $this->ref; - } - $this->newref = $num; + // Define new ref + if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + { + $num = $this->getNextNumRef($soc); + } + else + { + $num = $this->ref; + } + $this->newref = $num; - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET ref = '".$num."',"; - $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET ref = '".$num."',"; + $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - dol_syslog(get_class($this)."::valid", LOG_DEBUG); + dol_syslog(get_class($this)."::valid", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -1611,607 +1612,607 @@ class Propal extends CommonObject // Trigger calls if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('PROPAL_VALIDATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result=$this->call_trigger('PROPAL_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - if (! $error) - { - $this->oldref = $this->ref; - - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - // Rename of propal directory ($this->ref = old ref, $num = new ref) - // to not lose the linked files - $oldref = dol_sanitizeFileName($this->ref); - $newref = dol_sanitizeFileName($num); - $dirsource = $conf->propal->dir_output.'/'.$oldref; - $dirdest = $conf->propal->dir_output.'/'.$newref; - - if (file_exists($dirsource)) - { - dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); - foreach($listoffiles as $fileentry) - { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } - } - } - } - - $this->ref=$num; - $this->brouillon=0; - $this->statut = self::STATUS_VALIDATED; - $this->user_valid_id=$user->id; - $this->datev=$now; - - $this->db->commit(); - return 1; - } - else + if (! $error) { - $this->db->rollback(); - return -1; - } - } - - - /** - * Define proposal date - * - * @param User $user Object user that modify - * @param int $date Date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_date($user, $date, $notrigger=0) - { - if (empty($date)) - { - $this->error='ErrorBadParameter'; - dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); - return -1; - } - - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->date = $date; - $this->datep = $date; // deprecated - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - /** - * Define end validity date - * - * @param User $user Object user that modify - * @param int $date_fin_validite End of validity date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_echeance($user, $date_fin_validite, $notrigger=0) - { - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null'); - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - - if (! $error) - { - $this->oldcopy= clone $this; - $this->fin_validite = $date_fin_validite; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - /** - * Set delivery date - * - * @param User $user Object user that modify - * @param int $date_livraison Delivery date - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_date_livraison($user, $date_livraison, $notrigger=0) - { - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->date_livraison = $date_livraison; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - /** - * Set delivery - * - * @param User $user Object user that modify - * @param int $id Availability id - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_availability($user, $id, $notrigger=0) - { - if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET fk_availability = '".$id."'"; - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->fk_availability = $id; - $this->availability_id = $id; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } - - /** - * Set source of demand - * - * @param User $user Object user that modify - * @param int $id Input reason id - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_demand_reason($user, $id, $notrigger=0) - { - if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) - { - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET fk_input_reason = ".$id; - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - - if (! $error) - { - $this->oldcopy= clone $this; - $this->fk_input_reason = $id; - $this->demand_reason_id = $id; - } - - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } - - /** - * Set customer reference number - * - * @param User $user Object user that modify - * @param string $ref_client Customer reference - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_ref_client($user, $ref_client, $notrigger=0) - { - if (! empty($user->rights->propal->creer)) - { - $error=0; - - $this->db->begin(); - - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); - $sql.= ' WHERE rowid = '.$this->id; - - dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->ref_client = $ref_client; - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - return -1; - } - } - - /** - * Set an overall discount on the proposal - * - * @param User $user Object user that modify - * @param double $remise Amount discount - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_remise_percent($user, $remise, $notrigger=0) - { - $remise=trim($remise)?trim($remise):0; - - if (! empty($user->rights->propal->creer)) - { - $remise = price2num($remise); - - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->remise_percent = $remise; - $this->update_price(1); - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - - /** - * Set an absolute overall discount on the proposal - * - * @param User $user Object user that modify - * @param double $remise Amount discount - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function set_remise_absolue($user, $remise, $notrigger=0) - { - $remise=trim($remise)?trim($remise):0; - - if (! empty($user->rights->propal->creer)) - { - $remise = price2num($remise); - - $error=0; - - $this->db->begin(); - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; - $sql.= " SET remise_absolue = ".$remise; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } - - if (! $error) - { - $this->oldcopy= clone $this; - $this->remise_absolue = $remise; - $this->update_price(1); - } - - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - } - - - - /** - * Reopen the commercial proposal - * - * @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 - * @return int <0 if KO, >0 if OK - */ - function reopen($user, $statut, $note='', $notrigger=0) - { - - $this->statut = $statut; - $error=0; - - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$this->statut.","; + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + // Rename of propal directory ($this->ref = old ref, $num = new ref) + // to not lose the linked files + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->propal->dir_output.'/'.$oldref; + $dirdest = $conf->propal->dir_output.'/'.$newref; + + if (file_exists($dirsource)) + { + dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + + $this->ref=$num; + $this->brouillon=0; + $this->statut = self::STATUS_VALIDATED; + $this->user_valid_id=$user->id; + $this->datev=$now; + + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + + + /** + * Define proposal date + * + * @param User $user Object user that modify + * @param int $date Date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_date($user, $date, $notrigger=0) + { + if (empty($date)) + { + $this->error='ErrorBadParameter'; + dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); + return -1; + } + + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->date = $date; + $this->datep = $date; // deprecated + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + /** + * Define end validity date + * + * @param User $user Object user that modify + * @param int $date_fin_validite End of validity date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_echeance($user, $date_fin_validite, $notrigger=0) + { + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fin_validite = ".($date_fin_validite!=''?"'".$this->db->idate($date_fin_validite)."'":'null'); + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + + if (! $error) + { + $this->oldcopy= clone $this; + $this->fin_validite = $date_fin_validite; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + /** + * Set delivery date + * + * @param User $user Object user that modify + * @param int $date_livraison Delivery date + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_date_livraison($user, $date_livraison, $notrigger=0) + { + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET date_livraison = ".($date_livraison!=''?"'".$this->db->idate($date_livraison)."'":'null'); + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->date_livraison = $date_livraison; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + /** + * Set delivery + * + * @param User $user Object user that modify + * @param int $id Availability id + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_availability($user, $id, $notrigger=0) + { + if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET fk_availability = '".$id."'"; + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->fk_availability = $id; + $this->availability_id = $id; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } + + /** + * Set source of demand + * + * @param User $user Object user that modify + * @param int $id Input reason id + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_demand_reason($user, $id, $notrigger=0) + { + if (! empty($user->rights->propal->creer) && $this->statut >= self::STATUS_DRAFT) + { + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET fk_input_reason = ".$id; + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + + if (! $error) + { + $this->oldcopy= clone $this; + $this->fk_input_reason = $id; + $this->demand_reason_id = $id; + } + + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } + + /** + * Set customer reference number + * + * @param User $user Object user that modify + * @param string $ref_client Customer reference + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_ref_client($user, $ref_client, $notrigger=0) + { + if (! empty($user->rights->propal->creer)) + { + $error=0; + + $this->db->begin(); + + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET ref_client = '.(empty($ref_client) ? 'NULL' : '\''.$this->db->escape($ref_client).'\''); + $sql.= ' WHERE rowid = '.$this->id; + + dol_syslog(__METHOD__.' $this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->ref_client = $ref_client; + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + return -1; + } + } + + /** + * Set an overall discount on the proposal + * + * @param User $user Object user that modify + * @param double $remise Amount discount + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_remise_percent($user, $remise, $notrigger=0) + { + $remise=trim($remise)?trim($remise):0; + + if (! empty($user->rights->propal->creer)) + { + $remise = price2num($remise); + + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET remise_percent = ".$remise; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->remise_percent = $remise; + $this->update_price(1); + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + + /** + * Set an absolute overall discount on the proposal + * + * @param User $user Object user that modify + * @param double $remise Amount discount + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function set_remise_absolue($user, $remise, $notrigger=0) + { + $remise=trim($remise)?trim($remise):0; + + if (! empty($user->rights->propal->creer)) + { + $remise = price2num($remise); + + $error=0; + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal "; + $sql.= " SET remise_absolue = ".$remise; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } + + if (! $error) + { + $this->oldcopy= clone $this; + $this->remise_absolue = $remise; + $this->update_price(1); + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + } + + + + /** + * Reopen the commercial proposal + * + * @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 + * @return int <0 if KO, >0 if OK + */ + function reopen($user, $statut, $note='', $notrigger=0) + { + + $this->statut = $statut; + $error=0; + + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET fk_statut = ".$this->statut.","; if (! empty($note)) $sql.= " note_private = '".$this->db->escape($note)."',"; - $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; - $sql.= " WHERE rowid = ".$this->id; + $sql.= " date_cloture=NULL, fk_user_cloture=NULL"; + $sql.= " WHERE rowid = ".$this->id; - $this->db->begin(); + $this->db->begin(); dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2222,24 +2223,24 @@ class Propal extends CommonObject { if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('PROPAL_REOPEN',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('PROPAL_REOPEN',$user); + if ($result < 0) { $error++; } + // End call triggers } } // Commit or rollback if ($error) { - if (!empty($this->errors)) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - } + if (!empty($this->errors)) + { + 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; } @@ -2248,746 +2249,746 @@ class Propal extends CommonObject $this->db->commit(); return 1; } - } + } - /** - * Close the commercial proposal - * - * @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 - * @return int <0 if KO, >0 if OK - */ - function cloture($user, $statut, $note, $notrigger=0) - { - global $langs,$conf; + /** + * Close the commercial proposal + * + * @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 + * @return int <0 if KO, >0 if OK + */ + function cloture($user, $statut, $note, $notrigger=0) + { + global $langs,$conf; - $error=0; - $now=dol_now(); + $error=0; + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); - $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.= " WHERE rowid = ".$this->id; + $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.= " WHERE rowid = ".$this->id; - $resql=$this->db->query($sql); - if ($resql) - { - $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; - $trigger_name='PROPAL_CLOSE_REFUSED'; + $resql=$this->db->query($sql); + if ($resql) + { + $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; + $trigger_name='PROPAL_CLOSE_REFUSED'; - if ($statut == self::STATUS_SIGNED) - { - $trigger_name='PROPAL_CLOSE_SIGNED'; + if ($statut == self::STATUS_SIGNED) + { + $trigger_name='PROPAL_CLOSE_SIGNED'; $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf; - // The connected company is classified as a client - $soc=new Societe($this->db); - $soc->id = $this->socid; - $result=$soc->set_as_client(); + // The connected company is classified as a client + $soc=new Societe($this->db); + $soc->id = $this->socid; + $result=$soc->set_as_client(); - if ($result < 0) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } - if ($statut == self::STATUS_BILLED) - { - $trigger_name='PROPAL_CLASSIFY_BILLED'; - } + if ($result < 0) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } + if ($statut == self::STATUS_BILLED) + { + $trigger_name='PROPAL_CLASSIFY_BILLED'; + } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $outputlangs = new Translate("",$conf); - $newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang); - $outputlangs->setDefaultLang($newlang); - } - //$ret=$object->fetch($id); // Reload to get new records - $this->generateDocument($modelpdf, $outputlangs); - } + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + // Define output language + $outputlangs = $langs; + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $outputlangs = new Translate("",$conf); + $newlang=(GETPOST('lang_id','aZ09') ? GETPOST('lang_id','aZ09') : $this->thirdparty->default_lang); + $outputlangs->setDefaultLang($newlang); + } + //$ret=$object->fetch($id); // Reload to get new records + $this->generateDocument($modelpdf, $outputlangs); + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->statut = $statut; - $this->date_cloture = $now; - $this->note_private = $note; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->statut = $statut; + $this->date_cloture = $now; + $this->note_private = $note; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger($trigger_name,$user); - if ($result < 0) { $error++; } - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger($trigger_name,$user); + if ($result < 0) { $error++; } + // End call triggers + } - if ( ! $error ) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + if ( ! $error ) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Class invoiced the Propal - * - * @param User $user Object user - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 si ko, >0 si ok - */ - function classifyBilled(User $user, $notrigger=0) - { - $error=0; + /** + * Class invoiced the Propal + * + * @param User $user Object user + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 si ko, >0 si ok + */ + function classifyBilled(User $user, $notrigger=0) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED; - $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal SET fk_statut = '.self::STATUS_BILLED; + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->statut=self::STATUS_BILLED; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->statut=self::STATUS_BILLED; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } - /** - * Class invoiced the Propal - * - * @return int <0 si ko, >0 si ok - * @deprecated - * @see classifyBilled() - */ - function classer_facturee() - { - global $user; + /** + * Class invoiced the Propal + * + * @return int <0 si ko, >0 si ok + * @deprecated + * @see classifyBilled() + */ + function classer_facturee() + { + global $user; dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING); - return $this->classifyBilled($user); - } + return $this->classifyBilled($user); + } - /** - * Set draft status - * - * @param User $user Object user that modify - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function set_draft($user, $notrigger=0) - { - $error=0; + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function set_draft($user, $notrigger=0) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT; - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET fk_statut = ".self::STATUS_DRAFT; + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(__METHOD__, LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__, LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->statut = self::STATUS_DRAFT; - $this->brouillon = 1; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->statut = self::STATUS_DRAFT; + $this->brouillon = 1; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } - /** - * Return list of proposal (eventually filtered on user) into an array - * - * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) - * @param int $draft 0=not draft, 1=draft - * @param int $notcurrentuser 0=all user, 1=not current user - * @param int $socid Id third pary - * @param int $limit For pagination - * @param int $offset For pagination - * @param string $sortfield Sort criteria - * @param string $sortorder Sort order - * @return int -1 if KO, array with result if OK - */ - function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC') - { - global $user; + /** + * Return list of proposal (eventually filtered on user) into an array + * + * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name) + * @param int $draft 0=not draft, 1=draft + * @param int $notcurrentuser 0=all user, 1=not current user + * @param int $socid Id third pary + * @param int $limit For pagination + * @param int $offset For pagination + * @param string $sortfield Sort criteria + * @param string $sortorder Sort order + * @return int -1 if KO, array with result if OK + */ + function liste_array($shortlist=0, $draft=0, $notcurrentuser=0, $socid=0, $limit=0, $offset=0, $sortfield='p.datep', $sortorder='DESC') + { + global $user; - $ga = array(); + $ga = array(); - $sql = "SELECT s.rowid, s.nom as name, s.client,"; - $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; - $sql.= " p.datep as dp, p.fin_validite as datelimite"; - if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; + $sql = "SELECT s.rowid, s.nom as name, s.client,"; + $sql.= " p.rowid as propalid, p.fk_statut, p.total_ht, p.ref, p.remise, "; + $sql.= " p.datep as dp, p.fin_validite as datelimite"; + if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.entity IN (".getEntity('propal').")"; - $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.fk_statut = c.id"; - if (! $user->rights->societe->client->voir && ! $socid) //restriction - { - $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - } - if ($socid) $sql.= " AND s.rowid = ".$socid; - if ($draft) $sql.= " AND p.fk_statut = ".self::STATUS_DRAFT; - if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; - $sql.= $this->db->order($sortfield,$sortorder); - $sql.= $this->db->plimit($limit,$offset); + $sql.= " WHERE p.entity IN (".getEntity('propal').")"; + $sql.= " AND p.fk_soc = s.rowid"; + $sql.= " AND p.fk_statut = c.id"; + if (! $user->rights->societe->client->voir && ! $socid) //restriction + { + $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + } + if ($socid) $sql.= " AND s.rowid = ".$socid; + if ($draft) $sql.= " AND p.fk_statut = ".self::STATUS_DRAFT; + if ($notcurrentuser > 0) $sql.= " AND p.fk_user_author <> ".$user->id; + $sql.= $this->db->order($sortfield,$sortorder); + $sql.= $this->db->plimit($limit,$offset); - $result=$this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - if ($num) - { - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - - if ($shortlist == 1) - { - $ga[$obj->propalid] = $obj->ref; - } - else if ($shortlist == 2) - { - $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')'; - } - else - { - $ga[$i]['id'] = $obj->propalid; - $ga[$i]['ref'] = $obj->ref; - $ga[$i]['name'] = $obj->name; - } - - $i++; - } - } - return $ga; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Returns an array with the numbers of related invoices - * - * @return array Array of invoices - */ - function getInvoiceArrayList() - { - return $this->InvoiceArrayList($this->id); - } - - /** - * Returns an array with id and ref of related invoices - * - * @param int $id Id propal - * @return array Array of invoices id - */ - function InvoiceArrayList($id) - { - $ga = array(); - $linkedInvoices = array(); - - $this->fetchObjectLinked($id,$this->element); - foreach($this->linkedObjectsIds as $objecttype => $objectid) - { - // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n - // On parcourt donc une liste d'objets en tant qu'objet unique - foreach($objectid as $key => $object) - { - // Cas des factures liees directement - if ($objecttype == 'facture') - { - $linkedInvoices[] = $object; - } - // Cas des factures liees par un autre objet (ex: commande) - else + $result=$this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + if ($num) + { + $i = 0; + while ($i < $num) { - $this->fetchObjectLinked($object,$objecttype); - foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid) - { + $obj = $this->db->fetch_object($result); + + if ($shortlist == 1) + { + $ga[$obj->propalid] = $obj->ref; + } + else if ($shortlist == 2) + { + $ga[$obj->propalid] = $obj->ref.' ('.$obj->name.')'; + } + else + { + $ga[$i]['id'] = $obj->propalid; + $ga[$i]['ref'] = $obj->ref; + $ga[$i]['name'] = $obj->name; + } + + $i++; + } + } + return $ga; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Returns an array with the numbers of related invoices + * + * @return array Array of invoices + */ + function getInvoiceArrayList() + { + return $this->InvoiceArrayList($this->id); + } + + /** + * Returns an array with id and ref of related invoices + * + * @param int $id Id propal + * @return array Array of invoices id + */ + function InvoiceArrayList($id) + { + $ga = array(); + $linkedInvoices = array(); + + $this->fetchObjectLinked($id,$this->element); + foreach($this->linkedObjectsIds as $objecttype => $objectid) + { + // Nouveau système du comon object renvoi des rowid et non un id linéaire de 1 à n + // On parcourt donc une liste d'objets en tant qu'objet unique + foreach($objectid as $key => $object) + { + // Cas des factures liees directement + if ($objecttype == 'facture') + { + $linkedInvoices[] = $object; + } + // Cas des factures liees par un autre objet (ex: commande) + else + { + $this->fetchObjectLinked($object,$objecttype); + foreach($this->linkedObjectsIds as $subobjecttype => $subobjectid) + { foreach($subobjectid as $subkey => $subobject) - { - if ($subobjecttype == 'facture') - { - $linkedInvoices[] = $subobject; - } - } - } - } - } - } + { + if ($subobjecttype == 'facture') + { + $linkedInvoices[] = $subobject; + } + } + } + } + } + } - if (count($linkedInvoices) > 0) - { - $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture"; - $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")"; + if (count($linkedInvoices) > 0) + { + $sql= "SELECT rowid as facid, facnumber, total, datef as df, fk_user_author, fk_statut, paye"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture"; + $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")"; - dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); + $resql=$this->db->query($sql); - if ($resql) - { - $tab_sqlobj=array(); - $nump = $this->db->num_rows($resql); - for ($i = 0;$i < $nump;$i++) - { - $sqlobj = $this->db->fetch_object($resql); - $tab_sqlobj[] = $sqlobj; - } - $this->db->free($resql); + if ($resql) + { + $tab_sqlobj=array(); + $nump = $this->db->num_rows($resql); + for ($i = 0;$i < $nump;$i++) + { + $sqlobj = $this->db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + } + $this->db->free($resql); - $nump = count($tab_sqlobj); + $nump = count($tab_sqlobj); - if ($nump) - { - $i = 0; - while ($i < $nump) - { - $obj = array_shift($tab_sqlobj); + if ($nump) + { + $i = 0; + while ($i < $nump) + { + $obj = array_shift($tab_sqlobj); - $ga[$i] = $obj; + $ga[$i] = $obj; - $i++; - } - } - return $ga; - } - else - { - return -1; - } - } - else return $ga; - } + $i++; + } + } + return $ga; + } + else + { + return -1; + } + } + else return $ga; + } - /** - * Delete proposal - * - * @param User $user Object user that delete - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int 1 if ok, otherwise if error - */ - function delete($user, $notrigger=0) - { - global $conf; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Delete proposal + * + * @param User $user Object user that delete + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int 1 if ok, otherwise if error + */ + function delete($user, $notrigger=0) + { + global $conf; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('PROPAL_DELETE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id; - if ($this->db->query($sql)) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { - // Delete linked object - $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal = ".$this->id; + if ($this->db->query($sql)) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE rowid = ".$this->id; + if ($this->db->query($sql)) + { + // Delete linked object + $res = $this->deleteObjectLinked(); + if ($res < 0) $error++; - // Delete linked contacts - $res = $this->delete_linked_contact(); - if ($res < 0) $error++; + // Delete linked contacts + $res = $this->delete_linked_contact(); + if ($res < 0) $error++; - if (! $error) - { - // We remove directory - $ref = dol_sanitizeFileName($this->ref); - if ($conf->propal->dir_output && !empty($this->ref)) - { - $dir = $conf->propal->dir_output . "/" . $ref ; - $file = $dir . "/" . $ref . ".pdf"; - if (file_exists($file)) - { - dol_delete_preview($this); + if (! $error) + { + // We remove directory + $ref = dol_sanitizeFileName($this->ref); + if ($conf->propal->dir_output && !empty($this->ref)) + { + $dir = $conf->propal->dir_output . "/" . $ref ; + $file = $dir . "/" . $ref . ".pdf"; + if (file_exists($file)) + { + dol_delete_preview($this); - if (! dol_delete_file($file,0,0,0,$this)) // For triggers - { - $this->error='ErrorFailToDeleteFile'; - $this->errors=array('ErrorFailToDeleteFile'); - $this->db->rollback(); - return 0; - } - } - if (file_exists($dir)) - { - $res=@dol_delete_dir_recursive($dir); - if (! $res) - { - $this->error='ErrorFailToDeleteDir'; - $this->errors=array('ErrorFailToDeleteDir'); - $this->db->rollback(); - return 0; - } - } - } - } + if (! dol_delete_file($file,0,0,0,$this)) // For triggers + { + $this->error='ErrorFailToDeleteFile'; + $this->errors=array('ErrorFailToDeleteFile'); + $this->db->rollback(); + return 0; + } + } + if (file_exists($dir)) + { + $res=@dol_delete_dir_recursive($dir); + if (! $res) + { + $this->error='ErrorFailToDeleteDir'; + $this->errors=array('ErrorFailToDeleteDir'); + $this->db->rollback(); + return 0; + } + } + } + } - // Removed extrafields - if (! $error) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - $errorflag=-4; - dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); - } - } - } + // Removed extrafields + if (! $error) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + $errorflag=-4; + dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); + } + } + } - if (! $error) - { - dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return 0; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -3; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -2; - } - } - else - { - $this->db->rollback(); - return -1; - } - } + if (! $error) + { + dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return 0; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -3; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -2; + } + } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Change the delivery time - * - * @param int $availability_id Id of new delivery time - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int >0 if OK, <0 if KO - * @deprecated use set_availability - */ - function availability($availability_id, $notrigger=0) - { - global $user; + /** + * Change the delivery time + * + * @param int $availability_id Id of new delivery time + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int >0 if OK, <0 if KO + * @deprecated use set_availability + */ + function availability($availability_id, $notrigger=0) + { + global $user; - if ($this->statut >= self::STATUS_DRAFT) - { - $error=0; + if ($this->statut >= self::STATUS_DRAFT) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; - $sql .= ' SET fk_availability = '.$availability_id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; + $sql .= ' SET fk_availability = '.$availability_id; + $sql .= ' WHERE rowid='.$this->id; - dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->availability_id = $availability_id; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->availability_id = $availability_id; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } - /** - * Change source demand - * - * @param int $demand_reason_id Id of new source demand - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int >0 si ok, <0 si ko - * @deprecated use set_demand_reason - */ - function demand_reason($demand_reason_id, $notrigger=0) - { - if ($this->statut >= self::STATUS_DRAFT) - { - $error=0; + /** + * Change source demand + * + * @param int $demand_reason_id Id of new source demand + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int >0 si ok, <0 si ko + * @deprecated use set_demand_reason + */ + function demand_reason($demand_reason_id, $notrigger=0) + { + if ($this->statut >= self::STATUS_DRAFT) + { + $error=0; - $this->db->begin(); + $this->db->begin(); - $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; - $sql .= ' SET fk_input_reason = '.$demand_reason_id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; + $sql .= ' SET fk_input_reason = '.$demand_reason_id; + $sql .= ' WHERE rowid='.$this->id; - dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG); - $resql=$this->db->query($sql); - if (!$resql) - { - $this->errors[]=$this->db->error(); - $error++; - } + dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG); + $resql=$this->db->query($sql); + if (!$resql) + { + $this->errors[]=$this->db->error(); + $error++; + } - if (! $error) - { - $this->oldcopy= clone $this; - $this->demand_reason_id = $demand_reason_id; - } + if (! $error) + { + $this->oldcopy= clone $this; + $this->demand_reason_id = $demand_reason_id; + } - if (! $notrigger && empty($error)) - { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $notrigger && empty($error)) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - foreach($this->errors as $errmsg) - { - dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - } - else - { - $error_str='Propal status do not meet requirement '.$this->statut; - dol_syslog(__METHOD__.$error_str, LOG_ERR); - $this->error=$error_str; - $this->errors[]= $this->error; - return -2; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + foreach($this->errors as $errmsg) + { + dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + } + else + { + $error_str='Propal status do not meet requirement '.$this->statut; + dol_syslog(__METHOD__.$error_str, LOG_ERR); + $this->error=$error_str; + $this->errors[]= $this->error; + return -2; + } + } - /** - * Object Proposal Information - * - * @param int $id Proposal id - * @return void - */ - function info($id) - { - $sql = "SELECT c.rowid, "; - $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; - $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; - $sql.= " WHERE c.rowid = ".$id; + /** + * Object Proposal Information + * + * @param int $id Proposal id + * @return void + */ + function info($id) + { + $sql = "SELECT c.rowid, "; + $sql.= " c.datec, c.date_valid as datev, c.date_cloture as dateo,"; + $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; + $sql.= " WHERE c.rowid = ".$id; - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; + $this->id = $obj->rowid; - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_cloture = $this->db->jdate($obj->dateo); + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_cloture = $this->db->jdate($obj->dateo); - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; - if ($obj->fk_user_valid) - { - $vuser = new User($this->db); - $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; - } + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } - if ($obj->fk_user_cloture) - { - $cluser = new User($this->db); - $cluser->fetch($obj->fk_user_cloture); - $this->user_cloture = $cluser; - } + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } - } - $this->db->free($result); + } + $this->db->free($result); - } - else - { - dol_print_error($this->db); - } - } + } + else + { + dol_print_error($this->db); + } + } - /** - * Return label of status of proposal (draft, validated, ...) - * - * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut, $mode); - } + /** + * Return label of status of proposal (draft, validated, ...) + * + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut, $mode); + } - /** - * Return label of a status (draft, validated, ...) - * - * @param int $statut id statut - * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label - */ - function LibStatut($statut,$mode=1) - { + /** + * Return label of a status (draft, validated, ...) + * + * @param int $statut id statut + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label + */ + function LibStatut($statut,$mode=1) + { global $langs; $langs->load("propal"); @@ -3004,436 +3005,436 @@ class Propal extends CommonObject if ($mode == 4) return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut]; if ($mode == 5) return ''.$this->labelstatut_short[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); if ($mode == 6) return ''.$this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); - } + } - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Object user - * @param int $mode "opened" for proposal to close, "signed" for proposal to invoice - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - function load_board($user,$mode) - { - global $conf, $langs; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Object user + * @param int $mode "opened" for proposal to close, "signed" for proposal to invoice + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + function load_board($user,$mode) + { + global $conf, $langs; - $clause = " WHERE"; + $clause = " WHERE"; - $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->societe_id) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; - $clause = " AND"; - } - $sql.= $clause." p.entity IN (".getEntity('propal').")"; - if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED; - if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED; - if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id; - - $resql=$this->db->query($sql); - if ($resql) - { - $langs->load("propal"); - $now=dol_now(); - - if ($mode == 'opened') { - $delay_warning=$conf->propal->cloture->warning_delay; - $statut = self::STATUS_VALIDATED; - $label = $langs->trans("PropalsToClose"); - } - if ($mode == 'signed') { - $delay_warning=$conf->propal->facturation->warning_delay; - $statut = self::STATUS_SIGNED; - $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered - } - - $response = new WorkboardResponse(); - $response->warning_delay = $delay_warning/60/60/24; - $response->label = $label; - $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals'; - $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc'; - $response->img = img_object('',"propal"); - - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - if ($mode == 'opened') - { - $datelimit = $this->db->jdate($obj->datefin); - if ($datelimit < ($now - $delay_warning)) - { - $response->nbtodolate++; - } - } - // TODO Definir regle des propales a facturer en retard - // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; - } - - return $response; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } - - - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - global $langs; - - // Load array of products prodids - $num_prods = 0; - $prodids = array(); - $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."product"; - $sql.= " WHERE entity IN (".getEntity('product').")"; - $resql = $this->db->query($sql); - if ($resql) - { - $num_prods = $this->db->num_rows($resql); - $i = 0; - while ($i < $num_prods) - { - $i++; - $row = $this->db->fetch_row($resql); - $prodids[$i] = $row[0]; - } - } - - // Initialise parametres - $this->id=0; - $this->ref = 'SPECIMEN'; - $this->ref_client='NEMICEPS'; - $this->specimen=1; - $this->socid = 1; - $this->date = time(); - $this->fin_validite = $this->date+3600*24*30; - $this->cond_reglement_id = 1; - $this->cond_reglement_code = 'RECEP'; - $this->mode_reglement_id = 7; - $this->mode_reglement_code = 'CHQ'; - $this->availability_id = 1; - $this->availability_code = 'AV_NOW'; - $this->demand_reason_id = 1; - $this->demand_reason_code = 'SRC_00'; - $this->note_public='This is a comment (public)'; - $this->note_private='This is a comment (private)'; - // Lines - $nbp = 5; - $xnbp = 0; - while ($xnbp < $nbp) - { - $line=new PropaleLigne($this->db); - $line->desc=$langs->trans("Description")." ".$xnbp; - $line->qty=1; - $line->subprice=100; - $line->price=100; - $line->tva_tx=20; - $line->localtax1_tx=0; - $line->localtax2_tx=0; - if ($xnbp == 2) - { - $line->total_ht=50; - $line->total_ttc=60; - $line->total_tva=10; - $line->remise_percent=50; - } - else - { - $line->total_ht=100; - $line->total_ttc=120; - $line->total_tva=20; - $line->remise_percent=00; - } - - if ($num_prods > 0) - { - $prodid = mt_rand(1, $num_prods); - $line->fk_product=$prodids[$prodid]; - $line->product_ref='SPECIMEN'; - } - - $this->lines[$xnbp]=$line; - - $this->total_ht += $line->total_ht; - $this->total_tva += $line->total_tva; - $this->total_ttc += $line->total_ttc; - - $xnbp++; - } - } - - /** - * Charge indicateurs this->nb de tableau de bord - * - * @return int <0 if ko, >0 if ok - */ - function load_state_board() - { - global $user; - - $this->nb=array(); - $clause = "WHERE"; - - $sql = "SELECT count(p.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->societe_id) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; - $sql.= " WHERE sc.fk_user = " .$user->id; - $clause = "AND"; - } - $sql.= " ".$clause." p.entity IN (".getEntity('propal').")"; - - $resql=$this->db->query($sql); - if ($resql) - { - // This assignment in condition is not a bug. It allows walking the results. - while ($obj=$this->db->fetch_object($resql)) - { - $this->nb["proposals"]=$obj->nb; - } - $this->db->free($resql); - return 1; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } - - - /** - * Returns the reference to the following non used Proposal used depending on the active numbering module - * defined into PROPALE_ADDON - * - * @param Societe $soc Object thirdparty - * @return string Reference libre pour la propale - */ - function getNextNumRef($soc) - { - global $conf,$langs; - $langs->load("propal"); - - if (! empty($conf->global->PROPALE_ADDON)) - { - $mybool=false; - - $file = $conf->global->PROPALE_ADDON.".php"; - $classname = $conf->global->PROPALE_ADDON; - - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - - $dir = dol_buildpath($reldir."core/modules/propale/"); - - // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; - } - - if (! $mybool) - { - dol_print_error('',"Failed to include file ".$file); - return ''; - } - - $obj = new $classname(); - $numref = ""; - $numref = $obj->getNextValue($soc,$this); - - if ($numref != "") - { - return $numref; - } - else - { - $this->error=$obj->error; - //dol_print_error($db,"Propale::getNextNumRef ".$obj->error); - return ""; - } - } - else + $sql = "SELECT p.rowid, p.ref, p.datec as datec, p.fin_validite as datefin"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$user->societe_id) { - $langs->load("errors"); - print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete"); - return ""; - } - } + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc"; + $sql.= " WHERE sc.fk_user = " .$user->id; + $clause = " AND"; + } + $sql.= $clause." p.entity IN (".getEntity('propal').")"; + if ($mode == 'opened') $sql.= " AND p.fk_statut = ".self::STATUS_VALIDATED; + if ($mode == 'signed') $sql.= " AND p.fk_statut = ".self::STATUS_SIGNED; + if ($user->societe_id) $sql.= " AND p.fk_soc = ".$user->societe_id; - /** - * Return clicable link of object (with eventually picto) - * - * @param int $withpicto Add picto into link - * @param string $option Where point the link ('expedition', 'document', ...) - * @param string $get_params Parametres added to url - * @param int $notooltip 1=Disable tooltip - * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @return string String with URL - */ - function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1) - { - global $langs, $conf, $user; + $resql=$this->db->query($sql); + if ($resql) + { + $langs->load("propal"); + $now=dol_now(); - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if ($mode == 'opened') { + $delay_warning=$conf->propal->cloture->warning_delay; + $statut = self::STATUS_VALIDATED; + $label = $langs->trans("PropalsToClose"); + } + if ($mode == 'signed') { + $delay_warning=$conf->propal->facturation->warning_delay; + $statut = self::STATUS_SIGNED; + $label = $langs->trans("PropalsToBill"); // We set here bill but may be billed or ordered + } - $result=''; - $label=''; - $url=''; + $response = new WorkboardResponse(); + $response->warning_delay = $delay_warning/60/60/24; + $response->label = $label; + $response->url = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals'; + $response->url_late = DOL_URL_ROOT.'/comm/propal/list.php?viewstatut='.$statut.'&mainmenu=commercial&leftmenu=propals&sortfield=p.datep&sortorder=asc'; + $response->img = img_object('',"propal"); - if ($user->rights->propal->lire) - { - $label = '' . $langs->trans("ShowPropal") . ''; - if (! empty($this->ref)) - $label.= '
      '.$langs->trans('Ref').': '.$this->ref; - if (! empty($this->ref_client)) - $label.= '
      '.$langs->trans('RefCustomer').': '.$this->ref_client; - if (! empty($this->total_ht)) - $label.= '
      ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_tva)) - $label.= '
      ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_ttc)) - $label.= '
      ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($option == '') { - $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; - } - if ($option == 'compta') { // deprecated - $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; - } - if ($option == 'expedition') { - $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params; - } - if ($option == 'document') { - $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params; - } + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; + if ($mode == 'opened') + { + $datelimit = $this->db->jdate($obj->datefin); + if ($datelimit < ($now - $delay_warning)) + { + $response->nbtodolate++; + } + } + // TODO Definir regle des propales a facturer en retard + // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++; + } - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; - } - } + return $response; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } - $linkclose=''; - if (empty($notooltip) && $user->rights->propal->lire) - { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowPropal"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; - } - $linkstart = ''; - $linkend=''; + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + global $langs; - if ($withpicto) - $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) - $result.=' '; - $result.=$linkstart.$this->ref.$linkend; - return $result; - } + // Load array of products prodids + $num_prods = 0; + $prodids = array(); + $sql = "SELECT rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."product"; + $sql.= " WHERE entity IN (".getEntity('product').")"; + $resql = $this->db->query($sql); + if ($resql) + { + $num_prods = $this->db->num_rows($resql); + $i = 0; + while ($i < $num_prods) + { + $i++; + $row = $this->db->fetch_row($resql); + $prodids[$i] = $row[0]; + } + } - /** - * Retrieve an array of propal lines + // Initialise parametres + $this->id=0; + $this->ref = 'SPECIMEN'; + $this->ref_client='NEMICEPS'; + $this->specimen=1; + $this->socid = 1; + $this->date = time(); + $this->fin_validite = $this->date+3600*24*30; + $this->cond_reglement_id = 1; + $this->cond_reglement_code = 'RECEP'; + $this->mode_reglement_id = 7; + $this->mode_reglement_code = 'CHQ'; + $this->availability_id = 1; + $this->availability_code = 'AV_NOW'; + $this->demand_reason_id = 1; + $this->demand_reason_code = 'SRC_00'; + $this->note_public='This is a comment (public)'; + $this->note_private='This is a comment (private)'; + // Lines + $nbp = 5; + $xnbp = 0; + while ($xnbp < $nbp) + { + $line=new PropaleLigne($this->db); + $line->desc=$langs->trans("Description")." ".$xnbp; + $line->qty=1; + $line->subprice=100; + $line->price=100; + $line->tva_tx=20; + $line->localtax1_tx=0; + $line->localtax2_tx=0; + if ($xnbp == 2) + { + $line->total_ht=50; + $line->total_ttc=60; + $line->total_tva=10; + $line->remise_percent=50; + } + else + { + $line->total_ht=100; + $line->total_ttc=120; + $line->total_tva=20; + $line->remise_percent=00; + } + + if ($num_prods > 0) + { + $prodid = mt_rand(1, $num_prods); + $line->fk_product=$prodids[$prodid]; + $line->product_ref='SPECIMEN'; + } + + $this->lines[$xnbp]=$line; + + $this->total_ht += $line->total_ht; + $this->total_tva += $line->total_tva; + $this->total_ttc += $line->total_ttc; + + $xnbp++; + } + } + + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 if ko, >0 if ok + */ + function load_state_board() + { + global $user; + + $this->nb=array(); + $clause = "WHERE"; + + $sql = "SELECT count(p.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->societe_id) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + $sql.= " WHERE sc.fk_user = " .$user->id; + $clause = "AND"; + } + $sql.= " ".$clause." p.entity IN (".getEntity('propal').")"; + + $resql=$this->db->query($sql); + if ($resql) + { + // This assignment in condition is not a bug. It allows walking the results. + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["proposals"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + + + /** + * Returns the reference to the following non used Proposal used depending on the active numbering module + * defined into PROPALE_ADDON + * + * @param Societe $soc Object thirdparty + * @return string Reference libre pour la propale + */ + function getNextNumRef($soc) + { + global $conf,$langs; + $langs->load("propal"); + + if (! empty($conf->global->PROPALE_ADDON)) + { + $mybool=false; + + $file = $conf->global->PROPALE_ADDON.".php"; + $classname = $conf->global->PROPALE_ADDON; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + + $dir = dol_buildpath($reldir."core/modules/propale/"); + + // Load file with numbering class (if found) + $mybool|=@include_once $dir.$file; + } + + if (! $mybool) + { + dol_print_error('',"Failed to include file ".$file); + return ''; + } + + $obj = new $classname(); + $numref = ""; + $numref = $obj->getNextValue($soc,$this); + + if ($numref != "") + { + return $numref; + } + else + { + $this->error=$obj->error; + //dol_print_error($db,"Propale::getNextNumRef ".$obj->error); + return ""; + } + } + else + { + $langs->load("errors"); + print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete"); + return ""; + } + } + + /** + * Return clicable link of object (with eventually picto) + * + * @param int $withpicto Add picto into link + * @param string $option Where point the link ('expedition', 'document', ...) + * @param string $get_params Parametres added to url + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $get_params='', $notooltip=0, $save_lastsearch_value=-1) + { + global $langs, $conf, $user; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $result=''; + $label=''; + $url=''; + + if ($user->rights->propal->lire) + { + $label = '' . $langs->trans("ShowPropal") . ''; + if (! empty($this->ref)) + $label.= '
      '.$langs->trans('Ref').': '.$this->ref; + if (! empty($this->ref_client)) + $label.= '
      '.$langs->trans('RefCustomer').': '.$this->ref_client; + if (! empty($this->total_ht)) + $label.= '
      ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
      ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_ttc)) + $label.= '
      ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if ($option == '') { + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + } + if ($option == 'compta') { // deprecated + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + } + if ($option == 'expedition') { + $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params; + } + if ($option == 'document') { + $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params; + } + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + } + + $linkclose=''; + if (empty($notooltip) && $user->rights->propal->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowPropal"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend=''; + + if ($withpicto) + $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); + if ($withpicto && $withpicto != 2) + $result.=' '; + $result.=$linkstart.$this->ref.$linkend; + return $result; + } + + /** + * Retrieve an array of propal lines * * @return int >0 if OK, <0 if KO - */ - function getLinesArray() - { - // TODO Duplicate with fetch_lines ? Wich one to keep ? + */ + function getLinesArray() + { + // TODO Duplicate with fetch_lines ? Wich one to keep ? - $this->lines = array(); + $this->lines = array(); - $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; - $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,'; - $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,'; - $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,'; - $sql.= ' pt.fk_unit,'; - $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,'; - $sql.= ' p.entity,'; + $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; + $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.localtax1_tx, pt.localtax2_tx, pt.localtax1_type, pt.localtax2_type, pt.remise_percent, pt.subprice, pt.info_bits,'; + $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.total_localtax1, pt.total_localtax2, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code,'; + $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,'; + $sql.= ' pt.fk_unit,'; + $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid, p.description as product_desc, p.tobatch as product_tobatch,'; + $sql.= ' p.entity,'; $sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; - $sql.= ' WHERE pt.fk_propal = '.$this->id; - $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; + $sql.= ' WHERE pt.fk_propal = '.$this->id; + $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; - dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; + dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $this->lines[$i] = new PropaleLigne($this->db); - $this->lines[$i]->id = $obj->rowid; // for backward compatibility - $this->lines[$i]->rowid = $obj->rowid; - $this->lines[$i]->label = $obj->custom_label; - $this->lines[$i]->desc = $obj->description; - $this->lines[$i]->description = $obj->description; - $this->lines[$i]->fk_product = $obj->fk_product; - $this->lines[$i]->ref = $obj->ref; - $this->lines[$i]->product_ref = $obj->ref; - $this->lines[$i]->entity = $obj->entity; // Product entity - $this->lines[$i]->product_label = $obj->product_label; - $this->lines[$i]->product_desc = $obj->product_desc; - $this->lines[$i]->product_tobatch = $obj->product_tobatch; - $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated - $this->lines[$i]->product_type = $obj->product_type; - $this->lines[$i]->qty = $obj->qty; - $this->lines[$i]->subprice = $obj->subprice; - $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; - $this->lines[$i]->remise_percent = $obj->remise_percent; + $this->lines[$i] = new PropaleLigne($this->db); + $this->lines[$i]->id = $obj->rowid; // for backward compatibility + $this->lines[$i]->rowid = $obj->rowid; + $this->lines[$i]->label = $obj->custom_label; + $this->lines[$i]->desc = $obj->description; + $this->lines[$i]->description = $obj->description; + $this->lines[$i]->fk_product = $obj->fk_product; + $this->lines[$i]->ref = $obj->ref; + $this->lines[$i]->product_ref = $obj->ref; + $this->lines[$i]->entity = $obj->entity; // Product entity + $this->lines[$i]->product_label = $obj->product_label; + $this->lines[$i]->product_desc = $obj->product_desc; + $this->lines[$i]->product_tobatch = $obj->product_tobatch; + $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated + $this->lines[$i]->product_type = $obj->product_type; + $this->lines[$i]->qty = $obj->qty; + $this->lines[$i]->subprice = $obj->subprice; + $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; + $this->lines[$i]->remise_percent = $obj->remise_percent; - $this->lines[$i]->vat_src_code = $obj->vat_src_code; - $this->lines[$i]->tva_tx = $obj->tva_tx; - $this->lines[$i]->localtax1_tx = $obj->localtax1_tx; - $this->lines[$i]->localtax2_tx = $obj->localtax2_tx; - $this->lines[$i]->localtax1_type = $obj->localtax1_type; - $this->lines[$i]->localtax2_type = $obj->localtax2_type; - $this->lines[$i]->info_bits = $obj->info_bits; - $this->lines[$i]->total_ht = $obj->total_ht; - $this->lines[$i]->total_tva = $obj->total_tva; - $this->lines[$i]->total_ttc = $obj->total_ttc; - $this->lines[$i]->total_localtax1 = $obj->total_localtax1; - $this->lines[$i]->total_localtax2 = $obj->total_localtax2; - $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; + $this->lines[$i]->vat_src_code = $obj->vat_src_code; + $this->lines[$i]->tva_tx = $obj->tva_tx; + $this->lines[$i]->localtax1_tx = $obj->localtax1_tx; + $this->lines[$i]->localtax2_tx = $obj->localtax2_tx; + $this->lines[$i]->localtax1_type = $obj->localtax1_type; + $this->lines[$i]->localtax2_type = $obj->localtax2_type; + $this->lines[$i]->info_bits = $obj->info_bits; + $this->lines[$i]->total_ht = $obj->total_ht; + $this->lines[$i]->total_tva = $obj->total_tva; + $this->lines[$i]->total_ttc = $obj->total_ttc; + $this->lines[$i]->total_localtax1 = $obj->total_localtax1; + $this->lines[$i]->total_localtax2 = $obj->total_localtax2; + $this->lines[$i]->fk_fournprice = $obj->fk_fournprice; $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht); $this->lines[$i]->pa_ht = $marginInfos[0]; $this->lines[$i]->marge_tx = $marginInfos[1]; $this->lines[$i]->marque_tx = $marginInfos[2]; $this->lines[$i]->fk_parent_line = $obj->fk_parent_line; - $this->lines[$i]->special_code = $obj->special_code; - $this->lines[$i]->rang = $obj->rang; - $this->lines[$i]->date_start = $this->db->jdate($obj->date_start); - $this->lines[$i]->date_end = $this->db->jdate($obj->date_end); - $this->lines[$i]->fk_unit = $obj->fk_unit; + $this->lines[$i]->special_code = $obj->special_code; + $this->lines[$i]->rang = $obj->rang; + $this->lines[$i]->date_start = $this->db->jdate($obj->date_start); + $this->lines[$i]->date_end = $this->db->jdate($obj->date_end); + $this->lines[$i]->fk_unit = $obj->fk_unit; // Multicurrency $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency; @@ -3443,18 +3444,18 @@ class Propal extends CommonObject $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - $i++; - } - $this->db->free($resql); + $i++; + } + $this->db->free($resql); - return 1; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } + return 1; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } /** * Create a document onto disk according to template module. @@ -3512,16 +3513,16 @@ class Propal extends CommonObject */ class PropaleLigne extends CommonObjectLine { - public $element='propaldet'; - public $table_element='propaldet'; + public $element='propaldet'; + public $table_element='propaldet'; - var $oldline; + var $oldline; - // From llx_propaldet - var $fk_propal; - var $fk_parent_line; - var $desc; // Description ligne - var $fk_product; // Id produit predefini + // From llx_propaldet + var $fk_propal; + var $fk_parent_line; + var $desc; // Description ligne + var $fk_product; // Id produit predefini /** * @deprecated * @see product_type @@ -3532,51 +3533,51 @@ class PropaleLigne extends CommonObjectLine * @var int * @see Product::TYPE_PRODUCT, Product::TYPE_SERVICE */ - var $product_type = Product::TYPE_PRODUCT; + var $product_type = Product::TYPE_PRODUCT; - var $qty; - var $tva_tx; - var $subprice; - var $remise_percent; - var $fk_remise_except; + var $qty; + var $tva_tx; + var $subprice; + var $remise_percent; + var $fk_remise_except; - var $rang = 0; + var $rang = 0; var $fk_fournprice; var $pa_ht; var $marge_tx; var $marque_tx; - var $special_code; // Tag for special lines (exlusive tags) - // 1: frais de port - // 2: ecotaxe - // 3: option line (when qty = 0) + var $special_code; // Tag for special lines (exlusive tags) + // 1: frais de port + // 2: ecotaxe + // 3: option line (when qty = 0) - var $info_bits = 0; // Liste d'options cumulables: - // Bit 0: 0 si TVA normal - 1 si TVA NPR - // Bit 1: 0 ligne normale - 1 si ligne de remise fixe + var $info_bits = 0; // Liste d'options cumulables: + // Bit 0: 0 si TVA normal - 1 si TVA NPR + // Bit 1: 0 ligne normale - 1 si ligne de remise fixe - var $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne - var $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne - var $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne + var $total_ht; // Total HT de la ligne toute quantite et incluant la remise ligne + var $total_tva; // Total TVA de la ligne toute quantite et incluant la remise ligne + var $total_ttc; // Total TTC de la ligne toute quantite et incluant la remise ligne /** * @deprecated * @see $remise_percent, $fk_remise_except */ - var $remise; + var $remise; /** * @deprecated * @see subprice */ - var $price; + var $price; - // From llx_product + // From llx_product /** * @deprecated * @see product_ref */ - var $ref; + var $ref; /** * Product reference * @var string @@ -3586,7 +3587,7 @@ class PropaleLigne extends CommonObjectLine * @deprecated * @see product_label */ - var $libelle; + var $libelle; /** * Product label * @var string @@ -3596,21 +3597,21 @@ class PropaleLigne extends CommonObjectLine * Product description * @var string */ - public $product_desc; + public $product_desc; - var $localtax1_tx; // Local tax 1 - var $localtax2_tx; // Local tax 2 - var $localtax1_type; // Local tax 1 type + var $localtax1_tx; // Local tax 1 + var $localtax2_tx; // Local tax 2 + var $localtax1_type; // Local tax 1 type var $localtax2_type; // Local tax 2 type - var $total_localtax1; // Line total local tax 1 - var $total_localtax2; // Line total local tax 2 + var $total_localtax1; // Line total local tax 1 + var $total_localtax2; // Line total local tax 2 - var $date_start; - var $date_end; + var $date_start; + var $date_end; - var $skip_update_total; // Skip update price total for special lines + var $skip_update_total; // Skip update price total for special lines - // Multicurrency + // Multicurrency var $fk_multicurrency; var $multicurrency_code; var $multicurrency_subprice; @@ -3618,22 +3619,22 @@ class PropaleLigne extends CommonObjectLine var $multicurrency_total_tva; var $multicurrency_total_ttc; - /** - * Class line Contructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db= $db; - } + /** + * Class line Contructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db= $db; + } - /** - * Retrieve the propal line object - * - * @param int $rowid Propal line id - * @return int <0 if KO, >0 if OK - */ + /** + * Retrieve the propal line object + * + * @param int $rowid Propal line id + * @return int <0 if KO, >0 if OK + */ function fetch($rowid) { $sql = 'SELECT pd.rowid, pd.fk_propal, pd.fk_parent_line, pd.fk_product, pd.label as custom_label, pd.description, pd.price, pd.qty, pd.vat_src_code, pd.tva_tx,'; @@ -3653,59 +3654,66 @@ class PropaleLigne extends CommonObjectLine { $objp = $this->db->fetch_object($result); - $this->id = $objp->rowid; - $this->rowid = $objp->rowid; // deprecated - $this->fk_propal = $objp->fk_propal; - $this->fk_parent_line = $objp->fk_parent_line; - $this->label = $objp->custom_label; - $this->desc = $objp->description; - $this->qty = $objp->qty; - $this->price = $objp->price; // deprecated - $this->subprice = $objp->subprice; - $this->vat_src_code = $objp->vat_src_code; - $this->tva_tx = $objp->tva_tx; - $this->remise = $objp->remise; // deprecated - $this->remise_percent = $objp->remise_percent; - $this->fk_remise_except = $objp->fk_remise_except; - $this->fk_product = $objp->fk_product; - $this->info_bits = $objp->info_bits; + if ($objp) + { + $this->id = $objp->rowid; + $this->rowid = $objp->rowid; // deprecated + $this->fk_propal = $objp->fk_propal; + $this->fk_parent_line = $objp->fk_parent_line; + $this->label = $objp->custom_label; + $this->desc = $objp->description; + $this->qty = $objp->qty; + $this->price = $objp->price; // deprecated + $this->subprice = $objp->subprice; + $this->vat_src_code = $objp->vat_src_code; + $this->tva_tx = $objp->tva_tx; + $this->remise = $objp->remise; // deprecated + $this->remise_percent = $objp->remise_percent; + $this->fk_remise_except = $objp->fk_remise_except; + $this->fk_product = $objp->fk_product; + $this->info_bits = $objp->info_bits; - $this->total_ht = $objp->total_ht; - $this->total_tva = $objp->total_tva; - $this->total_ttc = $objp->total_ttc; + $this->total_ht = $objp->total_ht; + $this->total_tva = $objp->total_tva; + $this->total_ttc = $objp->total_ttc; - $this->fk_fournprice = $objp->fk_fournprice; + $this->fk_fournprice = $objp->fk_fournprice; - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht); - $this->pa_ht = $marginInfos[0]; - $this->marge_tx = $marginInfos[1]; - $this->marque_tx = $marginInfos[2]; + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht); + $this->pa_ht = $marginInfos[0]; + $this->marge_tx = $marginInfos[1]; + $this->marque_tx = $marginInfos[2]; - $this->special_code = $objp->special_code; - $this->product_type = $objp->product_type; - $this->rang = $objp->rang; + $this->special_code = $objp->special_code; + $this->product_type = $objp->product_type; + $this->rang = $objp->rang; - $this->ref = $objp->product_ref; // deprecated - $this->product_ref = $objp->product_ref; - $this->libelle = $objp->product_label; // deprecated - $this->product_label = $objp->product_label; - $this->product_desc = $objp->product_desc; - $this->fk_unit = $objp->fk_unit; + $this->ref = $objp->product_ref; // deprecated + $this->product_ref = $objp->product_ref; + $this->libelle = $objp->product_label; // deprecated + $this->product_label = $objp->product_label; + $this->product_desc = $objp->product_desc; + $this->fk_unit = $objp->fk_unit; - $this->date_start = $this->db->jdate($objp->date_start); - $this->date_end = $this->db->jdate($objp->date_end); + $this->date_start = $this->db->jdate($objp->date_start); + $this->date_end = $this->db->jdate($objp->date_end); - // Multicurrency - $this->fk_multicurrency = $objp->fk_multicurrency; - $this->multicurrency_code = $objp->multicurrency_code; - $this->multicurrency_subprice = $objp->multicurrency_subprice; - $this->multicurrency_total_ht = $objp->multicurrency_total_ht; - $this->multicurrency_total_tva = $objp->multicurrency_total_tva; - $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc; + // Multicurrency + $this->fk_multicurrency = $objp->fk_multicurrency; + $this->multicurrency_code = $objp->multicurrency_code; + $this->multicurrency_subprice = $objp->multicurrency_subprice; + $this->multicurrency_total_ht = $objp->multicurrency_total_ht; + $this->multicurrency_total_tva = $objp->multicurrency_total_tva; + $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc; - $this->db->free($result); + $this->db->free($result); - return 1; + return 1; + } + else + { + return 0; + } } else { @@ -3713,45 +3721,45 @@ class PropaleLigne extends CommonObjectLine } } - /** - * Insert object line propal in database - * - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK - */ - function insert($notrigger=0) - { - global $conf,$user; + /** + * Insert object line propal in database + * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK + */ + function insert($notrigger=0) + { + global $conf,$user; - $error=0; + $error=0; - dol_syslog(get_class($this)."::insert rang=".$this->rang); + dol_syslog(get_class($this)."::insert rang=".$this->rang); - $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. + $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx=0; - if (empty($this->localtax1_tx)) $this->localtax1_tx=0; - if (empty($this->localtax2_tx)) $this->localtax2_tx=0; - if (empty($this->localtax1_type)) $this->localtax1_type=0; + // Clean parameters + if (empty($this->tva_tx)) $this->tva_tx=0; + if (empty($this->localtax1_tx)) $this->localtax1_tx=0; + if (empty($this->localtax2_tx)) $this->localtax2_tx=0; + if (empty($this->localtax1_type)) $this->localtax1_type=0; if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; - if (empty($this->rang)) $this->rang=0; - if (empty($this->remise)) $this->remise=0; - if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0; - if (empty($this->info_bits)) $this->info_bits=0; - if (empty($this->special_code)) $this->special_code=0; - if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_fournprice)) $this->fk_fournprice=0; + if (empty($this->total_localtax1)) $this->total_localtax1=0; + if (empty($this->total_localtax2)) $this->total_localtax2=0; + if (empty($this->rang)) $this->rang=0; + if (empty($this->remise)) $this->remise=0; + if (empty($this->remise_percent) || ! is_numeric($this->remise_percent)) $this->remise_percent=0; + if (empty($this->info_bits)) $this->info_bits=0; + if (empty($this->special_code)) $this->special_code=0; + if (empty($this->fk_parent_line)) $this->fk_parent_line=0; + if (empty($this->fk_fournprice)) $this->fk_fournprice=0; if (! is_numeric($this->qty)) $this->qty = 0; - if (empty($this->pa_ht)) $this->pa_ht=0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0; + if (empty($this->pa_ht)) $this->pa_ht=0; + if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0; + if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0; + if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0; + if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0; - // if buy price not defined, define buyprice as configured in margin admin + // if buy price not defined, define buyprice as configured in margin admin if ($this->pa_ht == 0 && $pa_ht_isemptystring) { if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) @@ -3764,183 +3772,183 @@ class PropaleLigne extends CommonObjectLine } } - // Check parameters - if ($this->product_type < 0) return -1; + // Check parameters + if ($this->product_type < 0) return -1; - $this->db->begin(); + $this->db->begin(); - // Insert line into database - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; - $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; + // Insert line into database + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; + $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; $sql.= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; - $sql.= ' subprice, remise_percent, '; - $sql.= ' info_bits, '; - $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; - $sql.= ' fk_unit,'; - $sql.= ' date_start, date_end'; + $sql.= ' subprice, remise_percent, '; + $sql.= ' info_bits, '; + $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; + $sql.= ' fk_unit,'; + $sql.= ' date_start, date_end'; $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc)'; - $sql.= " VALUES (".$this->fk_propal.","; - $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; - $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; - $sql.= " '".$this->db->escape($this->desc)."',"; - $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").","; - $sql.= " '".$this->db->escape($this->product_type)."',"; - $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").","; - $sql.= " ".price2num($this->qty).","; - $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; - $sql.= " ".price2num($this->tva_tx).","; - $sql.= " ".price2num($this->localtax1_tx).","; - $sql.= " ".price2num($this->localtax2_tx).","; + $sql.= " VALUES (".$this->fk_propal.","; + $sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").","; + $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; + $sql.= " '".$this->db->escape($this->desc)."',"; + $sql.= " ".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":"null").","; + $sql.= " '".$this->db->escape($this->product_type)."',"; + $sql.= " ".($this->fk_remise_except?"'".$this->db->escape($this->fk_remise_except)."'":"null").","; + $sql.= " ".price2num($this->qty).","; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").","; + $sql.= " ".price2num($this->tva_tx).","; + $sql.= " ".price2num($this->localtax1_tx).","; + $sql.= " ".price2num($this->localtax2_tx).","; $sql.= " '".$this->db->escape($this->localtax1_type)."',"; $sql.= " '".$this->db->escape($this->localtax2_type)."',"; - $sql.= " ".($this->subprice?price2num($this->subprice):"null").","; - $sql.= " ".price2num($this->remise_percent).","; - $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").","; - $sql.= " ".price2num($this->total_ht).","; - $sql.= " ".price2num($this->total_tva).","; - $sql.= " ".price2num($this->total_localtax1).","; - $sql.= " ".price2num($this->total_localtax2).","; - $sql.= " ".price2num($this->total_ttc).","; - $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").","; - $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; - $sql.= ' '.$this->special_code.','; - $sql.= ' '.$this->rang.','; - $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; - $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").','; - $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); + $sql.= " ".($this->subprice?price2num($this->subprice):"null").","; + $sql.= " ".price2num($this->remise_percent).","; + $sql.= " ".(isset($this->info_bits)?"'".$this->db->escape($this->info_bits)."'":"null").","; + $sql.= " ".price2num($this->total_ht).","; + $sql.= " ".price2num($this->total_tva).","; + $sql.= " ".price2num($this->total_localtax1).","; + $sql.= " ".price2num($this->total_localtax2).","; + $sql.= " ".price2num($this->total_ttc).","; + $sql.= " ".(!empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null").","; + $sql.= " ".(isset($this->pa_ht)?"'".price2num($this->pa_ht)."'":"null").","; + $sql.= ' '.$this->special_code.','; + $sql.= ' '.$this->rang.','; + $sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit).','; + $sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").','; + $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= ", ".($this->fk_multicurrency > 0?$this->fk_multicurrency:'null'); $sql.= ", '".$this->db->escape($this->multicurrency_code)."'"; $sql.= ", ".$this->multicurrency_subprice; $sql.= ", ".$this->multicurrency_total_ht; $sql.= ", ".$this->multicurrency_total_tva; $sql.= ", ".$this->multicurrency_total_ttc; - $sql.= ')'; + $sql.= ')'; - dol_syslog(get_class($this).'::insert', LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); + dol_syslog(get_class($this).'::insert', LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'propaldet'); - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('LINEPROPAL_INSERT',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_INSERT',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + } - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } - /** - * Delete line in database - * - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function delete($notrigger=0) - { - global $conf,$user; + /** + * Delete line in database + * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function delete($notrigger=0) + { + global $conf,$user; - $error=0; - $this->db->begin(); + $error=0; + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; - dol_syslog("PropaleLigne::delete", LOG_DEBUG); - if ($this->db->query($sql) ) - { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; + dol_syslog("PropaleLigne::delete", LOG_DEBUG); + if ($this->db->query($sql) ) + { - // Remove extrafields - if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } + // Remove extrafields + if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('LINEPROPAL_DELETE',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - } - // End call triggers + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_DELETE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + } + // End call triggers - $this->db->commit(); + $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error()." sql=".$sql; - $this->db->rollback(); - return -1; - } - } + return 1; + } + else + { + $this->error=$this->db->error()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } - /** - * Update propal line object into DB - * - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if ko, >0 if ok - */ - function update($notrigger=0) - { - global $conf,$user; + /** + * Update propal line object into DB + * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if ko, >0 if ok + */ + function update($notrigger=0) + { + global $conf,$user; - $error=0; + $error=0; - $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. + $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'. - // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx=0; - if (empty($this->localtax1_tx)) $this->localtax1_tx=0; - if (empty($this->localtax2_tx)) $this->localtax2_tx=0; - if (empty($this->total_localtax1)) $this->total_localtax1=0; - if (empty($this->total_localtax2)) $this->total_localtax2=0; + // Clean parameters + if (empty($this->tva_tx)) $this->tva_tx=0; + if (empty($this->localtax1_tx)) $this->localtax1_tx=0; + if (empty($this->localtax2_tx)) $this->localtax2_tx=0; + if (empty($this->total_localtax1)) $this->total_localtax1=0; + if (empty($this->total_localtax2)) $this->total_localtax2=0; if (empty($this->localtax1_type)) $this->localtax1_type=0; if (empty($this->localtax2_type)) $this->localtax2_type=0; - if (empty($this->marque_tx)) $this->marque_tx=0; - if (empty($this->marge_tx)) $this->marge_tx=0; - if (empty($this->price)) $this->price=0; // TODO A virer - if (empty($this->remise)) $this->remise=0; // TODO A virer - if (empty($this->remise_percent)) $this->remise_percent=0; - if (empty($this->info_bits)) $this->info_bits=0; - if (empty($this->special_code)) $this->special_code=0; - if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_fournprice)) $this->fk_fournprice=0; - if (empty($this->subprice)) $this->subprice=0; + if (empty($this->marque_tx)) $this->marque_tx=0; + if (empty($this->marge_tx)) $this->marge_tx=0; + if (empty($this->price)) $this->price=0; // TODO A virer + if (empty($this->remise)) $this->remise=0; // TODO A virer + if (empty($this->remise_percent)) $this->remise_percent=0; + if (empty($this->info_bits)) $this->info_bits=0; + if (empty($this->special_code)) $this->special_code=0; + if (empty($this->fk_parent_line)) $this->fk_parent_line=0; + if (empty($this->fk_fournprice)) $this->fk_fournprice=0; + if (empty($this->subprice)) $this->subprice=0; if (empty($this->pa_ht)) $this->pa_ht=0; // if buy price not defined, define buyprice as configured in margin admin @@ -3956,119 +3964,119 @@ class PropaleLigne extends CommonObjectLine } } - $this->db->begin(); + $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; - $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= ", product_type=".$this->product_type; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; + $sql.= " description='".$this->db->escape($this->desc)."'"; + $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); + $sql.= ", product_type=".$this->product_type; $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; - $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; - $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); - $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; + $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'"; $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'"; - $sql.= ", qty='".price2num($this->qty)."'"; - $sql.= ", subprice=".price2num($this->subprice).""; - $sql.= ", remise_percent=".price2num($this->remise_percent).""; - $sql.= ", price=".price2num($this->price).""; // TODO A virer - $sql.= ", remise=".price2num($this->remise).""; // TODO A virer - $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'"; - if (empty($this->skip_update_total)) - { - $sql.= ", total_ht=".price2num($this->total_ht).""; - $sql.= ", total_tva=".price2num($this->total_tva).""; - $sql.= ", total_ttc=".price2num($this->total_ttc).""; - $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; - $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; - } + $sql.= ", qty='".price2num($this->qty)."'"; + $sql.= ", subprice=".price2num($this->subprice).""; + $sql.= ", remise_percent=".price2num($this->remise_percent).""; + $sql.= ", price=".price2num($this->price).""; // TODO A virer + $sql.= ", remise=".price2num($this->remise).""; // TODO A virer + $sql.= ", info_bits='".$this->db->escape($this->info_bits)."'"; + if (empty($this->skip_update_total)) + { + $sql.= ", total_ht=".price2num($this->total_ht).""; + $sql.= ", total_tva=".price2num($this->total_tva).""; + $sql.= ", total_ttc=".price2num($this->total_ttc).""; + $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; + $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; + } $sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null"); $sql.= ", buy_price_ht=".price2num($this->pa_ht); - if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code; - $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); - if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code; + $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); + if (! empty($this->rang)) $sql.= ", rang=".$this->rang; + $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); + $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); + $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; - $sql.= " WHERE rowid = ".$this->rowid; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + } - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -2; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -2; + } + } - /** - * Update DB line fields total_xxx - * Used by migration - * - * @return int <0 if ko, >0 if ok - */ - function update_total() - { - $this->db->begin(); + /** + * Update DB line fields total_xxx + * Used by migration + * + * @return int <0 if ko, >0 if ok + */ + function update_total() + { + $this->db->begin(); - // Mise a jour ligne en base - $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; - $sql.= " total_ht=".price2num($this->total_ht,'MT').""; - $sql.= ",total_tva=".price2num($this->total_tva,'MT').""; - $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; - $sql.= " WHERE rowid = ".$this->rowid; + // Mise a jour ligne en base + $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; + $sql.= " total_ht=".price2num($this->total_ht,'MT').""; + $sql.= ",total_tva=".price2num($this->total_tva,'MT').""; + $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog("PropaleLigne::update_total", LOG_DEBUG); + dol_syslog("PropaleLigne::update_total", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -2; - } - } + $resql=$this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -2; + } + } } diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index 41002eb9e71..bb8e0d880b9 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -124,42 +124,42 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.ref'=>'Ref', - 'p.ref_client'=>'CustomerRef', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'p.note_public'=>'NotePublic', + 'p.ref'=>'Ref', + 'p.ref_client'=>'CustomerRef', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'p.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["p.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'p.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), - 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), - 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), - 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'p.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), + 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), + 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'u.login'=>array('label'=>$langs->trans("Author"), 'checked'=>1, 'position'=>10), + 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'p.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } $object = new Propal($db); // To be passed as parameter of executeHooks that need @@ -181,40 +181,40 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_refcustomer=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_login=''; - $search_product_category=''; - $search_town=''; + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_refcustomer=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_login=''; + $search_product_category=''; + $search_town=''; $search_zip=""; - $search_state=""; + $search_state=""; $search_type=''; $search_country=''; $search_type_thirdparty=''; $search_year=''; - $search_month=''; - $search_day=''; + $search_month=''; + $search_day=''; $viewstatut=''; $object_statut=''; $toselect=''; - $search_array_options=array(); + $search_array_options=array(); } if ($object_statut != '') $viewstatut=$object_statut; if (empty($reshook)) { - $objectclass='Propal'; - $objectlabel='Proposals'; - $permtoread = $user->rights->propal->lire; - $permtodelete = $user->rights->propal->supprimer; - $uploaddir = $conf->propal->dir_output; + $objectclass='Propal'; + $objectlabel='Proposals'; + $permtoread = $user->rights->propal->lire; + $permtodelete = $user->rights->propal->supprimer; + $uploaddir = $conf->propal->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -266,8 +266,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as c"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE p.fk_soc = s.rowid'; $sql.= ' AND p.entity IN ('.getEntity('propal').')'; @@ -288,7 +288,7 @@ if ($search_montant_ht != '') $sql.= natural_search("p.total_ht", $search_monta if ($search_montant_vat != '') $sql.= natural_search("p.tva", $search_montant_vat, 1); if ($search_montant_ttc != '') $sql.= natural_search("p.total", $search_montant_ttc, 1); if ($sall) { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); + $sql .= natural_search(array_keys($fieldstosearchall), $sall); } if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category); if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; @@ -298,12 +298,12 @@ if ($viewstatut != '' && $viewstatut != '-1') } if ($search_month > 0) { - if ($search_year > 0 && empty($search_day)) - $sql.= " AND p.datep 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 p.datep 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(p.datep, '%m') = '".$db->escape($search_month)."'"; + if ($search_year > 0 && empty($search_day)) + $sql.= " AND p.datep 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 p.datep 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(p.datep, '%m') = '".$db->escape($search_month)."'"; } else if ($search_year > 0) { @@ -312,21 +312,21 @@ else if ($search_year > 0) if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); if ($search_user > 0) { - $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); + $sql.= " AND c.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal' AND c.element_id = p.rowid AND c.fk_socpeople = ".$db->escape($search_user); } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -340,8 +340,8 @@ $sql.=', p.ref DESC'; $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -361,7 +361,7 @@ if ($resql) } else { - $title = $langs->trans('ListOfProposals'); + $title = $langs->trans('ListOfProposals'); } $num = $db->num_rows($resql); @@ -369,15 +369,15 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param='&viewstatut='.urlencode($viewstatut); - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); if ($sall) $param.='&sall='.urlencode($sall); if ($search_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_ref) $param.='&search_ref='.urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); - if ($search_societe) $param.='&search_societe='.urlencode($search_societe); + if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); + if ($search_societe) $param.='&search_societe='.urlencode($search_societe); if ($search_user > 0) $param.='&search_user='.urlencode($search_user); if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); if ($search_montant_ht) $param.='&search_montant_ht='.urlencode($search_montant_ht); @@ -390,15 +390,15 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->propal->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); if ($massaction == 'presend') $arrayofmassactions=array(); @@ -406,7 +406,7 @@ if ($resql) // Lignes des champs de filtre print '
      '; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; @@ -419,19 +419,19 @@ if ($resql) if ($massaction == 'presend') { - $topicmail="SendSupplierProposalRef"; - $modelmail="supplier_proposal_send"; - $objecttmp=new Propal($db); - $trackid='ord'.$object->id; + $topicmail="SendSupplierProposalRef"; + $modelmail="supplier_proposal_send"; + $objecttmp=new Propal($db); + $trackid='ord'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } $i = 0; @@ -451,8 +451,8 @@ if ($resql) { $moreforfilter.='
      '; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter.='
      '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.='
      '; } // If the user can view products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) @@ -471,70 +471,70 @@ if ($resql) if (! empty($moreforfilter)) { - print '
      '; - print $moreforfilter; - print '
      '; + print '
      '; + print $moreforfilter; + print '
      '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
      '; + print '
      '; print ''."\n"; print ''; if (! empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.ref_client']['checked'])) { - print ''; } if (! empty($arrayfields['s.nom']['checked'])) { - print ''; } if (! empty($arrayfields['s.town']['checked'])) print ''; if (! empty($arrayfields['s.zip']['checked'])) print ''; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print ''; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + } // Date if (! empty($arrayfields['p.date']['checked'])) { - print ''; + print ''; } // Date end if (! empty($arrayfields['p.fin_validite']['checked'])) @@ -543,54 +543,54 @@ if ($resql) } if (! empty($arrayfields['p.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['p.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['p.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['u.login']['checked'])) { - // Author - print ''; + // Author + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -599,21 +599,21 @@ if ($resql) // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['p.fk_statut']['checked'])) { - print ''; + print ''; } // Action column print ''; if (! empty($arrayfields['p.ref']['checked'])) { - print '\n"; - if (! $i) $totalarray['nbfield']++; + print "\n"; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['p.ref_client']['checked'])) { - // Customer ref - print ''; - if (! $i) $totalarray['nbfield']++; + // Customer ref + print ''; + if (! $i) $totalarray['nbfield']++; } $companystatic->id=$obj->socid; @@ -731,169 +731,169 @@ if ($resql) // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date proposal - if (! empty($arrayfields['p.date']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.date']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } // Date end validity - if (! empty($arrayfields['p.fin_validite']['checked'])) - { - if ($obj->dfv) - { - print ''; - } - else - { - print ''; - } - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.fin_validite']['checked'])) + { + if ($obj->dfv) + { + print ''; + } + else + { + print ''; + } + if (! $i) $totalarray['nbfield']++; + } - // Amount HT - if (! empty($arrayfields['p.total_ht']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['p.total_vat']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount TTC - if (! empty($arrayfields['p.total_ttc']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + // Amount HT + if (! empty($arrayfields['p.total_ht']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['p.total_vat']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount TTC + if (! empty($arrayfields['p.total_ttc']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } - $userstatic->id=$obj->fk_user_author; + $userstatic->id=$obj->fk_user_author; $userstatic->login=$obj->login; - // Author - if (! empty($arrayfields['u.login']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } + // Author + if (! empty($arrayfields['u.login']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -901,7 +901,7 @@ if ($resql) } // Show total line - if (isset($totalarray['totalhtfield']) + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totalttcfield']) || isset($totalarray['totalamfield']) @@ -914,10 +914,10 @@ if ($resql) { $i++; if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } elseif ($totalarray['totalhtfield'] == $i) print ''; elseif ($totalarray['totalvatfield'] == $i) print ''; elseif ($totalarray['totalttcfield'] == $i) print ''; @@ -933,27 +933,27 @@ if ($resql) print $hookmanager->resPrint; print '
      '; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; - print ''; + print ''; + print ''; print ''; - print ''; - print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - //print ' '.$langs->trans('Year').': '; - $formother->select_year($search_year,'search_year',1, 20, 5); - print ''; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $formother->select_year($search_year,'search_year',1, 20, 5); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; } - print ''; - print ''; + print ''; - print ''; + print ''; - $formpropal->selectProposalStatus($viewstatut,1); - print ''; + $formpropal->selectProposalStatus($viewstatut,1); + print ''; @@ -645,19 +645,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -671,55 +671,55 @@ if ($resql) { $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; + $objectstatic->id=$obj->rowid; + $objectstatic->ref=$obj->ref; print '
      '; + print ''; - print ''; - // Picto + Ref - print ''; - // Warning - $warnornote=''; - if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (! empty($obj->note_private)) - { - $warnornote.=($warnornote?' ':''); - $warnornote.= ''; - $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - $warnornote.= ''; - } - if ($warnornote) - { - print ''; - } - // Other picto tool - print '
      '; - print $objectstatic->getNomUrl(1, '', '', 0, 1); - print ''; - print $warnornote; - print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - print '
      '; + print ''; + // Picto + Ref + print ''; + // Warning + $warnornote=''; + if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); + if (! empty($obj->note_private)) + { + $warnornote.=($warnornote?' ':''); + $warnornote.= ''; + $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + $warnornote.= ''; + } + if ($warnornote) + { + print ''; + } + // Other picto tool + print '
      '; + print $objectstatic->getNomUrl(1, '', '', 0, 1); + print ''; + print $warnornote; + print ''; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + print '
      '; - print "
      '; - print $obj->ref_client; - print ''; + print $obj->ref_client; + print ''; - print $companystatic->getNomUrl(1,'customer'); - print ''; + print $companystatic->getNomUrl(1,'customer'); + print ''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; - print dol_print_date($db->jdate($obj->dp), 'day'); - print "'; + print dol_print_date($db->jdate($obj->dp), 'day'); + print "'.dol_print_date($db->jdate($obj->dfv),'day'); - print ' '.dol_print_date($db->jdate($obj->dfv),'day'); + print ' '.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_ttc)."'.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_ttc)."'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print ' '; - print "'; + if ($userstatic->id) print $userstatic->getLoginUrl(1); + else print ' '; + print "'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$objectstatic->LibStatut($obj->fk_statut,5).''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; - } - print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$objectstatic->LibStatut($obj->fk_statut,5).''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
      '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
      '."\n"; - print '
      '."\n"; + print '
      '."\n"; print ''."\n"; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->lire; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->propal->lire; + $delallowed=$user->rights->propal->lire; - print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); + print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } else { - print '
      '.$langs->trans("ShowTempMassFilesArea").''; + print '
      '.$langs->trans("ShowTempMassFilesArea").''; } } diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 7a34d1a3a76..0127b8f15be 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -389,7 +389,7 @@ if ($socid > 0) $facturestatic->id=$obj->fk_facture_source; $facturestatic->ref=$obj->ref; $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); print ''; } else diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 5da8423c0a2..6d7b0c19e3f 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 @@ -1716,7 +1718,7 @@ if ($action == 'create' && $user->rights->commande->creer) print '
      '; print ''; print '     '; - print ''; + print ''; print '
      '; print ''; @@ -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") . ''; } @@ -2479,12 +2481,12 @@ if ($action == 'create' && $user->rights->commande->creer) } // Create contract - if ($conf->contrat->enabled && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_ACCEPTED || $object->statut == Commande::STATUS_CLOSED)) { - $langs->load("contracts"); + if ($conf->contrat->enabled && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)) { + $langs->load("contracts"); - if ($user->rights->contrat->creer) { - print ''; - } + if ($user->rights->contrat->creer) { + print ''; + } } // Ship @@ -2512,7 +2514,7 @@ if ($action == 'create' && $user->rights->commande->creer) } // Set to shipped - if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_ACCEPTED) && $user->rights->commande->cloturer) { + if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS) && $user->rights->commande->cloturer) { print ''; } @@ -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 ''; diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index 11d3fe7260a..1b84876c3af 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -316,7 +316,7 @@ class CommandeApi extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; @@ -389,7 +389,7 @@ class CommandeApi extends DolibarrApi * * @return int */ - function delLine($id, $lineid) { + function deleteLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index d4b4502d4ed..17ff8ae22f1 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -286,7 +286,7 @@ class Orders extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; @@ -353,14 +353,16 @@ class Orders extends DolibarrApi * Delete 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 delete * * @url DELETE {id}/lines/{lineid} * * @return int + * @throws 401 + * @throws 404 */ - function delLine($id, $lineid) { + function deleteLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } @@ -373,7 +375,8 @@ class Orders extends DolibarrApi if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $request_data = (object) $request_data; + + $request_data = (object) $request_data; $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user,$lineid); if ($updateRes > 0) { return $this->get($id); diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index a13e626fe20..79109ff511a 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -169,15 +169,13 @@ class Commande extends CommonOrder */ const STATUS_VALIDATED = 1; /** - * Accepted (supplier orders) - */ - const STATUS_ACCEPTED = 2; - /** - * Shipment on process (customer orders) + * Shipment on process */ const STATUS_SHIPMENTONPROCESS = 2; + const STATUS_ACCEPTED = 2; // For backward compatibility. Use key STATUS_SHIPMENTONPROCESS instead. + /** - * Closed (Sent/Received, billed or not) + * Closed (Sent, billed or not) */ const STATUS_CLOSED = 3; @@ -1242,7 +1240,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'; @@ -1559,10 +1557,10 @@ class Commande extends CommonOrder $sql.= ', ca.code as availability_code, ca.label as availability_label'; $sql.= ', dr.code as demand_reason_code'; $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid)'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON (c.fk_mode_reglement = p.id)'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON (c.fk_availability = ca.rowid)'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON (c.fk_input_reason = ca.rowid)'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN (' . getEntity('c_payment_term') . ')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement') . ')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; $sql.= " WHERE c.entity IN (".getEntity('commande').")"; if ($id) $sql.= " AND c.rowid=".$id; @@ -3225,7 +3223,7 @@ class Commande extends CommonOrder } $sql.= $clause." c.entity IN (".getEntity('commande').")"; //$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0"; - $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_ACCEPTED.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected + $sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_SHIPMENTONPROCESS.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id; $resql=$this->db->query($sql); @@ -3310,7 +3308,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceled'); if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraft'); if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidated').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return $langs->trans('StatusOrderSentShort').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBill'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered'); @@ -3320,7 +3318,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return $langs->trans('StatusOrderCanceledShort'); if ($statut==self::STATUS_DRAFT) return $langs->trans('StatusOrderDraftShort'); if ($statut==self::STATUS_VALIDATED) return $langs->trans('StatusOrderValidatedShort').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return $langs->trans('StatusOrderSentShort').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return $langs->trans('StatusOrderSentShort').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderToBillShort'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return $langs->trans('StatusOrderDelivered'); @@ -3330,7 +3328,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceledShort'); if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort'); @@ -3340,7 +3338,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1'); - if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3'); + if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3'); if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6'); if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6'); @@ -3350,7 +3348,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return img_picto($langs->trans('StatusOrderCanceled'),'statut5').' '.$langs->trans('StatusOrderCanceled'); if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext; - if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext; + if ($statut==self::STATUS_SHIPMENTONPROCESS) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext; if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered'); @@ -3360,7 +3358,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_CANCELED) return ''.$langs->trans('StatusOrderCanceledShort').' '.img_picto($langs->trans('StatusOrderCanceled'),'statut5'); if ($statut==self::STATUS_DRAFT) return ''.$langs->trans('StatusOrderDraftShort').' '.img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($statut==self::STATUS_VALIDATED) return ''.$langs->trans('StatusOrderValidatedShort').$billedtext.' '.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1'); - if ($statut==self::STATUS_ACCEPTED) return ''.$langs->trans('StatusOrderSentShort').$billedtext.' '.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3'); + if ($statut==self::STATUS_SHIPMENTONPROCESS) return ''.$langs->trans('StatusOrderSentShort').$billedtext.' '.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3'); if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderToBillShort').' '.img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderProcessedShort').$billedtext.' '.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6'); if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderDeliveredShort').' '.img_picto($langs->trans('StatusOrderDelivered'),'statut6'); diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 927460c511a..10c1459a087 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -108,42 +108,42 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'c.ref'=>'Ref', - 'c.ref_client'=>'RefCustomerOrder', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'c.note_public'=>'NotePublic', + 'c.ref'=>'Ref', + 'c.ref_client'=>'RefCustomerOrder', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'c.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'c.ref_client'=>array('label'=>$langs->trans("RefCustomerOrder"), 'checked'=>1), - 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), + 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'c.ref_client'=>array('label'=>$langs->trans("RefCustomerOrder"), 'checked'=>1), + 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'c.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), - 'c.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), - 'c.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'c.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'c.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'c.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), - 'c.facture'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'c.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), + 'c.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), + 'c.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'c.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'c.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'c.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'c.facture'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -161,274 +161,272 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // 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'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_ref_customer=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $search_orderyear=''; - $search_ordermonth=''; - $search_orderday=''; - $search_deliveryday=''; - $search_deliverymonth=''; - $search_deliveryyear=''; - $search_project_ref=''; - $viewstatut=''; - $billed=''; - $toselect=''; - $search_array_options=array(); - } - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') - || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) - { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_ref_customer=''; + $search_company=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_total_ht=''; + $search_total_vat=''; + $search_total_ttc=''; + $search_orderyear=''; + $search_ordermonth=''; + $search_orderday=''; + $search_deliveryday=''; + $search_deliverymonth=''; + $search_deliveryyear=''; + $search_project_ref=''; + $viewstatut=''; + $billed=''; + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } - // Mass actions - $objectclass='Commande'; - $objectlabel='Orders'; - $permtoread = $user->rights->commande->lire; - $permtodelete = $user->rights->commande->supprimer; - $uploaddir = $conf->commande->dir_output; - $trigger_name='ORDER_SENTBYMAIL'; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='Commande'; + $objectlabel='Orders'; + $permtoread = $user->rights->commande->lire; + $permtodelete = $user->rights->commande->supprimer; + $uploaddir = $conf->commande->dir_output; + $trigger_name='ORDER_SENTBYMAIL'; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // TODO Move this into mass action include - if ($massaction == 'confirm_createbills') { + if ($massaction == 'confirm_createbills') { - $orders = GETPOST('toselect'); - $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); - $validate_invoices = GETPOST('valdate_invoices', 'int'); + $orders = GETPOST('toselect','array'); + $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); + $validate_invoices = GETPOST('valdate_invoices', 'int'); - $TFact = array(); - $TFactThird = array(); + $TFact = array(); + $TFactThird = array(); - $nb_bills_created = 0; + $nb_bills_created = 0; - $db->begin(); + $db->begin(); - foreach($orders as $id_order) { + foreach($orders as $id_order) + { + $cmd = new Commande($db); + if ($cmd->fetch($id_order) <= 0) continue; - $cmd = new Commande($db); - if($cmd->fetch($id_order) <= 0) continue; + $object = new Facture($db); + if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + else { - $object = new Facture($db); - if(!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. - else { + $object->socid = $cmd->socid; + $object->type = Facture::TYPE_STANDARD; + $object->cond_reglement_id = $cmd->cond_reglement_id; + $object->mode_reglement_id = $cmd->mode_reglement_id; + $object->fk_project = $cmd->fk_project; - $object->socid = $cmd->socid; - $object->type = Facture::TYPE_STANDARD; - $object->cond_reglement_id = $cmd->cond_reglement_id; - $object->mode_reglement_id = $cmd->mode_reglement_id; - $object->fk_project = $cmd->fk_project; + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + if (empty($datefacture)) + { + $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + } - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - if (empty($datefacture)) - { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); - } + $object->date = $datefacture; + $object->origin = 'commande'; + $object->origin_id = $id_order; - $object->date = $datefacture; - $object->origin = 'commande'; - $object->origin_id = $id_order; + $res = $object->create($user); - $res = $object->create($user); + if($res > 0) $nb_bills_created++; + } - if($res > 0) $nb_bills_created++; + if ($object->id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $id_order; + $sql.= ", '".$object->origin."'"; + $sql.= ", ".$object->id; + $sql.= ", '".$object->element."'"; + $sql.= ")"; - } + if (! $db->query($sql)) + { + $error++; + } - if($object->id > 0) { + if (! $error) + { + $lines = $cmd->lines; + if (empty($lines) && method_exists($cmd, 'fetch_lines')) + { + $cmd->fetch_lines(); + $lines = $cmd->lines; + } - $db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $id_order; - $sql.= ", '".$object->origin."'"; - $sql.= ", ".$object->id; - $sql.= ", '".$object->element."'"; - $sql.= ")"; + $fk_parent_line=0; + $num=count($lines); - if ($db->query($sql)) - { - $db->commit(); - } - else - { - $db->rollback(); - } + for ($i=0;$i<$num;$i++) + { + $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + if ($lines[$i]->subprice < 0) + { + // Negative line, we create a discount line + $discount = new DiscountAbsolute($db); + $discount->fk_soc=$object->socid; + $discount->amount_ht=abs($lines[$i]->total_ht); + $discount->amount_tva=abs($lines[$i]->total_tva); + $discount->amount_ttc=abs($lines[$i]->total_ttc); + $discount->tva_tx=$lines[$i]->tva_tx; + $discount->fk_user=$user->id; + $discount->description=$desc; + $discountid=$discount->create($user); + if ($discountid > 0) + { + $result=$object->insert_discount($discountid); + //$result=$discount->link_to_invoice($lineid,$id); + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $error++; + break; + } + } + else + { + // Positive line + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + // Date start + $date_start=false; + if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; + //Date end + $date_end=false; + if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) + { + $fk_parent_line = 0; + } + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $lines[$i]->tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $product_type, + $ii, + $lines[$i]->special_code, + $object->origin, + $lines[$i]->rowid, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $lines[$i]->label + ); + if ($result > 0) + { + $lineid=$result; + } + else + { + $lineid=0; + $error++; + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) + { + $fk_parent_line = $result; + } + } + } + } + } - $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { - $cmd->fetch_lines(); - $lines = $cmd->lines; - } + //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. - $fk_parent_line=0; - $num=count($lines); + if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; + else $TFact[$object->id] = $object; + } - for ($i=0;$i<$num;$i++) - { - $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { - // Negative line, we create a discount line - $discount = new DiscountAbsolute($db); - $discount->fk_soc=$object->socid; - $discount->amount_ht=abs($lines[$i]->total_ht); - $discount->amount_tva=abs($lines[$i]->total_tva); - $discount->amount_ttc=abs($lines[$i]->total_ttc); - $discount->tva_tx=$lines[$i]->tva_tx; - $discount->fk_user=$user->id; - $discount->description=$desc; - $discountid=$discount->create($user); - if ($discountid > 0) - { - $result=$object->insert_discount($discountid); - //$result=$discount->link_to_invoice($lineid,$id); - } - else - { - setEventMessages($discount->error, $discount->errors, 'errors'); - $error++; - break; - } - } - else - { - // Positive line - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); - // Date start - $date_start=false; - if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; - //Date end - $date_end=false; - if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; - // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { - $fk_parent_line = 0; - } - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $lines[$i]->tva_tx, - $lines[$i]->localtax1_tx, - $lines[$i]->localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $date_start, - $date_end, - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_remise_except, - 'HT', - 0, - $product_type, - $ii, - $lines[$i]->special_code, - $object->origin, - $lines[$i]->rowid, - $fk_parent_line, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - $lines[$i]->label - ); - if ($result > 0) - { - $lineid=$result; - } - else - { - $lineid=0; - $error++; - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { - $fk_parent_line = $result; - } - } - } + // Build doc with all invoices + $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; + $toselect = array(); - } + if (! $error && $validate_invoices) + { + $massaction = $action = 'builddoc'; + foreach($TAllFact as &$object) + { + $result = $object->validate($user); + if ($result <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + break; + } - //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. + $id = $object->id; // For builddoc action - if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; - else $TFact[$object->id] = $object; - } + // Fac builddoc + $donotredirect = 1; + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + } - // Build doc with all invoices - $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; - $toselect = array(); + $massaction = $action = 'confirm_createbills'; + } - if(!empty($validate_invoices)) { - - $massaction = $action = 'builddoc'; - - foreach($TAllFact as &$object) { - $object->validate($user); - $toselect[] = $object->id; // For builddoc action - - // Fac builddoc - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - } - - $objectclass='Facture'; - $objectlabel='Invoice'; - $permtoread = $user->rights->facture->lire; - $permtodelete = $user->rights->facture->supprimer; - $uploaddir = $conf->facture->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - - } - - if (! $error) - { - $db->commit(); - setEventMessage($langs->trans('BillCreated', $nb_bills_created)); - } - else - { - $db->rollback(); - $action='create'; - $_GET["origin"]=$_POST["origin"]; - $_GET["originid"]=$_POST["originid"]; - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } + if (! $error) + { + $db->commit(); + setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + } + else + { + $db->rollback(); + $action='create'; + $_GET["origin"]=$_POST["origin"]; + $_GET["originid"]=$_POST["originid"]; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } } @@ -477,8 +475,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE c.fk_soc = s.rowid'; $sql.= ' AND c.entity IN ('.getEntity('commande').')'; @@ -514,29 +512,29 @@ if ($viewstatut <> '') } if ($search_ordermonth > 0) { - if ($search_orderyear > 0 && empty($search_orderday)) - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,$search_ordermonth,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,$search_ordermonth,false))."'"; - else if ($search_orderyear > 0 && ! empty($search_orderday)) - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_ordermonth, $search_orderday, $search_orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_ordermonth, $search_orderday, $search_orderyear))."'"; - else - $sql.= " AND date_format(c.date_commande, '%m') = '".$search_ordermonth."'"; + if ($search_orderyear > 0 && empty($search_orderday)) + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,$search_ordermonth,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,$search_ordermonth,false))."'"; + else if ($search_orderyear > 0 && ! empty($search_orderday)) + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_ordermonth, $search_orderday, $search_orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_ordermonth, $search_orderday, $search_orderyear))."'"; + else + $sql.= " AND date_format(c.date_commande, '%m') = '".$search_ordermonth."'"; } else if ($search_orderyear > 0) { - $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,12,false))."'"; + $sql.= " AND c.date_commande BETWEEN '".$db->idate(dol_get_first_day($search_orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_orderyear,12,false))."'"; } if ($search_deliverymonth > 0) { - if ($search_deliveryyear > 0 && empty($search_deliveryday)) - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,$search_deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,$search_deliverymonth,false))."'"; - else if ($search_deliveryyear > 0 && ! empty($search_deliveryday)) - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."'"; - else - $sql.= " AND date_format(c.date_livraison, '%m') = '".$search_deliverymonth."'"; + if ($search_deliveryyear > 0 && empty($search_deliveryday)) + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,$search_deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,$search_deliverymonth,false))."'"; + else if ($search_deliveryyear > 0 && ! empty($search_deliveryday)) + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_deliverymonth, $search_deliveryday, $search_deliveryyear))."'"; + else + $sql.= " AND date_format(c.date_livraison, '%m') = '".$search_deliverymonth."'"; } else if ($search_deliveryyear > 0) { - $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,12,false))."'"; + $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($search_deliveryyear,12,false))."'"; } if ($search_town) $sql.= natural_search('s.town', $search_town); if ($search_zip) $sql.= natural_search("s.zip",$search_zip); @@ -551,16 +549,16 @@ if ($search_project_ref != '') $sql.= natural_search("p.ref",$search_project_ref // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -616,7 +614,7 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.='&sall='.$sall; if ($socid > 0) $param.='&socid='.$socid; @@ -637,20 +635,20 @@ if ($resql) if ($search_total_ttc != '') $param.='&search_total_ttc='.$search_total_ttc; if ($search_project_ref >= 0) $param.="&search_project_ref=".$search_project_ref; if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($optioncss != '') $param.='&optioncss='.$optioncss; if ($billed != '') $param.='&billed='.$billed; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->commande->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); @@ -659,13 +657,13 @@ if ($resql) // Lines of title fields print '
      '; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -710,12 +708,12 @@ if ($resql) print ''; if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) { - print $form->selectyesno('valdate_invoices', 0, 1, 1); - print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; + print $form->selectyesno('valdate_invoices', 0, 1, 1); + print ' ('.$langs->trans("AutoValidationNotPossibleWhenStockIsDecreasedOnInvoiceValidation").')'; } else { - print $form->selectyesno('valdate_invoices', 0, 1); + print $form->selectyesno('valdate_invoices', 0, 1); } print ''; print ''; @@ -730,10 +728,10 @@ if ($resql) } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } $moreforfilter=''; @@ -751,7 +749,7 @@ if ($resql) { $moreforfilter.='
      '; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
      '; } // If the user can view prospects other than his' @@ -773,30 +771,30 @@ if ($resql) { print '
      '; print $moreforfilter; - print '
      '; + print '
      '; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
      '; - print ''."\n"; + print '
      '; + print '
      '."\n"; print ''; // Ref if (! empty($arrayfields['c.ref']['checked'])) { - print ''; + print ''; } // Ref customer if (! empty($arrayfields['c.ref_client']['checked'])) { - print ''; + print ''; } // Project ref if (! empty($arrayfields['p.project_ref']['checked'])) @@ -806,9 +804,9 @@ if ($resql) // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } // Town if (! empty($arrayfields['s.town']['checked'])) print ''; @@ -817,84 +815,84 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print ''; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + print ''; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + print ''; } // Date order if (! empty($arrayfields['c.date_commande']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['c.date_delivery']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['c.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['c.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['c.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -903,36 +901,36 @@ if ($resql) // Date creation if (! empty($arrayfields['c.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['c.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['c.fk_statut']['checked'])) { - print ''; + print ''; } // Status billed if (! empty($arrayfields['c.facture']['checked'])) { - print ''; + print ''; } // Action column print ''; - print "\n"; + print "\n"; // Fields title print ''; @@ -963,19 +961,19 @@ if ($resql) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.date_creation","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.fk_statut']['checked'])) print_liste_field_titre($arrayfields['c.fk_statut']['label'],$_SERVER["PHP_SELF"],"c.fk_statut","",$param,'align="right"',$sortfield,$sortorder); @@ -985,188 +983,188 @@ if ($resql) $total=0; $subtotal=0; - $productstat_cache=array(); + $productstat_cache=array(); - $generic_commande = new Commande($db); - $generic_product = new Product($db); + $generic_commande = new Commande($db); + $generic_product = new Product($db); - $i=0; + $i=0; $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - $notshippable=0; - $warning = 0; - $text_info=''; - $text_warning=''; - $nbprod=0; + $notshippable=0; + $warning = 0; + $text_info=''; + $text_warning=''; + $nbprod=0; - $companystatic->id=$obj->socid; - $companystatic->code_client = $obj->code_client; - $companystatic->name=$obj->name; - $companystatic->client=$obj->client; - $companystatic->email=$obj->email; + $companystatic->id=$obj->socid; + $companystatic->code_client = $obj->code_client; + $companystatic->name=$obj->name; + $companystatic->client=$obj->client; + $companystatic->email=$obj->email; - $generic_commande->id=$obj->rowid; - $generic_commande->ref=$obj->ref; - $generic_commande->statut = $obj->fk_statut; - $generic_commande->date_commande = $db->jdate($obj->date_commande); - $generic_commande->date_livraison = $db->jdate($obj->date_delivery); - $generic_commande->ref_client = $obj->ref_client; - $generic_commande->total_ht = $obj->total_ht; - $generic_commande->total_tva = $obj->total_tva; - $generic_commande->total_ttc = $obj->total_ttc; + $generic_commande->id=$obj->rowid; + $generic_commande->ref=$obj->ref; + $generic_commande->statut = $obj->fk_statut; + $generic_commande->date_commande = $db->jdate($obj->date_commande); + $generic_commande->date_livraison = $db->jdate($obj->date_delivery); + $generic_commande->ref_client = $obj->ref_client; + $generic_commande->total_ht = $obj->total_ht; + $generic_commande->total_tva = $obj->total_tva; + $generic_commande->total_ttc = $obj->total_ttc; - print ''; + print ''; - // Ref - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; + print '
      '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; - print ''; + print ''; - print ''; + print ''; - $liststatus=array( - Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), - Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), - Commande::STATUS_ACCEPTED=>$langs->trans("StatusOrderSentShort"), - Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), - -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"), - Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") - ); - print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); - print ''; + $liststatus=array( + Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), + Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), + Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSentShort"), + Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), + -3=>$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"), + Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") + ); + print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); + print ''; - print $form->selectyesno('billed', $billed, 1, 0, 1); - print ''; + print $form->selectyesno('billed', $billed, 1, 0, 1); + print ''; @@ -940,7 +938,7 @@ if ($resql) print $searchpicto; print '
      '; + // Ref + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; - $generic_commande->lines=array(); - $generic_commande->getLinesArray(); + $generic_commande->lines=array(); + $generic_commande->getLinesArray(); - print ''; - print ''; + print '
      '; - print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); - print '
      '; + print ''; - // Show shippable Icon (create subloop, so may be slow) - if ($conf->stock->enabled) - { - $langs->load("stocks"); - if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) - { - $numlines = count($generic_commande->lines); // Loop on each line of order - for ($lig=0; $lig < $numlines; $lig++) - { - if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service - { - $nbprod++; // order contains real products - $generic_product->id = $generic_commande->lines[$lig]->fk_product; + // Show shippable Icon (create subloop, so may be slow) + if ($conf->stock->enabled) + { + $langs->load("stocks"); + if (($obj->fk_statut > 0) && ($obj->fk_statut < 3)) + { + $numlines = count($generic_commande->lines); // Loop on each line of order + for ($lig=0; $lig < $numlines; $lig++) + { + if ($generic_commande->lines[$lig]->product_type == 0 && $generic_commande->lines[$lig]->fk_product > 0) // If line is a product and not a service + { + $nbprod++; // order contains real products + $generic_product->id = $generic_commande->lines[$lig]->fk_product; - // Get local and virtual stock and store it into cache - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) { - $generic_product->load_stock('nobatch'); - //$generic_product->load_virtual_stock(); Already included into load_stock - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel; - $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; - } else { - $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel']; - $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; - } + // Get local and virtual stock and store it into cache + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product])) { + $generic_product->load_stock('nobatch'); + //$generic_product->load_virtual_stock(); Already included into load_stock + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_reel; + $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; + } else { + $generic_product->stock_reel = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stock_reel']; + $generic_product->stock_theorique = $productstat_cachevirtual[$generic_commande->lines[$lig]->fk_product]['stock_reel'] = $generic_product->stock_theorique; + } - if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result - { - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); - $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel; - $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique; - $text_info .= '
      '; + if (empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) // Default code. Default is when this option is not set, setting it create strange result + { + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_info .= ' - '.$langs->trans("Stock").': '.$generic_product->stock_reel; + $text_info .= ' - '.$langs->trans("VirtualStock").': '.$generic_product->stock_theorique; + $text_info .= '
      '; - if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) - { - $notshippable++; - } - } - else { // Detailed code, looks bugged - // stock order and stock order_supplier - $stock_order=0; - $stock_order_supplier=0; - if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? - { - if (! empty($conf->commande->enabled)) - { - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { - $generic_product->load_stats_commande(0,'1,2'); - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty']; - } else { - $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; - } - $stock_order=$generic_product->stats_commande['qty']; - } - if (! empty($conf->fournisseur->enabled)) - { - if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { - $generic_product->load_stats_commande_fournisseur(0,'3'); - $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty']; - } else { - $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; - } - $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; - } - } - $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); - $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; - if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { - $warning++; - $text_warning.=''.$langs->trans('Available').' : '.$text_stock_reel.''; - } - if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { - $notshippable++; - $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; - } else { - $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; - } - if (! empty($conf->fournisseur->enabled)) { - $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
      '; - } else { - $text_info.= '
      '; - } - } - } - } - if ($notshippable==0) { - $text_icon = img_picto('', 'object_sending'); - $text_info = $langs->trans('Shippable').'
      '.$text_info; - } else { - $text_icon = img_picto('', 'error'); - $text_info = $langs->trans('NonShippable').'
      '.$text_info; - } - } + if ($generic_commande->lines[$lig]->qty > $generic_product->stock_reel) + { + $notshippable++; + } + } + else { // Detailed code, looks bugged + // stock order and stock order_supplier + $stock_order=0; + $stock_order_supplier=0; + if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) // What about other options ? + { + if (! empty($conf->commande->enabled)) + { + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'])) { + $generic_product->load_stats_commande(0,'1,2'); + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer'] = $generic_product->stats_commande['qty']; + } else { + $generic_product->stats_commande['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_customer']; + } + $stock_order=$generic_product->stats_commande['qty']; + } + if (! empty($conf->fournisseur->enabled)) + { + if (empty($productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'])) { + $generic_product->load_stats_commande_fournisseur(0,'3'); + $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier'] = $generic_product->stats_commande_fournisseur['qty']; + } else { + $generic_product->stats_commande_fournisseur['qty'] = $productstat_cache[$generic_commande->lines[$lig]->fk_product]['stats_order_supplier']; + } + $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; + } + } + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; + if ($stock_order > $generic_product->stock_reel && ! ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty)) { + $warning++; + $text_warning.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } + if ($generic_product->stock_reel < $generic_commande->lines[$lig]->qty) { + $notshippable++; + $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } else { + $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } + if (! empty($conf->fournisseur->enabled)) { + $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
      '; + } else { + $text_info.= '
      '; + } + } + } + } + if ($notshippable==0) { + $text_icon = img_picto('', 'object_sending'); + $text_info = $langs->trans('Shippable').'
      '.$text_info; + } else { + $text_icon = img_picto('', 'error'); + $text_info = $langs->trans('NonShippable').'
      '.$text_info; + } + } - print ''; - } + print ''; + } - // Warning late icon and note - print ''; + // Warning late icon and note + print ''; - print ''; - print '
      '; + print $generic_commande->getNomUrl(1, ($viewstatut != 2?0:$obj->fk_statut), 0, 0, 0, 1); + print ''; - if ($nbprod) - { - print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); - } - if ($warning) { // Always false in default mode - print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'
      '.$text_warning, 2, 1, img_picto('', 'error'),'',2); - } - print '
      '; + if ($nbprod) + { + print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); + } + if ($warning) { // Always false in default mode + print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'
      '.$text_warning, 2, 1, img_picto('', 'error'),'',2); + } + print '
      '; - if ($generic_commande->hasDelay()) { - print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning"); - } - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' '; - print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - print ''; - } - print ''; + if ($generic_commande->hasDelay()) { + print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning"); + } + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' '; + print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + print ''; + } + print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); - print '
      '; + print '
      '; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); + print '
      '; - print ''; - if (! $i) $totalarray['nbfield']++; - } + print ''; + if (! $i) $totalarray['nbfield']++; + } // Ref customer if (! empty($arrayfields['c.ref_client']['checked'])) { - print ''.$obj->ref_client.''; - if (! $i) $totalarray['nbfield']++; + print ''.$obj->ref_client.''; + if (! $i) $totalarray['nbfield']++; } // Project @@ -1183,167 +1181,167 @@ if ($resql) // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print ''; - print $companystatic->getNomUrl(1,'customer'); + print ''; + print $companystatic->getNomUrl(1,'customer'); - // If module invoices enabled and user with invoice creation permissions - if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) - { - if ($user->rights->facture->creer) - { - if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) - { - print ' '; - print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; - } - } - } - print ''; - if (! $i) $totalarray['nbfield']++; + // If module invoices enabled and user with invoice creation permissions + if (! empty($conf->facture->enabled) && ! empty($conf->global->ORDER_BILLING_ALL_CUSTOMER)) + { + if ($user->rights->facture->creer) + { + if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) + { + print ' '; + print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; + } + } + } + print ''; + if (! $i) $totalarray['nbfield']++; } // Town if (! empty($arrayfields['s.town']['checked'])) { - print ''; - print $obj->town; - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + print $obj->town; + print ''; + if (! $i) $totalarray['nbfield']++; } // Zip if (! empty($arrayfields['s.zip']['checked'])) { - print ''; - print $obj->zip; - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + print $obj->zip; + print ''; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print "".$obj->state_name."\n"; - if (! $i) $totalarray['nbfield']++; + print "".$obj->state_name."\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (! $i) $totalarray['nbfield']++; } // Type ent if (! empty($arrayfields['typent.code']['checked'])) { - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; + if (! $i) $totalarray['nbfield']++; } // Order date if (! empty($arrayfields['c.date_commande']['checked'])) { - print ''; - print dol_print_date($db->jdate($obj->date_commande), 'day'); - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + print dol_print_date($db->jdate($obj->date_commande), 'day'); + print ''; + if (! $i) $totalarray['nbfield']++; } // Plannned date of delivery if (! empty($arrayfields['c.date_delivery']['checked'])) { - print ''; - print dol_print_date($db->jdate($obj->date_delivery), 'day'); - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + print dol_print_date($db->jdate($obj->date_delivery), 'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Amount HT + if (! empty($arrayfields['c.total_ht']['checked'])) + { + print ''.price($obj->total_ht)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['c.total_vat']['checked'])) + { + print ''.price($obj->total_tva)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_tva; + } + // Amount TTC + if (! empty($arrayfields['c.total_ttc']['checked'])) + { + print ''.price($obj->total_ttc)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; } - // Amount HT - if (! empty($arrayfields['c.total_ht']['checked'])) - { - print ''.price($obj->total_ht)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['c.total_vat']['checked'])) - { - print ''.price($obj->total_tva)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_tva; - } - // Amount TTC - if (! empty($arrayfields['c.total_ttc']['checked'])) - { - print ''.price($obj->total_ttc)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['c.fk_statut']['checked'])) - { - print ''.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).''; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['c.fk_statut']['checked'])) + { + print ''.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).''; + if (! $i) $totalarray['nbfield']++; + } // Billed - if (! empty($arrayfields['c.facture']['checked'])) - { - print ''.yn($obj->billed).''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['c.facture']['checked'])) + { + print ''.yn($obj->billed).''; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; - } - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -1353,29 +1351,29 @@ if ($resql) } // Show total line - if (isset($totalarray['totalhtfield']) + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totalttcfield']) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; - else print ''.$langs->trans("Totalforthispage").''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; - elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; - elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; - else print ''; - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; + else print ''.$langs->trans("Totalforthispage").''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; + elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; + elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; + else print ''; + } + print ''; } $db->free($resql); @@ -1391,21 +1389,21 @@ if ($resql) if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->supprimer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->commande->lire; + $delallowed=$user->rights->commande->supprimer; - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - print '
      '.$langs->trans("ShowTempMassFilesArea").''; + print '
      '.$langs->trans("ShowTempMassFilesArea").''; } } diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index 6a8b57e3707..b1baf7332a1 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -280,7 +280,7 @@ if ($mode == 'customer') $liststatus=array( Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraft"), Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), - Commande::STATUS_ACCEPTED=>$langs->trans("StatusOrderSent"), + Commande::STATUS_SHIPMENTONPROCESS=>$langs->trans("StatusOrderSent"), Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceled") ); diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index eb14db2d3ac..44badfa51d8 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -149,7 +149,7 @@ dol_fiche_head($head, 'annual', $langs->trans("FinancialAccount"), -1, 'account' $title=$langs->trans("FinancialAccount")." : ".$object->label; $link=($year_start?"".img_previous('', 'class="valignbottom"')." ".$langs->trans("Year")." ".img_next('', 'class="valignbottom"')."":""); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; if (!empty($id)) @@ -203,7 +203,7 @@ print ''; $var=true; for ($mois = 1 ; $mois < 13 ; $mois++) { - + print ''; print "".dol_print_date(dol_mktime(1,1,1,$mois,1,2000),"%B").""; for ($annee = $year_start ; $annee <= $year_end ; $annee++) diff --git a/htdocs/compta/bank/bankentries.php b/htdocs/compta/bank/bankentries_list.php similarity index 95% rename from htdocs/compta/bank/bankentries.php rename to htdocs/compta/bank/bankentries_list.php index 8cb5b878dc0..a829cdc8cba 100644 --- a/htdocs/compta/bank/bankentries.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -23,7 +23,7 @@ */ /** - * \file htdocs/compta/bank/bankentries.php + * \file htdocs/compta/bank/bankentries_list.php * \ingroup banque * \brief List of bank transactions */ @@ -100,10 +100,10 @@ $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder='ASC'; -if (! $sortfield) $sortfield='b.datev, b.dateo, b.rowid'; +if (! $sortfield) $sortfield='b.datev,b.dateo,b.rowid'; $mode_balance_ok=false; -//if (($sortfield == 'b.datev' || $sortfield == 'b.datev, b.dateo, b.rowid')) // TODO Manage balance when account not selected +//if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) // TODO Manage balance when account not selected if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) { $sortfield = 'b.datev,b.dateo,b.rowid'; @@ -151,7 +151,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); } } @@ -367,7 +367,7 @@ if (!empty($debit)) $param.='&debit='.$debit; if (!empty($credit)) $param.='&credit='.$credit; if (!empty($account)) $param.='&account='.$account; if (!empty($search_num_releve)) $param.='&search_num_releve='.urlencode($search_num_releve); -if ($search_conciliated != '') $param.='&search_conciliated='.urlencode($search_conciliated); +if ($search_conciliated != '' && $search_conciliated != '-1') $param.='&search_conciliated='.urlencode($search_conciliated); if (!empty($bid)) $param.='&bid='.$bid; if (dol_strlen($search_dt_start) > 0) $param .= '&search_start_dtmonth=' . GETPOST('search_start_dtmonth', 'int') . '&search_start_dtday=' . GETPOST('search_start_dtday', 'int') . '&search_start_dtyear=' . GETPOST('search_start_dtyear', 'int'); if (dol_strlen($search_dt_end) > 0) $param .= '&search_end_dtmonth=' . GETPOST('search_end_dtmonth', 'int') . '&search_end_dtday=' . GETPOST('search_end_dtday', 'int') . '&search_end_dtyear=' . GETPOST('search_end_dtyear', 'int'); @@ -405,7 +405,7 @@ if ($id > 0 || ! empty($ref)) $head=bank_prepare_head($object); dol_fiche_head($head,'journal',$langs->trans("FinancialAccount"),0,'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); @@ -447,7 +447,7 @@ if ($id > 0 || ! empty($ref)) if ($object->canBeConciliated() > 0) { // If not cash account and can be reconciliate if ($user->rights->banque->consolidate) { - print ''.$langs->trans("Conciliate").''; + print ''.$langs->trans("Conciliate").''; } else { print ''.$langs->trans("Conciliate").''; } @@ -559,7 +559,7 @@ if (! empty($thirdparty)) $mode_balance_ok=false; $sql.= $db->plimit($limit+1,$offset); -dol_syslog('compta/bank/bankentries.php', LOG_DEBUG); +dol_syslog('compta/bank/bankentries_list.php', LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -963,6 +963,55 @@ if ($resql) else dol_print_error($db); $balancecalculated=true; + + // Output a line with start balance + if ($user->rights->banque->consolidate && $action == 'reconcile') + { + $tmpnbfieldbeforebalance=0; + $tmpnbfieldafterbalance=0; + $balancefieldfound=false; + foreach($arrayfields as $key => $val) + { + if ($key == 'balance') + { + $balancefieldfound=true; + continue; + } + if (! empty($arrayfields[$key]['checked'])) + { + if (! $balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + if (! empty($arrayfields[$key]['checked'])) + { + if (! $balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + } + } + + print ''; + if ($tmpnbfieldbeforebalance) + { + print ''; + print ''; + } + print ''; + print price(price2num($balance, 'MT'), 1, $langs); + print ''; + print ''; + print ''; + print ''; + } } $balance = price2num($balance + ($sign * $objp->amount),'MT'); @@ -1065,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; @@ -1082,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); @@ -1161,7 +1210,7 @@ if ($resql) if (! empty($arrayfields['type']['checked'])) { print ''; - $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle'); + $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle','',1); if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); else print $labeltype; print "\n"; diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php index 699edd31b7a..15aae28c1d1 100644 --- a/htdocs/compta/bank/budget.php +++ b/htdocs/compta/bank/budget.php @@ -74,9 +74,9 @@ if ($result) while ($i < $num) { $objp = $db->fetch_object($result); - + print ''; - print "rowid\">$objp->label"; + print "rowid\">$objp->label"; print ''.$objp->nombre.''; print ''.price(abs($objp->somme)).""; print ''.price(abs(price2num($objp->somme / $objp->nombre,'MT'))).""; diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index b32d4ea938e..0fc7657f184 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -72,204 +72,204 @@ if ($cancel) $action=''; if ($action == 'add') { - $error=0; + $error=0; - $db->begin(); + $db->begin(); - // Create account - $object = new Account($db); + // Create account + $object = new Account($db); - $object->ref = dol_sanitizeFileName(trim($_POST["ref"])); - $object->label = trim($_POST["label"]); - $object->courant = $_POST["type"]; - $object->clos = $_POST["clos"]; - $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; - $object->url = $_POST["url"]; + $object->ref = dol_sanitizeFileName(trim($_POST["ref"])); + $object->label = trim($_POST["label"]); + $object->courant = $_POST["type"]; + $object->clos = $_POST["clos"]; + $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; + $object->url = $_POST["url"]; $object->bank = trim($_POST["bank"]); - $object->code_banque = trim($_POST["code_banque"]); - $object->code_guichet = trim($_POST["code_guichet"]); - $object->number = trim($_POST["number"]); - $object->cle_rib = trim($_POST["cle_rib"]); - $object->bic = trim($_POST["bic"]); - $object->iban = trim($_POST["iban"]); - $object->domiciliation = trim($_POST["domiciliation"]); + $object->code_banque = trim($_POST["code_banque"]); + $object->code_guichet = trim($_POST["code_guichet"]); + $object->number = trim($_POST["number"]); + $object->cle_rib = trim($_POST["cle_rib"]); + $object->bic = trim($_POST["bic"]); + $object->iban = trim($_POST["iban"]); + $object->domiciliation = trim($_POST["domiciliation"]); - $object->proprio = trim($_POST["proprio"]); - $object->owner_address = trim($_POST["owner_address"]); + $object->proprio = trim($_POST["proprio"]); + $object->owner_address = trim($_POST["owner_address"]); $account_number = GETPOST('account_number','alpha'); if ($account_number <= 0) { $object->account_number = ''; } else { $object->account_number = $account_number; } $fk_accountancy_journal = GETPOST('fk_accountancy_journal','int'); if ($fk_accountancy_journal <= 0) { $object->fk_accountancy_journal = ''; } else { $object->fk_accountancy_journal = $fk_accountancy_journal; } - $object->solde = $_POST["solde"]; - $object->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); + $object->solde = $_POST["solde"]; + $object->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); - $object->currency_code = trim($_POST["account_currency_code"]); + $object->currency_code = trim($_POST["account_currency_code"]); - $object->state_id = $_POST["account_state_id"]; - $object->country_id = $_POST["account_country_id"]; + $object->state_id = $_POST["account_state_id"]; + $object->country_id = $_POST["account_country_id"]; - $object->min_allowed = GETPOST("account_min_allowed",'int'); - $object->min_desired = GETPOST("account_min_desired",'int'); - $object->comment = trim(GETPOST("account_comment")); + $object->min_allowed = GETPOST("account_min_allowed",'int'); + $object->min_desired = GETPOST("account_min_desired",'int'); + $object->comment = trim(GETPOST("account_comment")); - $object->fk_user_author = $user->id; + $object->fk_user_author = $user->id; - if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors'); - $action='create'; // Force chargement page en mode creation - $error++; - } - if (empty($object->ref)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); - $action='create'; // Force chargement page en mode creation - $error++; - } - if (empty($object->label)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); - $action='create'; // Force chargement page en mode creation - $error++; - } + if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors'); + $action='create'; // Force chargement page en mode creation + $error++; + } + if (empty($object->ref)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); + $action='create'; // Force chargement page en mode creation + $error++; + } + if (empty($object->label)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); + $action='create'; // Force chargement page en mode creation + $error++; + } - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if (! $error) - { - $id = $object->create($user); - if ($id > 0) - { - // Category association - $categories = GETPOST('categories', 'array'); - $object->setCategories($categories); + if (! $error) + { + $id = $object->create($user); + if ($id > 0) + { + // Category association + $categories = GETPOST('categories', 'array'); + $object->setCategories($categories); - $_GET["id"]=$id; // Force chargement page en mode visu + $_GET["id"]=$id; // Force chargement page en mode visu - $action=''; - } - else { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); + $action=''; + } + else { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); - $action='create'; // Force chargement page en mode creation - } - } + $action='create'; // Force chargement page en mode creation + } + } - if (! $error) - { - $db->commit(); - } - else - { - $db->rollback(); - } + if (! $error) + { + $db->commit(); + } + else + { + $db->rollback(); + } } if ($action == 'update') { - $error=0; + $error=0; - // Update account - $object = new Account($db); - $object->fetch(GETPOST("id")); + // Update account + $object = new Account($db); + $object->fetch(GETPOST("id")); - $object->ref = dol_string_nospecial(trim($_POST["ref"])); - $object->label = trim($_POST["label"]); - $object->courant = $_POST["type"]; - $object->clos = $_POST["clos"]; - $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; - $object->url = trim($_POST["url"]); + $object->ref = dol_string_nospecial(trim($_POST["ref"])); + $object->label = trim($_POST["label"]); + $object->courant = $_POST["type"]; + $object->clos = $_POST["clos"]; + $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; + $object->url = trim($_POST["url"]); - $object->bank = trim($_POST["bank"]); - $object->code_banque = trim($_POST["code_banque"]); - $object->code_guichet = trim($_POST["code_guichet"]); - $object->number = trim($_POST["number"]); - $object->cle_rib = trim($_POST["cle_rib"]); - $object->bic = trim($_POST["bic"]); - $object->iban = trim($_POST["iban"]); - $object->domiciliation = trim($_POST["domiciliation"]); + $object->bank = trim($_POST["bank"]); + $object->code_banque = trim($_POST["code_banque"]); + $object->code_guichet = trim($_POST["code_guichet"]); + $object->number = trim($_POST["number"]); + $object->cle_rib = trim($_POST["cle_rib"]); + $object->bic = trim($_POST["bic"]); + $object->iban = trim($_POST["iban"]); + $object->domiciliation = trim($_POST["domiciliation"]); - $object->proprio = trim($_POST["proprio"]); - $object->owner_address = trim($_POST["owner_address"]); + $object->proprio = trim($_POST["proprio"]); + $object->owner_address = trim($_POST["owner_address"]); $account_number = GETPOST('account_number', 'int'); if ($account_number <= 0) { $object->account_number = ''; } else { $object->account_number = $account_number; } $fk_accountancy_journal = GETPOST('fk_accountancy_journal','int'); if ($fk_accountancy_journal <= 0) { $object->fk_accountancy_journal = ''; } else { $object->fk_accountancy_journal = $fk_accountancy_journal; } - $object->currency_code = trim($_POST["account_currency_code"]); + $object->currency_code = trim($_POST["account_currency_code"]); - $object->state_id = $_POST["account_state_id"]; - $object->country_id = $_POST["account_country_id"]; + $object->state_id = $_POST["account_state_id"]; + $object->country_id = $_POST["account_country_id"]; - $object->min_allowed = GETPOST("account_min_allowed",'int'); - $object->min_desired = GETPOST("account_min_desired",'int'); - $object->comment = trim(GETPOST("account_comment")); + $object->min_allowed = GETPOST("account_min_allowed",'int'); + $object->min_desired = GETPOST("account_min_desired",'int'); + $object->comment = trim(GETPOST("account_comment")); - if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'error'); - $action='edit'; // Force chargement page en mode creation - $error++; - } - if (empty($object->ref)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation - $error++; - } - if (empty($object->label)) - { - setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); - $action='edit'; // Force chargement page en mode creation - $error++; - } + if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'error'); + $action='edit'; // Force chargement page en mode creation + $error++; + } + if (empty($object->ref)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); + $action='edit'; // Force chargement page en mode creation + $error++; + } + if (empty($object->label)) + { + setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); + $action='edit'; // Force chargement page en mode creation + $error++; + } - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - if (! $error) - { - $result = $object->update($user); - if ($result >= 0) - { - // Category association - $categories = GETPOST('categories', 'array'); - $object->setCategories($categories); + if (! $error) + { + $result = $object->update($user); + if ($result >= 0) + { + // Category association + $categories = GETPOST('categories', 'array'); + $object->setCategories($categories); - $_GET["id"]=$_POST["id"]; // Force chargement page en mode visu - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $action='edit'; // Force chargement page edition - } - } + $_GET["id"]=$_POST["id"]; // Force chargement page en mode visu + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $action='edit'; // Force chargement page edition + } + } } if ($action == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights->banque->configurer) { - // Delete - $object = new Account($db); - $object->fetch(GETPOST("id","int")); - $result = $object->delete($user); + // Delete + $object = new Account($db); + $object->fetch(GETPOST("id","int")); + $result = $object->delete($user); - if ($result > 0) - { - setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); - header("Location: ".DOL_URL_ROOT."/compta/bank/index.php"); - exit; - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - $action=''; - } + if ($result > 0) + { + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); + header("Location: ".DOL_URL_ROOT."/compta/bank/list.php"); + exit; + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + $action=''; + } } @@ -297,10 +297,10 @@ if ($action == 'create') print load_fiche_titre($langs->trans("NewFinancialAccount"), '', 'title_bank.png'); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) + { print "\n".''."\n"; - } + print ''."\n"; + } print ''; print ''; @@ -324,11 +324,11 @@ if ($action == 'create') // Ref print ''.$langs->trans("Ref").''; - print 'ref).'" maxlength="12">'; + print 'ref).'" maxlength="12" autofocus>'; // Label print ''.$langs->trans("LabelBankCashAccount").''; - print ''; + print ''; // Type print ''.$langs->trans("AccountType").''; @@ -347,12 +347,12 @@ if ($action == 'create') print ''; // Status - print ''.$langs->trans("Status").''; - print ''; - print $form->selectarray("clos", $object->status,(isset($_POST["clos"])?$_POST["clos"]:$object->clos)); - print ''; + print ''.$langs->trans("Status").''; + print ''; + print $form->selectarray("clos", $object->status,(GETPOST("clos",'int')!=''?GETPOST("clos",'int'):$object->clos)); + print ''; - // Country + // Country $selectedcode=''; if (isset($_POST["account_country_id"])) { @@ -383,24 +383,24 @@ if ($action == 'create') print ''.$langs->trans("Web").''; print ''; - // Tags-Categories - if ($conf->categorie->enabled) - { - print ''.$langs->trans("Categories").''; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); - $c = new Categorie($db); - $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); - foreach($cats as $cat) { - $arrayselected[] = $cat->id; - } - print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); - print ""; - } + // Tags-Categories + if ($conf->categorie->enabled) + { + print ''.$langs->trans("Categories").''; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); + $c = new Categorie($db); + $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); + foreach($cats as $cat) { + $arrayselected[] = $cat->id; + } + print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); + print ""; + } // Comment print ''.$langs->trans("Comment").''; print ''; - // Editor wysiwyg + // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$object->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_4,'90%'); $doleditor->Create(); @@ -409,7 +409,7 @@ if ($action == 'create') // Other attributes $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields,'edit',$parameters); @@ -504,7 +504,7 @@ if ($action == 'create') print ''; // Accountancy code $fieldrequired=''; - if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired='fieldrequired '; + if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired='fieldrequired '; if (! empty($conf->accounting->enabled)) { @@ -523,7 +523,7 @@ if ($action == 'create') if (! empty($conf->accounting->enabled)) { print ''; - print ''; } @@ -547,7 +547,7 @@ if ($action == 'create') /* ************************************************************************** */ else { - if (($_GET["id"] || $_GET["ref"]) && $action != 'edit') + if (($_GET["id"] || $_GET["ref"]) && $action != 'edit') { $object = new Account($db); if ($_GET["id"]) @@ -576,7 +576,7 @@ else // Print form confirm print $formconfirm; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); @@ -605,7 +605,7 @@ else print ''; @@ -624,15 +624,15 @@ else print $accountingaccount->getNomUrl(0,1,1,'',1); } else { - print $object->account_number; + print $object->account_number; } print ''; // Accountancy journal if (! empty($conf->accounting->enabled)) { - print ''; - print ''; + print ''; if (! $i) $totalarray['nbfield']++; if (! $i) $totalarray['totalbalancefield']=$totalarray['nbfield']; diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index ec61c39ee84..fb43f098583 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -47,10 +47,14 @@ $langs->load("companies"); $langs->load("bills"); $action=GETPOST('action', 'alpha'); -$id=GETPOST('account'); -$ref=GETPOST('ref'); -$dvid=GETPOST('dvid'); -$numref=GETPOST('num'); +$id=GETPOST('account','int'); +$ref=GETPOST('ref','alpha'); +$dvid=GETPOST('dvid','alpha'); +$numref=GETPOST('num','alpha'); +$ve=GETPOST("ve",'alpha'); +$brref=GETPOST('brref','alpha'); +$oldbankreceipt=GETPOST('oldbankreceipt','alpha'); +$newbankreceipt=GETPOST('newbankreceipt','alpha'); // Security check $fieldid = (! empty($ref)?$ref:$id); @@ -95,6 +99,59 @@ if ($id > 0 || ! empty($ref)) // Initialize technical object to manage context to save list fields $contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id); + +// Define number of receipt to show (current, previous or next one ?) +$found=false; +if ($_GET["rel"] == 'prev') +{ + // Recherche valeur pour num = numero releve precedent + $sql = "SELECT DISTINCT(b.num_releve) as num"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql.= " WHERE b.num_releve < '".$db->escape($numref)."'"; + $sql.= " AND b.fk_account = ".$object->id; + $sql.= " ORDER BY b.num_releve DESC"; + + dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $numrows = $db->num_rows($resql); + if ($numrows > 0) + { + $obj = $db->fetch_object($resql); + $numref = $obj->num; + $found=true; + } + } +} +elseif ($_GET["rel"] == 'next') +{ + // Recherche valeur pour num = numero releve precedent + $sql = "SELECT DISTINCT(b.num_releve) as num"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql.= " WHERE b.num_releve > '".$db->escape($numref)."'"; + $sql.= " AND b.fk_account = ".$object->id; + $sql.= " ORDER BY b.num_releve ASC"; + + dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $numrows = $db->num_rows($resql); + if ($numrows > 0) + { + $obj = $db->fetch_object($resql); + $numref = $obj->num; + $found=true; + } + } +} +else { + // On veut le releve num + $found=true; +} + + $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,"; $sql.= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,"; $sql.= " b.fk_bordereau,"; @@ -104,7 +161,7 @@ $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; $sql.= ", ".MAIN_DB_PREFIX."bank as b"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bordereau_cheque as bc ON bc.rowid=b.fk_bordereau'; $sql.= " WHERE b.num_releve='".$db->escape($numref)."'"; -if (!isset($numref)) $sql.= " OR b.num_releve is null"; +if (empty($numref)) $sql.= " OR b.num_releve is null"; $sql.= " AND b.fk_account = ".$object->id; $sql.= " AND b.fk_account = ba.rowid"; $sql.= $db->order("b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day @@ -117,6 +174,16 @@ $sqlrequestforbankline = $sql; * Actions */ +if ($action == 'confirm_editbankreceipt' && ! empty($oldbankreceipt) && ! empty($newbankreceipt)) +{ + // TODO Add a test to check newbankreceipt does not exists yet + $sqlupdate = 'UPDATE '.MAIN_DB_PREFIX.'bank SET num_releve = "'.$db->escape($newbankreceipt).'" WHERE num_releve = "'.$db->escape($oldbankreceipt).'"'; + $result = $db->query($sqlupdate); + if ($result < 0) dol_print_error($db); + + $action='view'; +} + // ZIP creation if ($action=="dl" && $numref > 0) { @@ -328,7 +395,7 @@ if (empty($numref)) $head=bank_prepare_head($object); dol_fiche_head($head,'statement',$langs->trans("FinancialAccount"),0,'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); @@ -340,23 +407,29 @@ if (empty($numref)) if ($object->canBeConciliated() > 0) { // If not cash account and can be reconciliate if ($user->rights->banque->consolidate) { - print ''.$langs->trans("Conciliate").''; + print ''.$langs->trans("Conciliate").''; } else { print ''.$langs->trans("Conciliate").''; } } print ''; - print '

      '; print_barre_liste('', $page, $_SERVER["PHP_SELF"], "&account=".$object->id, $sortfield, $sortorder,'',$numrows); + print ''; + print ''; + print ''; + print ''; + print ''; + print '
      '.$langs->trans("AccountancyJournal").''; + print ''; print $formaccounting->select_journal($object->fk_accountancy_journal, 'fk_accountancy_journal', 4, 1, 0, 0); print '
      '; $conciliate=$object->canBeConciliated(); if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; - else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; + else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; else print ($object->rappro==1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')')); print '
      '.$langs->trans("AccountancyJournal").''; + print '
      '.$langs->trans("AccountancyJournal").''; $accountingjournal = new AccountingJournal($db); $accountingjournal->fetch($object->fk_accountancy_journal); @@ -655,12 +655,12 @@ else print ''; - // Categories - if ($conf->categorie->enabled) { - print '"; - } + // Categories + if ($conf->categorie->enabled) { + print '"; + } print ''; print ''; @@ -669,11 +669,10 @@ else if ($object->type == Account::TYPE_SAVINGS || $object->type == Account::TYPE_CURRENT) { - print '
      '; - print '
      '; + print '
      '; - print '
      '.$langs->trans("Categories").''; - print $form->showCategories($object->id,'bank_account',1); - print "
      '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'bank_account',1); + print "
      '.$langs->trans("Comment").''.dol_htmlentitiesbr($object->comment).'
      '; + print '
      '; print ''; print ''; @@ -764,23 +763,23 @@ else } - /* ************************************************************************** */ - /* */ - /* Edition */ - /* */ - /* ************************************************************************** */ + /* ************************************************************************** */ + /* */ + /* Edition */ + /* */ + /* ************************************************************************** */ - if (GETPOST('id','int') && $action == 'edit' && $user->rights->banque->configurer) - { - $object = new Account($db); - $object->fetch(GETPOST('id','int')); + if (GETPOST('id','int') && $action == 'edit' && $user->rights->banque->configurer) + { + $object = new Account($db); + $object->fetch(GETPOST('id','int')); - print load_fiche_titre($langs->trans("EditFinancialAccount"), '', 'title_bank.png'); + print load_fiche_titre($langs->trans("EditFinancialAccount"), '', 'title_bank.png'); - if ($conf->use_javascript_ajax) - { - print "\n".''."\n"; - } + print ''."\n"; + } - print ''; - print ''; - print ''; - print ''."\n\n"; + print ''; + print ''; + print ''; + print ''."\n\n"; - dol_fiche_head(''); + dol_fiche_head(''); - print '
      '; + print '
      '; - print '
      '.$langs->trans("BankName").''.$object->bank.'
      '; + print '
      '; // Ref print ''; print ''; // Label - print ''; - print ''; + print ''; + print ''; - // Type - print ''; - print ''; + print ''; + print ''; // Currency print ''; // Status - print ''; - print ''; + print ''; + print ''; // Country $object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; @@ -865,15 +864,15 @@ else print ''; // Conciliable - print ''; - print ''; + print ''; + print ''; - // Balance + // Balance print ''; print ''; @@ -881,28 +880,28 @@ else print ''; // Web - print ''; - print ''; + print ''; + print ''; - // Tags-Categories - if ($conf->categorie->enabled) - { - print '"; - } + // Tags-Categories + if ($conf->categorie->enabled) + { + print '"; + } // Comment print ''; print ''.$langs->trans("AccountancyCode").''; print ''; @@ -954,9 +953,9 @@ else if ($_POST["type"] == Account::TYPE_SAVINGS || $_POST["type"] == Account::TYPE_CURRENT) { - print '
      '; + print '
      '; - //print '
      '; + //print '
      '; print '
      '.$langs->trans("Ref").'ref).'">
      '.$langs->trans("Label").'label).'">
      '.$langs->trans("Label").'label).'">
      '.$langs->trans("AccountType").''; + // Type + print '
      '.$langs->trans("AccountType").''; $formbank->selectTypeOfBankAccount((isset($_POST["type"])?$_POST["type"]:$object->type),"type"); - print '
      '.$langs->trans("Currency"); @@ -834,10 +833,10 @@ else print '
      '.$langs->trans("Status").''; - print $form->selectarray("clos", $object->status, (isset($_POST["clos"])?$_POST["clos"]:$object->clos)); - print '
      '.$langs->trans("Status").''; + print $form->selectarray("clos", $object->status, (isset($_POST["clos"])?$_POST["clos"]:$object->clos)); + print '
      '.$langs->trans("Conciliable").''; - $conciliate=$object->canBeConciliated(); - if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; - else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; - else print ' 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation"); - print '
      '.$langs->trans("Conciliable").''; + $conciliate=$object->canBeConciliated(); + if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; + else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; + else print ' 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation"); + print '
      '.$langs->trans("BalanceMinimalAllowed").'min_allowed).'">
      min_desired).'">
      '.$langs->trans("Web").'url).'">'; - print '
      '.$langs->trans("Web").'url).'">'; + print '
      '.$langs->trans("Categories").''; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); - $c = new Categorie($db); - $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); - foreach($cats as $cat) { - $arrayselected[] = $cat->id; - } - print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); - print "
      '.$langs->trans("Categories").''; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); + $c = new Categorie($db); + $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); + foreach($cats as $cat) { + $arrayselected[] = $cat->id; + } + print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); + print "
      '.$langs->trans("Comment").''; - // Editor wysiwyg + // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$object->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_4,'95%'); $doleditor->Create(); @@ -911,7 +910,7 @@ else // Other attributes $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields,'edit'); @@ -929,15 +928,15 @@ else $tdextra = ' class="titlefieldcreate"'; if (!empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) { - $tdextra = ' class="fieldrequired titlefieldcreate"'; + $tdextra = ' class="fieldrequired titlefieldcreate"'; } print '
      '; if (!empty($conf->accounting->enabled)) { - print $formaccounting->select_account($object->account_number, 'account_number', 1, '', 1, 1); + print $formaccounting->select_account($object->account_number, 'account_number', 1, '', 1, 1); } else { - print 'account_number).'">'; + print 'account_number).'">'; } print '
      '; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index cb59862e005..8ad1ccd2ecf 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -36,117 +36,117 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class Account extends CommonObject { - public $element = 'bank_account'; - public $table_element = 'bank_account'; - public $picto = 'account'; + public $element = 'bank_account'; + public $table_element = 'bank_account'; + public $picto = 'account'; - /** - * @var int Use id instead of rowid - * @deprecated - * @see id - */ - public $rowid; + /** + * @var int Use id instead of rowid + * @deprecated + * @see id + */ + public $rowid; - /** - * Label - * @var string - */ - public $label; + /** + * Label + * @var string + */ + public $label; - /** - * Bank account type. Check TYPE_ constants - * @var int - */ - public $courant; + /** + * Bank account type. Check TYPE_ constants + * @var int + */ + public $courant; - /** - * Bank account type. Check TYPE_ constants - * @var int - */ - public $type; + /** + * Bank account type. Check TYPE_ constants + * @var int + */ + public $type; - /** - * Bank name - * @var string - */ - public $bank; + /** + * Bank name + * @var string + */ + public $bank; - /** - * Status - * @var int - */ - public $clos = self::STATUS_OPEN; + /** + * Status + * @var int + */ + public $clos = self::STATUS_OPEN; - /** - * Does it need to be conciliated? - * @var int - */ - public $rappro=1; + /** + * Does it need to be conciliated? + * @var int + */ + public $rappro=1; - /** - * Webpage - * @var string - */ - public $url; + /** + * Webpage + * @var string + */ + public $url; - /** - * Bank number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $code_banque; + /** + * Bank number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $code_banque; - /** - * Branch number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $code_guichet; + /** + * Branch number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $code_guichet; - /** - * Account number. If in SEPA area, you should move to IBAN field - * @var string - */ - public $number; + /** + * Account number. If in SEPA area, you should move to IBAN field + * @var string + */ + public $number; - /** - * Bank account number control digit. If in SEPA area, you should move to IBAN field - * @var string - */ - public $cle_rib; + /** + * Bank account number control digit. If in SEPA area, you should move to IBAN field + * @var string + */ + public $cle_rib; - /** - * BIC/Swift code - * @var string - */ - public $bic; + /** + * BIC/Swift code + * @var string + */ + public $bic; - /** - * IBAN number (International Bank Account Number). Stored into iban_prefix field into database - * @var - */ - public $iban; + /** + * IBAN number (International Bank Account Number). Stored into iban_prefix field into database + * @var + */ + public $iban; - /** - * Name of account holder - * @var string - */ - public $proprio; + /** + * Name of account holder + * @var string + */ + public $proprio; - /** - * Address of account holder - * @var string - */ - public $owner_address; + /** + * Address of account holder + * @var string + */ + public $owner_address; - public $state_id; - public $state_code; - public $state; + public $state_id; + public $state_code; + public $state; /** * Variable containing all account types with their respective translated label. * Defined in __construct * @var array */ - public $type_lib = array(); + public $type_lib = array(); /** * Variable containing all account statuses with their respective translated label. @@ -155,90 +155,90 @@ class Account extends CommonObject */ public $status = array(); - /** - * Accountancy code - * @var string - */ - public $account_number; + /** + * Accountancy code + * @var string + */ + public $account_number; public $fk_accountancy_journal; - /** - * Currency code - * @var string - */ - public $currency_code; + /** + * Currency code + * @var string + */ + public $currency_code; - /** - * Currency code - * @var string - * @deprecated Use currency_code instead - */ - public $account_currency_code; + /** + * Currency code + * @var string + * @deprecated Use currency_code instead + */ + public $account_currency_code; - /** - * Authorized minimum balance - * @var float - */ - public $min_allowed; + /** + * Authorized minimum balance + * @var float + */ + public $min_allowed; - /** - * Desired minimum balance - * @var float - */ - public $min_desired; + /** + * Desired minimum balance + * @var float + */ + public $min_desired; - /** - * Notes - * @var string - */ - public $comment; + /** + * Notes + * @var string + */ + public $comment; - /** - * Date of the initial balance. Used in Account::create - * @var int - */ - public $date_solde; + /** + * Date of the initial balance. Used in Account::create + * @var int + */ + public $date_solde; - /** - * Current account - */ - const TYPE_CURRENT = 1; - /** - * Cash account - */ - const TYPE_CASH = 2; - /** - * Savings account - */ - const TYPE_SAVINGS = 0; + /** + * Current account + */ + const TYPE_CURRENT = 1; + /** + * Cash account + */ + const TYPE_CASH = 2; + /** + * Savings account + */ + const TYPE_SAVINGS = 0; - const STATUS_OPEN = 0; - const STATUS_CLOSED = 1; + const STATUS_OPEN = 0; + const STATUS_CLOSED = 1; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct(DoliDB $db) - { - global $langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB $db) + { + global $langs; - $this->db = $db; + $this->db = $db; - $this->solde = 0; + $this->solde = 0; - $this->type_lib = array( - self::TYPE_SAVINGS => $langs->trans("BankType0"), - self::TYPE_CURRENT => $langs->trans("BankType1"), - self::TYPE_CASH => $langs->trans("BankType2"), - ); + $this->type_lib = array( + self::TYPE_SAVINGS => $langs->trans("BankType0"), + self::TYPE_CURRENT => $langs->trans("BankType1"), + self::TYPE_CASH => $langs->trans("BankType2"), + ); - $this->status = array( - self::STATUS_OPEN => $langs->trans("StatusAccountOpened"), - self::STATUS_CLOSED => $langs->trans("StatusAccountClosed") - ); - } + $this->status = array( + self::STATUS_OPEN => $langs->trans("StatusAccountOpened"), + self::STATUS_CLOSED => $langs->trans("StatusAccountClosed") + ); + } /** * Shows the account number in the appropiate format @@ -270,183 +270,184 @@ class Account extends CommonObject } - /** - * Return if a bank account need to be conciliated - * - * @return int 1 if need to be concialiated, < 0 otherwise. - */ - function canBeConciliated() - { - global $conf; + /** + * Return if a bank account need to be conciliated + * + * @return int 1 if need to be concialiated, < 0 otherwise. + */ + function canBeConciliated() + { + global $conf; - if (empty($this->rappro)) return -1; - if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2; - if ($this->clos) return -3; - return 1; - } + if (empty($this->rappro)) return -1; + if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2; + if ($this->clos) return -3; + return 1; + } - /** - * Add a link between bank line record and its source - * - * @param int $line_id Id ecriture bancaire - * @param int $url_id Id parametre url - * @param string $url Url - * @param string $label Link label - * @param string $type Type of link ('payment', 'company', 'member', ...) - * @return int <0 if KO, id line if OK - */ - function add_url_line($line_id, $url_id, $url, $label, $type) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; - $sql.= "fk_bank"; - $sql.= ", url_id"; - $sql.= ", url"; - $sql.= ", label"; - $sql.= ", type"; - $sql.= ") VALUES ("; - $sql.= "'".$line_id."'"; - $sql.= ", '".$url_id."'"; - $sql.= ", '".$url."'"; - $sql.= ", '".$this->db->escape($label)."'"; - $sql.= ", '".$type."'"; - $sql.= ")"; + /** + * Add a link between bank line record and its source + * + * @param int $line_id Id ecriture bancaire + * @param int $url_id Id parametre url + * @param string $url Url + * @param string $label Link label + * @param string $type Type of link ('payment', 'company', 'member', ...) + * @return int <0 if KO, id line if OK + */ + function add_url_line($line_id, $url_id, $url, $label, $type) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url ("; + $sql.= "fk_bank"; + $sql.= ", url_id"; + $sql.= ", url"; + $sql.= ", label"; + $sql.= ", type"; + $sql.= ") VALUES ("; + $sql.= "'".$line_id."'"; + $sql.= ", '".$url_id."'"; + $sql.= ", '".$url."'"; + $sql.= ", '".$this->db->escape($label)."'"; + $sql.= ", '".$type."'"; + $sql.= ")"; - dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); - if ($this->db->query($sql)) - { - $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url"); - return $rowid; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG); + if ($this->db->query($sql)) + { + $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url"); + return $rowid; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } - /** - * TODO Move this into AccountLine - * Return array with links from llx_bank_url - * - * @param int $fk_bank To search using bank transaction id - * @param int $url_id To search using link to - * @param string $type To search using type - * @return array|-1 Array of links or -1 on error - */ - function get_url($fk_bank='', $url_id='', $type='') - { - $lines = array(); + /** + * TODO Move this into AccountLine + * Return array with links from llx_bank_url + * + * @param int $fk_bank To search using bank transaction id + * @param int $url_id To search using link to + * @param string $type To search using type + * @return array|-1 Array of links or -1 on error + */ + function get_url($fk_bank='', $url_id='', $type='') + { + $lines = array(); - // Check parameters - if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) - { - $this->error="ErrorBadParameter"; - return -1; - } + // Check parameters + if (! empty($fk_bank) && (! empty($url_id) || ! empty($type))) + { + $this->error="ErrorBadParameter"; + return -1; + } - $sql = "SELECT fk_bank, url_id, url, label, type"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; - if ($fk_bank > 0) { - $sql.= " WHERE fk_bank = ".$fk_bank; - } - else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; - } - $sql.= " ORDER BY type, label"; + $sql = "SELECT fk_bank, url_id, url, label, type"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_url"; + if ($fk_bank > 0) { + $sql.= " WHERE fk_bank = ".$fk_bank; + } + else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'"; + } + $sql.= " ORDER BY type, label"; - dol_syslog(get_class($this)."::get_url", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $i = 0; - $num = $this->db->num_rows($result); - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - // Anciens liens (pour compatibilite) - $lines[$i][0] = $obj->url; - $lines[$i][1] = $obj->url_id; - $lines[$i][2] = $obj->label; - $lines[$i][3] = $obj->type; - // Nouveaux liens - $lines[$i]['url'] = $obj->url; - $lines[$i]['url_id'] = $obj->url_id; - $lines[$i]['label'] = $obj->label; - $lines[$i]['type'] = $obj->type; - $lines[$i]['fk_bank'] = $obj->fk_bank; - $i++; - } - } - else dol_print_error($this->db); + dol_syslog(get_class($this)."::get_url", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $i = 0; + $num = $this->db->num_rows($result); + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + // Anciens liens (pour compatibilite) + $lines[$i][0] = $obj->url; + $lines[$i][1] = $obj->url_id; + $lines[$i][2] = $obj->label; + $lines[$i][3] = $obj->type; + // Nouveaux liens + $lines[$i]['url'] = $obj->url; + $lines[$i]['url_id'] = $obj->url_id; + $lines[$i]['label'] = $obj->label; + $lines[$i]['type'] = $obj->type; + $lines[$i]['fk_bank'] = $obj->fk_bank; + $i++; + } + } + else dol_print_error($this->db); - return $lines; - } + return $lines; + } - /** - * Add an entry into table ".MAIN_DB_PREFIX."bank - * - * @param int $date Date operation - * @param string $oper 1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ... - * @param string $label Descripton - * @param float $amount Amount - * @param string $num_chq Numero cheque ou virement - * @param int $categorie Category id (optionnal) - * @param User $user User that create - * @param string $emetteur Name of cheque writer - * @param string $banque Bank of cheque writer - * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. - * @return int Rowid of added entry, <0 if KO - */ - function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') - { - // Deprecatîon warning - if (is_numeric($oper)) { - dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); - } + /** + * Add an entry into table ".MAIN_DB_PREFIX."bank + * + * @param int $date Date operation + * @param string $oper 1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ... + * @param string $label Descripton + * @param float $amount Amount + * @param string $num_chq Numero cheque ou virement + * @param int $categorie Category id (optionnal) + * @param User $user User that create + * @param string $emetteur Name of cheque writer + * @param string $banque Bank of cheque writer + * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. + * @return int Rowid of added entry, <0 if KO + */ + function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') + { + // Deprecatîon warning + if (is_numeric($oper)) { + dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING); + } - // Clean parameters - $emetteur=trim($emetteur); - $banque=trim($banque); + // Clean parameters + $emetteur=trim($emetteur); + $banque=trim($banque); - $now=dol_now(); + $now=dol_now(); - if (is_numeric($oper)) // Clean oper to have a code instead of a rowid - { - $sql ="SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; - $sql.=" WHERE id=".$oper; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $oper=$obj->code; - } - else - { - dol_print_error($this->db,'Failed to get payment type code'); - return -1; - } - } + if (is_numeric($oper)) // Clean oper to have a code instead of a rowid + { + $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement"; + $sql.= " WHERE id=".$oper; + $sql.= " AND entity IN (" . getEntity('c_paiement') . ")"; + $resql=$this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $oper=$obj->code; + } + else + { + dol_print_error($this->db,'Failed to get payment type code'); + return -1; + } + } - // Check parameters - if (! $oper) - { - $this->error="oper not defined"; - return -1; - } - if (! $this->rowid) - { - $this->error="this->rowid not defined"; - return -2; - } - if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') - { - $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; - return -3; - } + // Check parameters + if (! $oper) + { + $this->error="oper not defined"; + return -1; + } + if (! $this->rowid) + { + $this->error="this->rowid not defined"; + return -2; + } + if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') + { + $this->error="ErrorCashAccountAcceptsOnlyCashMoney"; + return -3; + } - $this->db->begin(); + $this->db->begin(); - $datev = $date; + $datev = $date; $accline = new AccountLine($this->db); $accline->datec = $now; @@ -497,109 +498,109 @@ class Account extends CommonObject } } - /** - * Create bank account into database - * - * @param User $user Object user making creation - * @param int $notrigger 1=Disable triggers - * @return int < 0 if KO, > 0 if OK - */ - function create(User $user = null, $notrigger=0) - { - global $langs,$conf, $hookmanager; + /** + * Create bank account into database + * + * @param User $user Object user making creation + * @param int $notrigger 1=Disable triggers + * @return int < 0 if KO, > 0 if OK + */ + function create(User $user = null, $notrigger=0) + { + global $langs,$conf, $hookmanager; - // Clean parameters - if (! $this->min_allowed) $this->min_allowed=0; - if (! $this->min_desired) $this->min_desired=0; - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + // Clean parameters + if (! $this->min_allowed) $this->min_allowed=0; + if (! $this->min_desired) $this->min_desired=0; + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - // Check parameters - if (empty($this->country_id)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->ref)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->date_solde)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance")); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - return -1; - } + // Check parameters + if (empty($this->country_id)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->ref)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->date_solde)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance")); + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + return -1; + } - // Chargement librairie pour acces fonction controle RIB - require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; + // Chargement librairie pour acces fonction controle RIB + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - $now=dol_now(); + $now=dol_now(); - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; - $sql.= "datec"; - $sql.= ", ref"; - $sql.= ", label"; - $sql.= ", entity"; - $sql.= ", account_number"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; + $sql.= "datec"; + $sql.= ", ref"; + $sql.= ", label"; + $sql.= ", entity"; + $sql.= ", account_number"; $sql.= ", fk_accountancy_journal"; $sql.= ", bank"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ", bic"; - $sql.= ", iban_prefix"; - $sql.= ", domiciliation"; - $sql.= ", proprio"; - $sql.= ", owner_address"; + $sql.= ", code_banque"; + $sql.= ", code_guichet"; + $sql.= ", number"; + $sql.= ", cle_rib"; + $sql.= ", bic"; + $sql.= ", iban_prefix"; + $sql.= ", domiciliation"; + $sql.= ", proprio"; + $sql.= ", owner_address"; $sql.= ", currency_code"; - $sql.= ", rappro"; - $sql.= ", min_allowed"; - $sql.= ", min_desired"; - $sql.= ", comment"; - $sql.= ", state_id"; - $sql.= ", fk_pays"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->idate($now)."'"; - $sql.= ", '".$this->db->escape($this->ref)."'"; - $sql.= ", '".$this->db->escape($this->label)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->escape($this->account_number)."'"; + $sql.= ", rappro"; + $sql.= ", min_allowed"; + $sql.= ", min_desired"; + $sql.= ", comment"; + $sql.= ", state_id"; + $sql.= ", fk_pays"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->idate($now)."'"; + $sql.= ", '".$this->db->escape($this->ref)."'"; + $sql.= ", '".$this->db->escape($this->label)."'"; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->escape($this->account_number)."'"; $sql.= ", ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); $sql.= ", '".$this->db->escape($this->bank)."'"; - $sql.= ", '".$this->db->escape($this->code_banque)."'"; - $sql.= ", '".$this->db->escape($this->code_guichet)."'"; - $sql.= ", '".$this->db->escape($this->number)."'"; - $sql.= ", '".$this->db->escape($this->cle_rib)."'"; - $sql.= ", '".$this->db->escape($this->bic)."'"; - $sql.= ", '".$this->db->escape($this->iban)."'"; - $sql.= ", '".$this->db->escape($this->domiciliation)."'"; - $sql.= ", '".$this->db->escape($this->proprio)."'"; - $sql.= ", '".$this->db->escape($this->owner_address)."'"; - $sql.= ", '".$this->db->escape($this->currency_code)."'"; - $sql.= ", ".$this->rappro; - $sql.= ", ".price2num($this->min_allowed); - $sql.= ", ".price2num($this->min_desired); - $sql.= ", '".$this->db->escape($this->comment)."'"; - $sql.= ", ".($this->state_id>0?$this->state_id:"null"); - $sql.= ", ".$this->country_id; - $sql.= ")"; + $sql.= ", '".$this->db->escape($this->code_banque)."'"; + $sql.= ", '".$this->db->escape($this->code_guichet)."'"; + $sql.= ", '".$this->db->escape($this->number)."'"; + $sql.= ", '".$this->db->escape($this->cle_rib)."'"; + $sql.= ", '".$this->db->escape($this->bic)."'"; + $sql.= ", '".$this->db->escape($this->iban)."'"; + $sql.= ", '".$this->db->escape($this->domiciliation)."'"; + $sql.= ", '".$this->db->escape($this->proprio)."'"; + $sql.= ", '".$this->db->escape($this->owner_address)."'"; + $sql.= ", '".$this->db->escape($this->currency_code)."'"; + $sql.= ", ".$this->rappro; + $sql.= ", ".price2num($this->min_allowed); + $sql.= ", ".price2num($this->min_desired); + $sql.= ", '".$this->db->escape($this->comment)."'"; + $sql.= ", ".($this->state_id>0?$this->state_id:"null"); + $sql.= ", ".$this->country_id; + $sql.= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); - $result=$this->update($user, 1); - if ($result > 0) - { + $result=$this->update($user, 1); + if ($result > 0) + { $accline = new AccountLine($this->db); $accline->datec = $this->db->idate($now); $accline->label = '('.$langs->trans("InitialBankBalance").')'; @@ -612,455 +613,455 @@ class Account extends CommonObject if ($accline->insert() < 0) { $error++; - $this->error = $accline->error; - $this->errors = $accline->errors; + $this->error = $accline->error; + $this->errors = $accline->errors; } if (! $error) { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; + $result=$this->insertExtraFields(); + if ($result < 0) $error++; } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } - else - { - $error++; - } - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); - $error++; - } - else { - $this->error=$this->db->error()." sql=".$sql; - $error++; - } - } - - if (! $error) - { - $this->db->commit(); - return $this->id; - } - else - { - $this->db->rollback(); - return -1*$error; - } - } - - /** - * Update bank account card - * - * @param User $user Object user making action - * @param int $notrigger 1=Disable triggers - * @return int <0 if KO, >0 if OK - */ - function update(User $user = null, $notrigger = 0) - { - global $langs,$conf, $hookmanager; - - $error=0; - - $this->db->begin(); - - // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - - // Check parameters - if (empty($this->country_id)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); - return -1; - } - if (empty($this->ref)) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); - return -1; - } - if (! $this->label) $this->label = "???"; - - $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - - $sql.= " ref = '".$this->db->escape($this->ref)."'"; - $sql.= ",label = '".$this->db->escape($this->label)."'"; - - $sql.= ",courant = ".$this->courant; - $sql.= ",clos = ".$this->clos; - $sql.= ",rappro = ".$this->rappro; - $sql.= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null"); - $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; - $sql.= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); - $sql.= ",bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - - $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; - - $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); - $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); - $sql.= ",comment = '".$this->db->escape($this->comment)."'"; - - $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); - $sql.= ",fk_pays = ".$this->country_id; - - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // Actions on extra fields (by external module or standard code) - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - if (! $error) - { - $result=$this->insertExtraFields(); - if ($result < 0) $error++; - } - } - - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } - else - { - $error++; - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - } - - if (! $error) - { - $this->db->commit(); - return $this->id; + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; + } } else { - $this->db->rollback(); - return -1*$error; + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); + $error++; + } + else { + $this->error=$this->db->error()." sql=".$sql; + $error++; + } } - } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } + } + + /** + * Update bank account card + * + * @param User $user Object user making action + * @param int $notrigger 1=Disable triggers + * @return int <0 if KO, >0 if OK + */ + function update(User $user = null, $notrigger = 0) + { + global $langs,$conf, $hookmanager; + + $error=0; + + $this->db->begin(); + + // Clean parameters + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + + // Check parameters + if (empty($this->country_id)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country")); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -1; + } + if (empty($this->ref)) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -1; + } + if (! $this->label) $this->label = "???"; + + $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; + + $sql.= " ref = '".$this->db->escape($this->ref)."'"; + $sql.= ",label = '".$this->db->escape($this->label)."'"; + + $sql.= ",courant = ".$this->courant; + $sql.= ",clos = ".$this->clos; + $sql.= ",rappro = ".$this->rappro; + $sql.= ",url = ".($this->url?"'".$this->db->escape($this->url)."'":"null"); + $sql.= ",account_number = '".$this->db->escape($this->account_number)."'"; + $sql.= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null"); + $sql.= ",bank = '".$this->db->escape($this->bank)."'"; + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + + $sql.= ",currency_code = '".$this->db->escape($this->currency_code)."'"; + + $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null"); + $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null"); + $sql.= ",comment = '".$this->db->escape($this->comment)."'"; + + $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); + $sql.= ",fk_pays = ".$this->country_id; + + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // Actions on extra fields (by external module or standard code) + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + if (! $error) + { + $result=$this->insertExtraFields(); + if ($result < 0) $error++; + } + } + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } + } - /** - * Update BBAN (RIB) account fields - * - * @param User $user Object user making update - * @return int <0 if KO, >0 if OK - */ - function update_bban(User $user = null) - { - global $conf,$langs; + /** + * Update BBAN (RIB) account fields + * + * @param User $user Object user making update + * @return int <0 if KO, >0 if OK + */ + function update_bban(User $user = null) + { + global $conf,$langs; - // Clean parameters - $this->state_id = ($this->state_id?$this->state_id:$this->state_id); - $this->country_id = ($this->country_id?$this->country_id:$this->country_id); + // Clean parameters + $this->state_id = ($this->state_id?$this->state_id:$this->state_id); + $this->country_id = ($this->country_id?$this->country_id:$this->country_id); - // Chargement librairie pour acces fonction controle RIB - require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; + // Chargement librairie pour acces fonction controle RIB + require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; - dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); + dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban"); - // Check parameters - if (! $this->ref) - { - $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref")); - return -2; - } + // Check parameters + if (! $this->ref) + { + $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref")); + return -2; + } - $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; - $sql.= " bank = '".$this->db->escape($this->bank)."'"; - $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; - $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; - $sql.= ",number='".$this->db->escape($this->number)."'"; - $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; - $sql.= ",bic='".$this->db->escape($this->bic)."'"; - $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; - $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; - $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; - $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; - $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); - $sql.= ",fk_pays = ".$this->country_id; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET "; + $sql.= " bank = '".$this->db->escape($this->bank)."'"; + $sql.= ",code_banque='".$this->db->escape($this->code_banque)."'"; + $sql.= ",code_guichet='".$this->db->escape($this->code_guichet)."'"; + $sql.= ",number='".$this->db->escape($this->number)."'"; + $sql.= ",cle_rib='".$this->db->escape($this->cle_rib)."'"; + $sql.= ",bic='".$this->db->escape($this->bic)."'"; + $sql.= ",iban_prefix = '".$this->db->escape($this->iban)."'"; + $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'"; + $sql.= ",proprio = '".$this->db->escape($this->proprio)."'"; + $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'"; + $sql.= ",state_id = ".($this->state_id>0?$this->state_id:"null"); + $sql.= ",fk_pays = ".$this->country_id; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); + dol_syslog(get_class($this)."::update_bban", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - return -1; - } - } + $result = $this->db->query($sql); + if ($result) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + return -1; + } + } - /** - * Load a bank account into memory from database - * - * @param int $id Id of bank account to get - * @param string $ref Ref of bank account to get - * @return int <0 if KO, >0 if OK - */ - function fetch($id, $ref='') - { - global $conf; + /** + * Load a bank account into memory from database + * + * @param int $id Id of bank account to get + * @param string $ref Ref of bank account to get + * @return int <0 if KO, >0 if OK + */ + function fetch($id, $ref='') + { + global $conf; - if (empty($id) && empty($ref)) - { - $this->error="ErrorBadParameters"; - return -1; - } + if (empty($id) && empty($ref)) + { + $this->error="ErrorBadParameters"; + return -1; + } - $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; - $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; - $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; - $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; - $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; - $sql.= " ba.datec as date_creation, ba.tms as date_update,"; - $sql.= ' c.code as country_code, c.label as country,'; - $sql.= ' d.code_departement as state_code, d.nom as state'; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; - $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; - if ($id) $sql.= " AND ba.rowid = ".$id; - if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; + $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,"; + $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,"; + $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,"; + $sql.= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,"; + $sql.= " ba.min_allowed, ba.min_desired, ba.comment,"; + $sql.= " ba.datec as date_creation, ba.tms as date_update,"; + $sql.= ' c.code as country_code, c.label as country,'; + $sql.= ' d.code_departement as state_code, d.nom as state'; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid'; + $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; + if ($id) $sql.= " AND ba.rowid = ".$id; + if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->ref = $obj->ref; - $this->label = $obj->label; - $this->type = $obj->courant; - $this->courant = $obj->courant; - $this->bank = $obj->bank; - $this->clos = $obj->clos; - $this->rappro = $obj->rappro; - $this->url = $obj->url; + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->ref = $obj->ref; + $this->label = $obj->label; + $this->type = $obj->courant; + $this->courant = $obj->courant; + $this->bank = $obj->bank; + $this->clos = $obj->clos; + $this->rappro = $obj->rappro; + $this->url = $obj->url; - $this->code_banque = $obj->code_banque; - $this->code_guichet = $obj->code_guichet; - $this->number = $obj->number; - $this->cle_rib = $obj->cle_rib; - $this->bic = $obj->bic; - $this->iban = $obj->iban; - $this->domiciliation = $obj->domiciliation; - $this->proprio = $obj->proprio; - $this->owner_address = $obj->owner_address; + $this->code_banque = $obj->code_banque; + $this->code_guichet = $obj->code_guichet; + $this->number = $obj->number; + $this->cle_rib = $obj->cle_rib; + $this->bic = $obj->bic; + $this->iban = $obj->iban; + $this->domiciliation = $obj->domiciliation; + $this->proprio = $obj->proprio; + $this->owner_address = $obj->owner_address; - $this->state_id = $obj->state_id; - $this->state_code = $obj->state_code; - $this->state = $obj->state; + $this->state_id = $obj->state_id; + $this->state_code = $obj->state_code; + $this->state = $obj->state; - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_code; - $this->country = $obj->country; + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_code; + $this->country = $obj->country; - $this->account_number = $obj->account_number; + $this->account_number = $obj->account_number; $this->fk_accountancy_journal = $obj->fk_accountancy_journal; - $this->currency_code = $obj->currency_code; - $this->account_currency_code = $obj->currency_code; - $this->min_allowed = $obj->min_allowed; - $this->min_desired = $obj->min_desired; - $this->comment = $obj->comment; + $this->currency_code = $obj->currency_code; + $this->account_currency_code = $obj->currency_code; + $this->min_allowed = $obj->min_allowed; + $this->min_desired = $obj->min_desired; + $this->comment = $obj->comment; - $this->date_creation = $this->db->jdate($obj->date_creation); - $this->date_update = $this->db->jdate($obj->date_update); + $this->date_creation = $this->db->jdate($obj->date_creation); + $this->date_update = $this->db->jdate($obj->date_update); - // Retreive all extrafield for thirdparty - // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); - return 1; - } - else + return 1; + } + else { - return 0; - } - } - else - { - $this->error=$this->db->lasterror; - $this->errors[]=$this->error; - return -1; - } - } + return 0; + } + } + else + { + $this->error=$this->db->lasterror; + $this->errors[]=$this->error; + return -1; + } + } - /** - * Sets object to supplied categories. - * - * Deletes object from existing categories not supplied. - * Adds it to non existing supplied categories. - * Existing categories are left untouch. - * - * @param int[]|int $categories Category or categories IDs - */ - public function setCategories($categories) { - // Handle single category - if (! is_array($categories)) { - $categories = array($categories); - } + /** + * Sets object to supplied categories. + * + * Deletes object from existing categories not supplied. + * Adds it to non existing supplied categories. + * Existing categories are left untouch. + * + * @param int[]|int $categories Category or categories IDs + */ + public function setCategories($categories) { + // Handle single category + if (! is_array($categories)) { + $categories = array($categories); + } - // Get current categories - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $c = new Categorie($this->db); - $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); + // Get current categories + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $c = new Categorie($this->db); + $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id'); - // Diff - if (is_array($existing)) { - $to_del = array_diff($existing, $categories); - $to_add = array_diff($categories, $existing); - } else { - $to_del = array(); // Nothing to delete - $to_add = $categories; - } + // Diff + if (is_array($existing)) { + $to_del = array_diff($existing, $categories); + $to_add = array_diff($categories, $existing); + } else { + $to_del = array(); // Nothing to delete + $to_add = $categories; + } - // Process - foreach($to_del as $del) { - if ($c->fetch($del) > 0) { - $c->del_type($this, 'account'); - } - } - foreach ($to_add as $add) { - if ($c->fetch($add) > 0) { - $c->add_type($this, 'account'); - } - } + // Process + foreach($to_del as $del) { + if ($c->fetch($del) > 0) { + $c->del_type($this, 'account'); + } + } + foreach ($to_add as $add) { + if ($c->fetch($add) > 0) { + $c->add_type($this, 'account'); + } + } - return; - } + return; + } - /** - * Delete bank account from database - * - * @param User $user User deleting - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null) - { - global $conf; + /** + * Delete bank account from database + * + * @param User $user User deleting + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null) + { + global $conf; - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - // Delete link between tag and bank account - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; - $sql.= " WHERE fk_account = ".$this->id; + // Delete link between tag and bank account + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account"; + $sql.= " WHERE fk_account = ".$this->id; - $resql = $this->db->query($sql); - if (!$resql) - { - $error++; - $this->error = "Error ".$this->db->lasterror(); - } - } + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = "Error ".$this->db->lasterror(); + } + } - if (! $error) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE rowid = ".$this->rowid; + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account"; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - // Remove extrafields - if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used - { - $result=$this->deleteExtraFields(); - if ($result < 0) - { - $error++; - dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); - } - } - } - else - { - $error++; - $this->error = "Error ".$this->db->lasterror(); - } - } + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + // Remove extrafields + if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); + } + } + } + else + { + $error++; + $this->error = "Error ".$this->db->lasterror(); + } + } - if (! $error) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** + /** * Return label of object status - * + * * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->clos,$mode); - } + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->clos,$mode); + } - /** - * Return label of given object status - * - * @param int $statut Id statut + /** + * Return label of given object status + * + * @param int $statut Id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @return string Label - */ + * @return string Label + */ function LibStatut($statut, $mode = 0) { global $langs; @@ -1083,7 +1084,7 @@ class Account extends CommonObject } elseif ($mode == 5) { return $label.' '.$picto; } elseif ($mode == 6) { - return $label.' '.$picto; + return $label.' '.$picto; } //There is no short mode for this label @@ -1091,342 +1092,394 @@ class Account extends CommonObject } - /** - * Renvoi si un compte peut etre supprimer ou non (sans mouvements) - * - * @return boolean vrai si peut etre supprime, faux sinon - */ - function can_be_deleted() - { - $can_be_deleted=false; + /** + * Renvoi si un compte peut etre supprimer ou non (sans mouvements) + * + * @return boolean vrai si peut etre supprime, faux sinon + */ + function can_be_deleted() + { + $can_be_deleted=false; - $sql = "SELECT COUNT(rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account=".$this->id; + $sql = "SELECT COUNT(rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account=".$this->id; - $resql = $this->db->query($sql); - if ($resql) { - $obj=$this->db->fetch_object($resql); - if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde - } - else { - dol_print_error($this->db); - } - return $can_be_deleted; - } + $resql = $this->db->query($sql); + if ($resql) { + $obj=$this->db->fetch_object($resql); + if ($obj->nb <= 1) $can_be_deleted=true; // Juste le solde + } + else { + dol_print_error($this->db); + } + return $can_be_deleted; + } - /** - * Return error - * - * @return string Error string - */ - function error() - { - return $this->error; - } + /** + * Return error + * + * @return string Error string + */ + function error() + { + return $this->error; + } - /** - * Return current sold - * - * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) - * @return int Current sold (value date <= today) - */ - function solde($option=0) - { - $sql = "SELECT sum(amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account = ".$this->id; - if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; + /** + * Return current sold + * + * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) + * @return int Current sold (value date <= today) + */ + function solde($option=0) + { + $sql = "SELECT sum(amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account = ".$this->id; + if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'"; - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj=$this->db->fetch_object($resql); - $solde = $obj->amount; - } - $this->db->free($resql); - return $solde; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj=$this->db->fetch_object($resql); + $solde = $obj->amount; + } + $this->db->free($resql); + return $solde; + } + } - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @param int $filteraccountid To get info for a particular account id - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - function load_board(User $user, $filteraccountid = 0) - { - global $conf, $langs; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @param int $filteraccountid To get info for a particular account id + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + */ + function load_board(User $user, $filteraccountid = 0) + { + global $conf, $langs; - if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe - $sql = "SELECT b.rowid, b.datev as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.rappro=0"; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable - $sql.= " AND clos = 0"; - if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; + $sql = "SELECT b.rowid, b.datev as datefin"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.rappro=0"; + $sql.= " AND b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable + $sql.= " AND clos = 0"; + if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; - $resql=$this->db->query($sql); - if ($resql) - { - $langs->load("banks"); - $now=dol_now(); + $resql=$this->db->query($sql); + if ($resql) + { + $langs->load("banks"); + $now=dol_now(); - require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; - $response = new WorkboardResponse(); - $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24; - $response->label=$langs->trans("TransactionsToConciliate"); - $response->url=DOL_URL_ROOT.'/compta/bank/index.php?leftmenu=bank&mainmenu=bank'; - $response->img=img_object('',"payment"); + $response = new WorkboardResponse(); + $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24; + $response->label=$langs->trans("TransactionsToConciliate"); + $response->url=DOL_URL_ROOT.'/compta/bank/list.php?leftmenu=bank&mainmenu=bank'; + $response->img=img_object('',"payment"); - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; - if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) { - $response->nbtodolate++; - } - } + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; + if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) { + $response->nbtodolate++; + } + } - return $response; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } - } + return $response; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + + /** + * Charge indicateurs this->nb de tableau de bord + * @param int $filteraccountid To get info for a particular account id + * @return int <0 if ko, >0 if ok + */ + function load_state_board($filteraccountid = 0) + { + global $user; + + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + + $sql = "SELECT count(b.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable + $sql.= " AND clos = 0"; + if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid; + + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["banklines"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } - /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @return int Nb of account we can reconciliate - */ - public static function countAccountToReconcile() - { - global $db, $conf, $user; + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @return int Nb of account we can reconciliate + */ + public static function countAccountToReconcile() + { + global $db, $conf, $user; - //Protection against external users - if ($user->societe_id) { - return 0; - } + //Protection against external users + if ($user->societe_id) { + return 0; + } - $nb=0; + $nb=0; - $sql = "SELECT COUNT(ba.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $nb = $obj->nb; - } - else dol_print_error($db); + $sql = "SELECT COUNT(ba.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE ba.rappro > 0 and ba.clos = 0"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $nb = $obj->nb; + } + else dol_print_error($db); - return $nb; - } + return $nb; + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto Include picto into link - * @param string $mode ''=Link to card, 'transactions'=Link to transactions card - * @param string $option ''=Show ref, 'reflabel'=Show ref+label - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0, $mode='', $option='') - { - global $conf, $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto Include picto into link + * @param string $mode ''=Link to card, 'transactions'=Link to transactions card + * @param string $option ''=Show ref, 'reflabel'=Show ref+label + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0, $mode='', $option='', $save_lastsearch_value=-1) + { + global $conf, $langs; - $result=''; - $label = '' . $langs->trans("ShowAccount") . ''; - $label .= '
      ' . $langs->trans('BankAccount') . ': ' . $this->label; - $label .= '
      ' . $langs->trans('AccountNumber') . ': ' . $this->number; - $label .= '
      ' . $langs->trans("AccountCurrency") . ': ' . $this->currency_code; - if (! empty($conf->accounting->enabled)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; - $langs->load("accountancy"); - $label .= '
      ' . $langs->trans('AccountAccounting') . ': ' . length_accountg($this->account_number); - $label .= '
      ' . $langs->trans('AccountancyJournal') . ': ' . $this->accountancy_journal; - } - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + $result=''; + $label = '' . $langs->trans("ShowAccount") . ''; + $label .= '
      ' . $langs->trans('BankAccount') . ': ' . $this->label; + $label .= '
      ' . $langs->trans('AccountNumber') . ': ' . $this->number; + $label .= '
      ' . $langs->trans("AccountCurrency") . ': ' . $this->currency_code; + if (! empty($conf->accounting->enabled)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + $langs->load("accountancy"); + $label .= '
      ' . $langs->trans('AccountAccounting') . ': ' . length_accountg($this->account_number); + $label .= '
      ' . $langs->trans('AccountancyJournal') . ': ' . $this->accountancy_journal; + } + $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - if (empty($mode)) - { - $link = ''; - } - else if ($mode == 'receipts') - { - $link = 'ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; - return $result; - } + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $link = 'ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; + return $result; + } - // Method after here are common to Account and CompanyBankAccount + // Method after here are common to Account and CompanyBankAccount - /** - * Return if an account has valid information - * - * @return int 1 if correct, <=0 if wrong - */ - function verif() - { - require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; + /** + * Return if an account has valid information for Direct debit payment + * + * @return int 1 if correct, <=0 if wrong + */ + function verif() + { + require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; - // Call function to check BAN - if (! checkBanForAccount($this)) + $this->error_number = 0; + + // Call function to check BAN + + if (! checkIbanForAccount($this) || ! checkSwiftForAccount($this)) + { + $this->error_number = 12; + $this->error_message = 'IBANSWIFTControlError'; + } + /*if (! checkBanForAccount($this)) { $this->error_number = 12; - $this->error_message = 'RIBControlError'; - } + $this->error_message = 'BANControlError'; + }*/ - if ($this->error_number == 0) - { - return 1; - } - else - { - return 0; - } - } + if ($this->error_number == 0) + { + return 1; + } + else + { + return 0; + } + } - /** - * Return account country code - * - * @return string country code - */ - function getCountryCode() - { - global $mysoc; + /** + * Return account country code + * + * @return string country code + */ + function getCountryCode() + { + global $mysoc; - // We return country code of bank account - if (! empty($this->country_code)) return $this->country_code; + // We return country code of bank account + if (! empty($this->country_code)) return $this->country_code; - // For backward compatibility, we try to guess country from other information - if (! empty($this->iban)) - { - // If IBAN defined, we can know country of account from it - if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; - } + // For backward compatibility, we try to guess country from other information + if (! empty($this->iban)) + { + // If IBAN defined, we can know country of account from it + if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; + } - // If this class is linked to a third party - if (! empty($this->socid)) - { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; - $company=new Societe($this->db); - $result=$company->fetch($this->socid); - if (! empty($company->country_code)) return $company->country_code; - } + // If this class is linked to a third party + if (! empty($this->socid)) + { + require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; + $company=new Societe($this->db); + $result=$company->fetch($this->socid); + if (! empty($company->country_code)) return $company->country_code; + } - // We return country code of managed company - if (! empty($mysoc->country_code)) return $mysoc->country_code; + // We return country code of managed company + if (! empty($mysoc->country_code)) return $mysoc->country_code; - return ''; - } + return ''; + } - /** - * Return if a bank account is defined with detailed information (bank code, desk code, number and key). - * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code - * - * @return int 0=No bank code need + Account number is enough - * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key - * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number - */ - function useDetailedBBAN() - { - $country_code=$this->getCountryCode(); + /** + * Return if a bank account is defined with detailed information (bank code, desk code, number and key). + * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code + * + * @return int 0=No bank code need + Account number is enough + * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key + * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number + */ + function useDetailedBBAN() + { + $country_code=$this->getCountryCode(); - if (in_array($country_code,array('CH','FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... - if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... - return 0; - } + if (in_array($country_code,array('CH','FR','ES','GA','IT','NC'))) return 1; // France, Spain, Gabon, ... + if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2; // Australia, England... + return 0; + } - /** - * Return 1 if IBAN / BIC is mandatory (otherwise option) - * - * @return int 1 = mandatory / 0 = Not mandatory - */ - function needIBAN() - { - $country_code=$this->getCountryCode(); + /** + * Return 1 if IBAN / BIC is mandatory (otherwise option) + * + * @return int 1 = mandatory / 0 = Not mandatory + */ + function needIBAN() + { + $country_code=$this->getCountryCode(); - $country_code_in_EEC=array( - 'AT', // Austria - 'BE', // Belgium - 'BG', // Bulgaria - 'CY', // Cyprus - 'CZ', // Czech republic - 'DE', // Germany - 'DK', // Danemark - 'EE', // Estonia - 'ES', // Spain - 'FI', // Finland - 'FR', // France - 'GB', // United Kingdom - 'GR', // Greece - 'HR', // Croatia - 'NL', // Holland - 'HU', // Hungary - 'IE', // Ireland - 'IM', // Isle of Man - Included in UK - 'IT', // Italy - 'LT', // Lithuania - 'LU', // Luxembourg - 'LV', // Latvia - 'MC', // Monaco - Included in France - 'MT', // Malta - //'NO', // Norway - 'PL', // Poland - 'PT', // Portugal - 'RO', // Romania - 'SE', // Sweden - 'SK', // Slovakia - 'SI', // Slovenia - 'UK', // United Kingdom - //'CH', // Switzerland - No. Swizerland in not in EEC - ); + $country_code_in_EEC=array( + 'AT', // Austria + 'BE', // Belgium + 'BG', // Bulgaria + 'CY', // Cyprus + 'CZ', // Czech republic + 'DE', // Germany + 'DK', // Danemark + 'EE', // Estonia + 'ES', // Spain + 'FI', // Finland + 'FR', // France + 'GB', // United Kingdom + 'GR', // Greece + 'HR', // Croatia + 'NL', // Holland + 'HU', // Hungary + 'IE', // Ireland + 'IM', // Isle of Man - Included in UK + 'IT', // Italy + 'LT', // Lithuania + 'LU', // Luxembourg + 'LV', // Latvia + 'MC', // Monaco - Included in France + 'MT', // Malta + //'NO', // Norway + 'PL', // Poland + 'PT', // Portugal + 'RO', // Romania + 'SE', // Sweden + 'SK', // Slovakia + 'SI', // Slovenia + 'UK', // United Kingdom + //'CH', // Switzerland - No. Swizerland in not in EEC + ); - if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ... - return 0; - } + if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ... + return 0; + } - /** - * Load miscellaneous information for tab "Info" - * - * @param int $id Id of object to load - * @return void - */ - function info($id) - { + /** + * Load miscellaneous information for tab "Info" + * + * @param int $id Id of object to load + * @return void + */ + function info($id) + { - } + } /** * Returns the fields in order that this bank account should show to the user @@ -1518,32 +1571,32 @@ class Account extends CommonObject } - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - $this->specimen = 1; - $this->ref = 'MBA'; - $this->label = 'My Big Company Bank account'; - $this->bank = 'MyBank'; - $this->courant = Account::TYPE_CURRENT; - $this->clos = Account::STATUS_OPEN; - $this->code_banque = '123'; - $this->code_guichet = '456'; - $this->number = 'ABC12345'; - $this->cle_rib = 50; - $this->bic = 'AA12'; - $this->iban = 'FR999999999'; - $this->domiciliation = 'My bank address'; - $this->proprio = 'Owner'; - $this->owner_address = 'Owner address'; - $this->country_id = 1; - } + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $this->specimen = 1; + $this->ref = 'MBA'; + $this->label = 'My Big Company Bank account'; + $this->bank = 'MyBank'; + $this->courant = Account::TYPE_CURRENT; + $this->clos = Account::STATUS_OPEN; + $this->code_banque = '123'; + $this->code_guichet = '456'; + $this->number = 'ABC12345'; + $this->cle_rib = 50; + $this->bic = 'AA12'; + $this->iban = 'FR999999999'; + $this->domiciliation = 'My bank address'; + $this->proprio = 'Owner'; + $this->owner_address = 'Owner address'; + $this->country_id = 1; + } } @@ -1553,122 +1606,122 @@ class Account extends CommonObject */ class AccountLine extends CommonObject { - var $error; - var $db; - var $element='bank'; - var $table_element='bank'; - var $picto = 'generic'; + var $error; + var $db; + var $element='bank'; + var $table_element='bank'; + var $picto = 'generic'; - var $id; - var $ref; - var $datec; - var $dateo; + var $id; + var $ref; + var $datec; + var $dateo; - /** - * Value date - */ - var $datev; - var $amount; - var $label; - var $note; - var $fk_user_author; - var $fk_user_rappro; - var $fk_type; - var $rappro; // Is it conciliated - var $num_releve; // If conciliated, what is bank statement - var $num_chq; // Num of cheque - var $bank_chq; // Bank of cheque - var $fk_bordereau; // Id of cheque receipt + /** + * Value date + */ + var $datev; + var $amount; + var $label; + var $note; + var $fk_user_author; + var $fk_user_rappro; + var $fk_type; + var $rappro; // Is it conciliated + var $num_releve; // If conciliated, what is bank statement + var $num_chq; // Num of cheque + var $bank_chq; // Bank of cheque + var $fk_bordereau; // Id of cheque receipt - var $fk_account; // Id of bank account - var $bank_account_label; // Label of bank account + var $fk_account; // Id of bank account + var $bank_account_label; // Label of bank account - public $emetteur; + public $emetteur; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct(DoliDB $db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct(DoliDB $db) + { + $this->db = $db; + } - /** - * Load into memory content of a bank transaction line - * - * @param int $rowid Id of bank transaction to load - * @param string $ref Ref of bank transaction to load - * @param string $num External num to load (ex: num of transaction for paypal fee) - * @return int <0 if KO, 0 if OK but not found, >0 if OK and found - */ - function fetch($rowid,$ref='',$num='') - { - global $conf; + /** + * Load into memory content of a bank transaction line + * + * @param int $rowid Id of bank transaction to load + * @param string $ref Ref of bank transaction to load + * @param string $num External num to load (ex: num of transaction for paypal fee) + * @return int <0 if KO, 0 if OK but not found, >0 if OK and found + */ + function fetch($rowid,$ref='',$num='') + { + global $conf; - // Check parameters - if (empty($rowid) && empty($ref) && empty($num)) return -1; + // Check parameters + if (empty($rowid) && empty($ref) && empty($num)) return -1; - $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; - $sql.= " b.fk_user_author, b.fk_user_rappro,"; - $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; - $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; - //$sql.= " b.author"; // Is this used ? - $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; - $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= " WHERE b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; - if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; - else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; - else $sql.= " AND b.rowid=".$rowid; + $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,"; + $sql.= " b.fk_user_author, b.fk_user_rappro,"; + $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,"; + $sql.= " b.fk_bordereau, b.banque, b.emetteur,"; + //$sql.= " b.author"; // Is this used ? + $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,"; + $sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'"; + else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'"; + else $sql.= " AND b.rowid=".$rowid; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $ret=0; + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $ret=0; - $obj = $this->db->fetch_object($result); - if ($obj) - { - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; - $this->ref = $obj->rowid; + $obj = $this->db->fetch_object($result); + if ($obj) + { + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->ref = $obj->rowid; - $this->datec = $obj->datec; - $this->datev = $obj->datev; - $this->dateo = $obj->dateo; - $this->amount = $obj->amount; - $this->label = $obj->label; - $this->note = $obj->note; + $this->datec = $obj->datec; + $this->datev = $obj->datev; + $this->dateo = $obj->dateo; + $this->amount = $obj->amount; + $this->label = $obj->label; + $this->note = $obj->note; - $this->fk_user_author = $obj->fk_user_author; - $this->fk_user_rappro = $obj->fk_user_rappro; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_rappro = $obj->fk_user_rappro; - $this->fk_type = $obj->fk_type; // Type of transaction - $this->rappro = $obj->rappro; - $this->num_releve = $obj->num_releve; + $this->fk_type = $obj->fk_type; // Type of transaction + $this->rappro = $obj->rappro; + $this->num_releve = $obj->num_releve; - $this->num_chq = $obj->num_chq; - $this->bank_chq = $obj->banque; - $this->fk_bordereau = $obj->fk_bordereau; + $this->num_chq = $obj->num_chq; + $this->bank_chq = $obj->banque; + $this->fk_bordereau = $obj->fk_bordereau; - $this->fk_account = $obj->fk_account; - $this->bank_account_ref = $obj->bank_account_ref; - $this->bank_account_label = $obj->bank_account_label; + $this->fk_account = $obj->fk_account; + $this->bank_account_ref = $obj->bank_account_ref; + $this->bank_account_label = $obj->bank_account_label; - $ret=1; - } - $this->db->free($result); - return $ret; - } - else - { - return -1; - } - } + $ret=1; + } + $this->db->free($result); + return $ret; + } + else + { + return -1; + } + } /** * Inserts a transaction to a bank account @@ -1719,420 +1772,420 @@ class AccountLine extends CommonObject return $this->id; } - /** - * Delete transaction bank line record - * - * @param User $user User object that delete - * @return int <0 if KO, >0 if OK - */ - function delete(User $user = null) - { - $nbko=0; + /** + * Delete transaction bank line record + * + * @param User $user User object that delete + * @return int <0 if KO, >0 if OK + */ + function delete(User $user = null) + { + $nbko=0; - if ($this->rappro) - { - // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; - return -1; - } + if ($this->rappro) + { + // Protection to avoid any delete of consolidated lines + $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + return -1; + } - $this->db->begin(); + $this->db->begin(); - // Delete urls - $result=$this->delete_urls($user); - if ($result < 0) - { - $nbko++; - } + // Delete urls + $result=$this->delete_urls($user); + if ($result < 0) + { + $nbko++; + } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - if (! $nbko) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -$nbko; - } - } + if (! $nbko) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -$nbko; + } + } - /** - * Delete bank line records - * - * @param User $user User object that delete - * @return int <0 if KO, >0 if OK - */ - function delete_urls(User $user = null) - { - $nbko=0; + /** + * Delete bank line records + * + * @param User $user User object that delete + * @return int <0 if KO, >0 if OK + */ + function delete_urls(User $user = null) + { + $nbko=0; - if ($this->rappro) - { - // Protection to avoid any delete of consolidated lines - $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; - return -1; - } + if ($this->rappro) + { + // Protection to avoid any delete of consolidated lines + $this->error="ErrorDeleteNotPossibleLineIsConsolidated"; + return -1; + } - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; - dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); - $result = $this->db->query($sql); - if (! $result) $nbko++; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid; + dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG); + $result = $this->db->query($sql); + if (! $result) $nbko++; - if (! $nbko) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -$nbko; - } - } + if (! $nbko) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -$nbko; + } + } - /** - * Update bank account record in database - * - * @param User $user Object user making update - * @param int $notrigger 0=Disable all triggers - * @return int <0 if KO, >0 if OK - */ - function update(User $user, $notrigger = 0) - { - $this->db->begin(); + /** + * Update bank account record in database + * + * @param User $user Object user making update + * @param int $notrigger 0=Disable all triggers + * @return int <0 if KO, >0 if OK + */ + function update(User $user, $notrigger = 0) + { + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " amount = ".price2num($this->amount).","; - $sql.= " datev='".$this->db->idate($this->datev)."',"; - $sql.= " dateo='".$this->db->idate($this->dateo)."'"; - $sql.= " WHERE rowid = ".$this->rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " amount = ".price2num($this->amount).","; + $sql.= " datev='".$this->db->idate($this->datev)."',"; + $sql.= " dateo='".$this->db->idate($this->dateo)."'"; + $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - $this->error=$this->db->error(); - return -1; - } - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + $this->error=$this->db->error(); + return -1; + } + } - /** - * Update conciliation field - * - * @param User $user Objet user making update - * @param int $cat Category id - * @return int <0 if KO, >0 if OK - */ - function update_conciliation(User $user, $cat) - { - global $conf; + /** + * Update conciliation field + * + * @param User $user Objet user making update + * @param int $cat Category id + * @return int <0 if KO, >0 if OK + */ + function update_conciliation(User $user, $cat) + { + global $conf; - $this->db->begin(); + $this->db->begin(); - // Check statement field - if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) - { - if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) - { - $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); - return -1; - } - } + // Check statement field + if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) + { + if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) + { + $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); + return -1; + } + } - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " rappro = 1"; - $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; - $sql.= ", fk_user_rappro = ".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " rappro = 1"; + $sql.= ", num_releve = '".$this->db->escape($this->num_releve)."'"; + $sql.= ", fk_user_rappro = ".$user->id; + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if (! empty($cat)) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; - $sql.= "lineid"; - $sql.= ", fk_categ"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$cat; - $sql.= ")"; + dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if (! empty($cat)) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class ("; + $sql.= "lineid"; + $sql.= ", fk_categ"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", ".$cat; + $sql.= ")"; - dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); - $this->db->query($sql); + dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG); + $this->db->query($sql); - // No error check. Can fail if category already affected - } + // No error check. Can fail if category already affected + } - $this->rappro=1; + $this->rappro=1; - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Increase/decrease value date of a rowid - * - * @param int $rowid Id of line - * @param int $sign 1 or -1 - * @return int >0 if OK, 0 if KO - */ - function datev_change($rowid,$sign=1) - { - $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); + /** + * Increase/decrease value date of a rowid + * + * @param int $rowid Id of line + * @param int $sign 1 or -1 + * @return int >0 if OK, 0 if KO + */ + function datev_change($rowid,$sign=1) + { + $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign); - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " datev = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " datev = '".$this->db->idate($newdate)."'"; + $sql.= " WHERE rowid = ".$rowid; - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->affected_rows($result)) - { - return 1; - } - } - else - { - dol_print_error($this->db); - return 0; - } - } - else dol_print_error($this->db); - return 0; - } + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->affected_rows($result)) + { + return 1; + } + } + else + { + dol_print_error($this->db); + return 0; + } + } + else dol_print_error($this->db); + return 0; + } - /** - * Increase value date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function datev_next($id) - { - return $this->datev_change($id,1); - } + /** + * Increase value date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function datev_next($id) + { + return $this->datev_change($id,1); + } - /** - * Decrease value date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function datev_previous($id) - { - return $this->datev_change($id,-1); - } + /** + * Decrease value date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function datev_previous($id) + { + return $this->datev_change($id,-1); + } - /** - * Increase/decrease operation date of a rowid - * - * @param int $rowid Id of line - * @param int $sign 1 or -1 - * @return int >0 if OK, 0 if KO - */ - function dateo_change($rowid,$sign=1) - { - $sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; - $resql = $this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $newdate=$this->db->jdate($obj->dateo)+(3600*24*$sign); + /** + * Increase/decrease operation date of a rowid + * + * @param int $rowid Id of line + * @param int $sign 1 or -1 + * @return int >0 if OK, 0 if KO + */ + function dateo_change($rowid,$sign=1) + { + $sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid; + $resql = $this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $newdate=$this->db->jdate($obj->dateo)+(3600*24*$sign); - $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; - $sql.= " dateo = '".$this->db->idate($newdate)."'"; - $sql.= " WHERE rowid = ".$rowid; + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; + $sql.= " dateo = '".$this->db->idate($newdate)."'"; + $sql.= " WHERE rowid = ".$rowid; - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->affected_rows($result)) - { - return 1; - } - } - else - { - dol_print_error($this->db); - return 0; - } - } - else dol_print_error($this->db); - return 0; - } + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->affected_rows($result)) + { + return 1; + } + } + else + { + dol_print_error($this->db); + return 0; + } + } + else dol_print_error($this->db); + return 0; + } - /** - * Increase operation date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function dateo_next($id) - { - return $this->dateo_change($id,1); - } + /** + * Increase operation date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function dateo_next($id) + { + return $this->dateo_change($id,1); + } - /** - * Decrease operation date of a rowid - * - * @param int $id Id of line to change - * @return int >0 if OK, 0 if KO - */ - function dateo_previous($id) - { - return $this->dateo_change($id,-1); - } + /** + * Decrease operation date of a rowid + * + * @param int $id Id of line to change + * @return int >0 if OK, 0 if KO + */ + function dateo_previous($id) + { + return $this->dateo_change($id,-1); + } - /** - * Load miscellaneous information for tab "Info" - * - * @param int $id Id of object to load - * @return void - */ - function info($id) - { - $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; - $sql.= ' b.fk_user_author, b.fk_user_rappro'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; - $sql.= ' WHERE b.rowid = '.$id; + /** + * Load miscellaneous information for tab "Info" + * + * @param int $id Id of object to load + * @return void + */ + function info($id) + { + $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; + $sql.= ' b.fk_user_author, b.fk_user_rappro'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b'; + $sql.= ' WHERE b.rowid = '.$id; - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; - if ($obj->fk_user_author) - { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } - if ($obj->fk_user_rappro) - { - $ruser = new User($this->db); - $ruser->fetch($obj->fk_user_rappro); - $this->user_rappro = $ruser; - } + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + if ($obj->fk_user_rappro) + { + $ruser = new User($this->db); + $ruser->fetch($obj->fk_user_rappro); + $this->user_rappro = $ruser; + } - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_modification = $this->db->jdate($obj->datem); - //$this->date_rappro = $obj->daterappro; // Not yet managed - } - $this->db->free($result); - } - else - { - dol_print_error($this->db); - } - } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + //$this->date_rappro = $obj->daterappro; // Not yet managed + } + $this->db->free($result); + } + else + { + dol_print_error($this->db); + } + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $maxlen Longueur max libelle - * @param string $option Option ('showall') - * @return string Chaine avec URL - */ - function getNomUrl($withpicto=0,$maxlen=0,$option='') - { - global $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlen Longueur max libelle + * @param string $option Option ('showall') + * @return string Chaine avec URL + */ + function getNomUrl($withpicto=0,$maxlen=0,$option='') + { + global $langs; - $result=''; - $label=$langs->trans("ShowTransaction").': '.$this->rowid; - $link = ''; - $linkend=''; + $result=''; + $label=$langs->trans("ShowTransaction").': '.$this->rowid; + $link = ''; + $linkend=''; - if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->rowid.$linkend; + if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->rowid.$linkend; - if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; - if ($option == 'showall') - { - $result.=$langs->trans("BankAccount").': '; - $accountstatic=new Account($this->db); - $accountstatic->id=$this->fk_account; - $accountstatic->ref=$this->bank_account_ref; - $accountstatic->label=$this->bank_account_label; - $result.=$accountstatic->getNomUrl(0).', '; - } - if ($option == 'showall' || $option == 'showconciliated') - { - $result.=$langs->trans("BankLineConciliated").': '; - $result.=yn($this->rappro); - } - if ($option == 'showall' || $option == 'showconciliated') $result.=')'; + if ($option == 'showall' || $option == 'showconciliated') $result.=' ('; + if ($option == 'showall') + { + $result.=$langs->trans("BankAccount").': '; + $accountstatic=new Account($this->db); + $accountstatic->id=$this->fk_account; + $accountstatic->ref=$this->bank_account_ref; + $accountstatic->label=$this->bank_account_label; + $result.=$accountstatic->getNomUrl(0).', '; + } + if ($option == 'showall' || $option == 'showconciliated') + { + $result.=$langs->trans("BankLineConciliated").': '; + $result.=yn($this->rappro); + } + if ($option == 'showall' || $option == 'showconciliated') $result.=')'; - return $result; - } + return $result; + } - /** - * Return label of status (activity, closed) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->status,$mode); - } + /** + * Return label of status (activity, closed) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long + * @return string Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } - /** - * Renvoi le libelle d'un statut donne - * - * @param int $statut Id statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut - */ - function LibStatut($statut,$mode=0) - { - global $langs; - //$langs->load('companies'); - /* + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + function LibStatut($statut,$mode=0) + { + global $langs; + //$langs->load('companies'); + /* if ($mode == 0) { if ($statut==0) return $langs->trans("ActivityCeased"); @@ -2163,7 +2216,7 @@ class AccountLine extends CommonObject if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); }*/ - } + } } diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index 40f06895792..2fca317d1c4 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -117,7 +117,7 @@ if ($id > 0 || !empty($ref)) { $totalsize+=$file['size']; } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index 12cfeda7b15..a813a71eeca 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -108,7 +108,7 @@ else dol_print_error($db); } if (empty($min)) $min = dol_now - 3600 * 24; - + $log="graph.php: min=".$min." max=".$max; dol_syslog($log); @@ -760,7 +760,7 @@ $head=bank_prepare_head($object); dol_fiche_head($head,'graph',$langs->trans("FinancialAccount"),0,'account'); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; if ($account) { diff --git a/htdocs/compta/bank/info.php b/htdocs/compta/bank/info.php index 15555e45338..832ec95dcd2 100644 --- a/htdocs/compta/bank/info.php +++ b/htdocs/compta/bank/info.php @@ -58,7 +58,7 @@ $h++; dol_fiche_head($head, $hselected, $langs->trans("LineRecord"), -1, 'account'); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); diff --git a/htdocs/compta/bank/ligne.php b/htdocs/compta/bank/ligne.php index c88220192ab..9266e65a872 100644 --- a/htdocs/compta/bank/ligne.php +++ b/htdocs/compta/bank/ligne.php @@ -152,7 +152,7 @@ if ($user->rights->banque->modifier && $action == "update") { $error++; } - + if (! $error) { $arrayofcategs=GETPOST('custcats', 'array'); @@ -175,8 +175,8 @@ if ($user->rights->banque->modifier && $action == "update") } // $arrayselected will be loaded after in page output } - } - + } + if (! $error) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); @@ -296,14 +296,14 @@ if ($result) print ''; dol_fiche_head($tabs, 0, $langs->trans('LineRecord'), 0, 'account'); - - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($bankline, 'rowid', $linkback); - - print '
      '; + + print '
      '; print '
      '; // Ref @@ -314,7 +314,7 @@ if ($result) print ''; print ''; */ - + $i++; // Bank account @@ -582,7 +582,7 @@ if ($result) if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) { $langs->load('categories'); - + // Bank line print '
      ' . fieldLabel('RubriquesTransactions', 'custcats') . ''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_BANK_LINE, null, 'parent', null, null, 1); @@ -591,28 +591,28 @@ if ($result) } print "
      "; - + dol_fiche_end(); - - + + print '

      '; - + print ""; - - + + // Releve rappro if ($acct->canBeConciliated() > 0) // Si compte rapprochable { print load_fiche_titre($langs->trans("Reconciliation"), '', 'title_bank.png'); print '
      '."\n"; - + print '
      '; print ''; print ''; print ''; print ''; - + print ''; print '"; @@ -652,13 +652,13 @@ if ($result) print '
      '.$langs->trans("Conciliation")."
      '; print '
      '; - + print ''; if ($backtopage) { print '   '; print ''; - } + } print '
      '; print '
      '; diff --git a/htdocs/compta/bank/index.php b/htdocs/compta/bank/list.php similarity index 98% rename from htdocs/compta/bank/index.php rename to htdocs/compta/bank/list.php index 4485680a4e9..0ecfe01498f 100644 --- a/htdocs/compta/bank/index.php +++ b/htdocs/compta/bank/list.php @@ -19,7 +19,7 @@ */ /** - * \file htdocs/compta/bank/index.php + * \file htdocs/compta/bank/list.php * \ingroup banque * \brief Home page of bank module */ @@ -103,7 +103,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); } } @@ -611,7 +611,7 @@ foreach ($accounts as $key=>$type) if (! empty($arrayfields['balance']['checked'])) { print '
      '; - print ''.price($solde, 0, $langs, 0, 0, -1, $obj->currency_code).''; + print ''.price($solde, 0, $langs, 0, 0, -1, $obj->currency_code).''; print '
      '; print ''; print ''; print ''; print ''; + print ''; print ''; $balancestart=array(); @@ -372,7 +445,20 @@ if (empty($numref)) } else { - print ''; + print ''; + print ''; // Calculate start amount $sql = "SELECT sum(b.amount) as amount"; @@ -402,11 +488,18 @@ if (empty($numref)) } print ''; + print ''; + print ''."\n"; } $i++; } print "
      '.$langs->trans("AccountStatement").''.$langs->trans("InitialBankBalance").''.$langs->trans("EndBankBalance").'
      '.$objp->numr.'
      '; + if ($action != 'editbankreceipt' || $objp->numr != $brref) + { + print ''.$objp->numr.''; + } + else + { + print ''; + print ''; + print ''; + print ''; + } + print ''.price(($balancestart[$objp->numr]+$content[$objp->numr]),'',$langs,1,-1,-1,$conf->currency).''; + if ($user->rights->banque->consolidate && $action != 'editbankreceipt') { + print 'numr.'">'.img_edit().''; + } + print '
      \n"; + print ''; print "\n
      \n"; } @@ -420,58 +513,6 @@ else /** * Show list of bank statements */ - $ve=$_GET["ve"]; - - // Define number of receipt to show (current, previous or next one ?) - $found=false; - if ($_GET["rel"] == 'prev') - { - // Recherche valeur pour num = numero releve precedent - $sql = "SELECT DISTINCT(b.num_releve) as num"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve < '".$db->escape($numref)."'"; - $sql.= " AND b.fk_account = ".$object->id; - $sql.= " ORDER BY b.num_releve DESC"; - - dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $numrows = $db->num_rows($resql); - if ($numrows > 0) - { - $obj = $db->fetch_object($resql); - $numref = $obj->num; - $found=true; - } - } - } - elseif ($_GET["rel"] == 'next') - { - // Recherche valeur pour num = numero releve precedent - $sql = "SELECT DISTINCT(b.num_releve) as num"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; - $sql.= " WHERE b.num_releve > '".$db->escape($numref)."'"; - $sql.= " AND b.fk_account = ".$object->id; - $sql.= " ORDER BY b.num_releve ASC"; - - dol_syslog("htdocs/compta/bank/releve.php", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $numrows = $db->num_rows($resql); - if ($numrows > 0) - { - $obj = $db->fetch_object($resql); - $numref = $obj->num; - $found=true; - } - } - } - else { - // On veut le releve num - $found=true; - } $mesprevnext=''; $mesprevnext.='
      '; } } @@ -2482,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 @@ -2526,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")) { @@ -2548,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 { @@ -2644,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) @@ -2668,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'); } @@ -2701,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 ''; } @@ -2710,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 @@ -2802,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) . ''; @@ -2897,12 +2905,12 @@ else if ($id > 0 || ! empty($ref)) $resteapayer = 0; $resteapayeraffiche = $resteapayer; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final 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)%' OR description LIKE '(EXCESS RECEIVED)%'))"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); @@ -2925,9 +2933,9 @@ else if ($id > 0 || ! empty($ref)) // Confirmation de la conversion de l'avoir en reduc if ($action == 'converttoreduc') { - if($object->type == 0) $type_fac = 'ExcessReceived'; - elseif($object->type == 2) $type_fac = 'CreditNote'; - elseif($object->type == 3) $type_fac = 'Deposit'; + if($object->type == Facture::TYPE_STANDARD) $type_fac = 'ExcessReceived'; + elseif($object->type == Facture::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; + elseif($object->type == Facture::TYPE_DEPOSIT) $type_fac = 'Deposit'; $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac))); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); } @@ -3171,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.='
      '; @@ -3251,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 ''; @@ -3493,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 ''; @@ -3560,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); @@ -3576,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 @@ -3594,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 @@ -3621,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 @@ -3667,161 +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 .= ' 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); - 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; + // 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; + + 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)) { @@ -3833,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') . ' 
      '; - $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 $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 '
      '; @@ -4072,10 +4084,10 @@ 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 '
      '; + print '
      '; print ''; // Show object lines @@ -4098,7 +4110,7 @@ else if ($id > 0 || ! empty($ref)) } print "
      \n"; - print "
      "; + print "
      "; print "\n"; @@ -4115,28 +4127,35 @@ else if ($id > 0 || ! empty($ref)) $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { // Editer une facture deja validee, sans paiement effectue et pas exporte en compta - if ($object->statut == 1) + if ($object->statut == Facture::STATUS_VALIDATED) { // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees $ventilExportCompta = $object->getVentilExportCompta(); - if ($resteapayer == $object->total_ttc && empty($object->paye) && $ventilExportCompta == 0) + if ($ventilExportCompta == 0) { - if (! $objectidnext && $object->is_last_in_cycle()) + if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) { - 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 (! $objectidnext && $object->is_last_in_cycle()) { - print ''; + 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 { + print '
      ' . $langs->trans('Modify') . '
      '; + } + } else if (!$object->is_last_in_cycle()) { + print '
      ' . $langs->trans('Modify') . '
      '; } else { - print '
      ' . $langs->trans('Modify') . '
      '; + print '
      ' . $langs->trans('Modify') . '
      '; } - } else if (!$object->is_last_in_cycle()) { - print '
      ' . $langs->trans('Modify') . '
      '; - } else { - print '
      ' . $langs->trans('Modify') . '
      '; } } + else + { + print '
      ' . $langs->trans('Modify') . '
      '; + } } $discount = new DiscountAbsolute($db); @@ -4147,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 { @@ -4158,9 +4177,9 @@ else if ($id > 0 || ! empty($ref)) } // Validate - if ($object->statut == 0 && 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 ($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 ''; } @@ -4181,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 @@ -4314,7 +4333,7 @@ else if ($id > 0 || ! empty($ref)) // Delete if ($user->rights->facture->supprimer) { - if (! $object->is_erasable()) { + if ($object->is_erasable() <= 0) { print ''; } else if ($objectidnext) { print ''; diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index e28d19b95b2..3d94595f558 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -305,16 +305,66 @@ class Invoices extends DolibarrApi } 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 } + * + * 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 * - * @url POST {id}/lines + * @url POST {id}/addline * * @return int */ @@ -331,14 +381,14 @@ class Invoices extends DolibarrApi if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - - $request_data = (object) $request_data; - + + $request_data = (object) $request_data; + // Reset fk_parent_line for no child products and special product if (($request_data->product_type != 9 && empty($request_data->fk_parent_line)) || $request_data->product_type == 9) { $request_data->fk_parent_line = 0; - } - + } + $updateRes = $this->invoice->addline( $request_data->desc, $request_data->subprice, @@ -371,14 +421,66 @@ 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.'); } /** - * Validate an order + * Sets an invoice as draft + * + * @param int $id Order ID + * @param int $idwarehouse Warehouse ID + * + * @url POST {id}/settodraft + * + * @return array + * + * @throws 200 + * @throws 304 + * @throws 401 + * @throws 404 + * @throws 500 + * + */ + function settodraft($id, $idwarehouse=-1) + { + 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); + } + + $result = $this->invoice->set_draft(DolibarrApiAccess::$user, $idwarehouse); + if ($result == 0) { + throw new RestException(304, 'Nothing done.'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + $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); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + + /** + * Validate an invoice * * @param int $id Order ID * @param int $idwarehouse Warehouse ID @@ -411,20 +513,82 @@ class Invoices extends DolibarrApi $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger); if ($result == 0) { - throw new RestException(500, 'Error nothing done. May be object is already validated'); + throw new RestException(304, 'Error nothing done. May be object is already validated'); } if ($result < 0) { throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error); } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')' - ) - ); + + $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); + } + + return $this->_cleanObjectDatas($this->invoice); + + } + /** + * Sets an invoice as paid + * + * @param int $id Order ID + * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple) + * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) + * + * @url POST {id}/settopaid + * + * @return array An invoice object + * + * @throws 200 + * @throws 304 + * @throws 401 + * @throws 404 + * @throws 500 + */ + function settopaid($id, $close_code='', $close_note='') + { + 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); + } + + $result = $this->invoice->set_paid(DolibarrApiAccess::$user, $close_code, $close_note); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + + $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); + } + + return $this->_cleanObjectDatas($this->invoice); + + + } + + /** * Clean sensible object datas * diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 7c6e0567c24..dd42c8d3fb7 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -262,8 +262,8 @@ class FactureRec extends CommonInvoice $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; //$sql.= ', el.fk_source'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')'; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; if ($rowid) $sql.= ' WHERE f.rowid='.$rowid; elseif ($ref) $sql.= " WHERE f.titre='".$this->db->escape($ref)."'"; @@ -823,6 +823,30 @@ class FactureRec extends CommonInvoice return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency); } + /** + * Return if maximum number of generation is reached + * + * @return boolean False by default, True if maximum number of generation is reached + */ + function isMaxNbGenReached() + { + $ret = false; + if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) $ret = true; + return $ret; + } + + /** + * Format string to output with by striking the string if max number of generation was reached + * + * @param string $ret Default value to output + * @return boolean False by default, True if maximum number of generation is reached + */ + function strikeIfMaxNbGenReached($ret) + { + // Special case to strike the date + return ($this->isMaxNbGenReached()?'':'').$ret.($this->isMaxNbGenReached()?'':''); + } + /** * Create all recurrents invoices (for all entities if multicompany is used). * A result may also be provided into this->output. diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index b6d294c6e18..6452c689215 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -351,22 +351,19 @@ class Facture extends CommonInvoice } // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) - $substitutionarray=array( - '__TOTAL_HT__' => price($this->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency_code), - '__TOTAL_TTC__' => price($this->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency_code), - '__INVOICE_PREVIOUS_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'), - '__INVOICE_MONTH__' => dol_print_date($this->date, '%m'), - '__INVOICE_NEXT_MONTH__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m'), - '__INVOICE_PREVIOUS_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B'), - '__INVOICE_MONTH_TEXT__' => dol_print_date($this->date, '%B'), - '__INVOICE_NEXT_MONTH_TEXT__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B'), - '__INVOICE_PREVIOUS_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y'), - '__INVOICE_YEAR__' => dol_print_date($this->date, '%Y'), - '__INVOICE_NEXT_YEAR__' => dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'), - // Only for tempalte invoice - '__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__' => dol_print_date($originaldatewhen, 'dayhour'), - '__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__' => dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour') - ); + $substitutionarray=getCommonSubstitutionArray($outputlangs, 0, null, $this); + $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m'); + $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m'); + $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m'); + $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B'); + $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B'); + $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B'); + $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y'); + $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y'); + $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'); + // Only for tempalte invoice + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour'); + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour'); //var_dump($substitutionarray);exit; @@ -1059,28 +1056,36 @@ class Facture extends CommonInvoice */ function getDirectExternalLink($withpicto=0) { + global $dolibarr_main_url_root; + // Define $urlwithroot $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $url='eee'; - return ''.$this->ref.''; + // TODO Read into ecmfile table to get entry and hash exists (PS: If not found, add it) + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($this->db); + //$result = $ecmfile->get(); + + $hashp='todo'; + return ''.$this->ref.''; } /** - * Return clicable link of object (with eventually picto) + * Return clicable link of object (with eventually picto) * - * @param int $withpicto Add picto into link - * @param string $option Where point the link - * @param int $max Maxlength of ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @param int $addlinktonotes 1=Add link to notes - * @return string String with URL + * @param int $withpicto Add picto into link + * @param string $option Where point the link + * @param int $max Maxlength of ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $addlinktonotes 1=Add link to notes + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='',$notooltip=0,$addlinktonotes=0) + function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $moretitle='', $notooltip=0, $addlinktonotes=0, $save_lastsearch_value=-1) { global $langs, $conf, $user, $form; @@ -1093,6 +1098,14 @@ class Facture extends CommonInvoice if ($short) return $url; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $picto='bill'; if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note @@ -1190,8 +1203,8 @@ class Facture extends CommonInvoice $sql.= ', f.fk_incoterms, f.location_incoterms'; $sql.= ", i.libelle as libelle_incoterms"; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid'; $sql.= ' WHERE f.entity = '.$conf->entity; if ($rowid) $sql.= " AND f.rowid=".$rowid; @@ -1730,20 +1743,24 @@ class Facture extends CommonInvoice * @param User $user User making the deletion. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @param int $idwarehouse Id warehouse to use for stock change. - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, 0=Refused, >0 if OK */ function delete($user, $notrigger=0, $idwarehouse=-1) { global $langs,$conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (empty($rowid)) $rowid=$this->id; + $rowid=$this->id; - dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); + dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG); - // TODO Test if there is at least one payment. If yes, refuse to delete. + // Test to avoid invoice deletion (allowed if draft) + $test = $this->is_erasable(); + + if ($test <= 0) return $test; $error=0; + $this->db->begin(); if (! $error && ! $notrigger) @@ -2065,7 +2082,7 @@ class Facture extends CommonInvoice * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK */ function validate($user, $force_number='', $idwarehouse=0, $notrigger=0) { @@ -2077,6 +2094,10 @@ class Facture extends CommonInvoice $error=0; dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse); + // Force to have object complete for checks + $this->fetch_thirdparty(); + $this->fetch_lines(); + // Check parameters if (! $this->brouillon) { @@ -2099,9 +2120,6 @@ class Facture extends CommonInvoice $this->db->begin(); - $this->fetch_thirdparty(); - $this->fetch_lines(); - // Check parameters if ($this->type == self::TYPE_REPLACEMENT) // si facture de remplacement { @@ -3160,6 +3178,7 @@ class Facture extends CommonInvoice //$sql.= ' WHERE pf.'.$field.' = 1'; $sql.= ' AND pf.'.$field2.' = p.rowid'; $sql.= ' AND p.fk_paiement = t.id'; + $sql.= ' AND t.entity IN (' . getEntity('c_paiement').')'; if ($filtertype) $sql.=" AND t.code='PRE'"; dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG); @@ -3206,6 +3225,8 @@ class Facture extends CommonInvoice if (! empty($conf->global->FACTURE_ADDON)) { + dol_syslog("Call getNextNumRef with FACTURE_ADDON = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->nom.", type=".$soc->typent_code, LOG_DEBUG); + $mybool=false; $file = $conf->global->FACTURE_ADDON.".php"; @@ -3349,40 +3370,49 @@ class Facture extends CommonInvoice /** * Return if an invoice can be deleted * Rule is: - * If hidden option INVOICE_CAN_ALWAYS_BE_REMOVED is on, we can - * If invoice has a definitive ref, is last, without payment and not dipatched into accountancy -> yes end of rule * If invoice is draft and ha a temporary ref -> yes + * If hidden option INVOICE_CAN_ALWAYS_BE_REMOVED is on, we can. If hidden option INVOICE_CAN_NEVER_BE_REMOVED is on, we can't. + * If invoice has a definitive ref, is last, without payment and not dipatched into accountancy -> yes end of rule * - * @return int <0 if KO, 0=no, 1=yes + * @return int <0 if KO, 0=no, >0=yes */ function is_erasable() { global $conf; - if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 1; + // we check if invoice is a temporary number (PROVxxxx) + $tmppart = substr($this->ref, 1, 4); + + if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined + { + return 1; + } + + if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 2; if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0; - // on verifie si la facture est en numerotation provisoire - $facref = substr($this->ref, 1, 4); + // TODO Test if there is at least one payment. If yes, refuse to delete. + // ... // If not a draft invoice and not temporary invoice - if ($facref != 'PROV') + if ($tmppart !== 'PROV') { + // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag). + if (empty($this->thirdparty)) $this->fetch_thirdparty(); + $maxfacnumber = $this->getNextNumRef($this->thirdparty,'last'); $ventilExportCompta = $this->getVentilExportCompta(); + // If there is no invoice into the reset range and not already dispatched, we can delete - if ($maxfacnumber == '' && $ventilExportCompta == 0) return 1; + if ($maxfacnumber == '' && $ventilExportCompta == 0) return 3; // If invoice to delete is last one and not already dispatched, we can delete - if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) return 1; + if ($maxfacnumber == $this->ref && $ventilExportCompta == 0) return 4; + if ($this->situation_cycle_ref) { $last = $this->is_last_in_cycle(); return $last; } } - else if ($this->statut == self::STATUS_DRAFT && $facref == 'PROV') // Si facture brouillon et provisoire - { - return 1; - } return 0; } @@ -3642,7 +3672,7 @@ class Facture extends CommonInvoice if (! $error) { // Force payment mode of invoice to withdraw - $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement'); + $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement', 'code', 'id', 1); if ($payment_mode_id > 0) { $result=$this->setPaymentMethods($payment_mode_id); 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/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index a34705c8476..bc13b0d5876 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -91,6 +91,7 @@ class PaymentTerm // extends CommonObject // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_payment_term("; $sql.= "rowid,"; + $sql.= "entity,"; $sql.= "code,"; $sql.= "sortorder,"; $sql.= "active,"; @@ -101,6 +102,7 @@ class PaymentTerm // extends CommonObject $sql.= "decalage"; $sql.= ") VALUES ("; $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; + $sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").","; $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'").","; @@ -165,6 +167,7 @@ class PaymentTerm // extends CommonObject global $langs; $sql = "SELECT"; $sql.= " t.rowid,"; + $sql.= " t.entity"; $sql.= " t.code,"; $sql.= " t.sortorder,"; @@ -178,6 +181,7 @@ class PaymentTerm // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.rowid = ".$id; + $sql.= " AND t.entity = " . getEntity('c_payment_term'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -227,6 +231,7 @@ class PaymentTerm // extends CommonObject $sql.= " t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.code = 'RECEP'"; + $sql.= " AND t.entity = " . getEntity('c_payment_term'); dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); $resql=$this->db->query($sql); @@ -255,9 +260,10 @@ class PaymentTerm // extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=null, $notrigger=0) - { - global $conf, $langs; + function update($user=null, $notrigger=0) + { + global $conf, $langs; + $error=0; // Clean parameters @@ -276,8 +282,8 @@ class PaymentTerm // extends CommonObject // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_payment_term SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_payment_term SET"; $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").","; $sql.= " sortorder=".(isset($this->sortorder)?$this->sortorder:"null").","; $sql.= " active=".(isset($this->active)?$this->active:"null").","; @@ -286,37 +292,38 @@ class PaymentTerm // extends CommonObject $sql.= " type_cdr=".(isset($this->type_cdr)?$this->type_cdr:"null").","; $sql.= " nbjour=".(isset($this->nbjour)?$this->nbjour:"null").","; $sql.= " decalage=".(isset($this->decalage)?$this->decalage:"null").""; - $sql.= " WHERE rowid=".$this->id; + $sql.= " WHERE rowid = " . $this->id; + $sql.= " AND entity = " . getEntity('c_payment_term'); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + $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 call a trigger. + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call 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 - } + // 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 + } } - // Commit or rollback + // 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); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); return -1*$error; @@ -326,7 +333,7 @@ class PaymentTerm // extends CommonObject $this->db->commit(); return 1; } - } + } /** @@ -342,7 +349,8 @@ class PaymentTerm // extends CommonObject $error=0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_payment_term"; - $sql.= " WHERE rowid=".$this->id; + $sql.= " WHERE rowid = " . $this->id; + $sql.= " AND t.entity = " . getEntity('c_payment_term'); $this->db->begin(); diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index 93b23834e9f..5ac71ef03ca 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -139,13 +139,13 @@ if ($id > 0 || ! empty($ref)) $head = facture_prepare_head($object); $totalpaye = $object->getSommePaiement(); - + dol_fiche_head($head, 'contact', $langs->trans('InvoiceCustomer'), -1, 'bill'); // Invoice content - - $linkback = '' . $langs->trans("BackToList") . ''; - + + $linkback = '' . $langs->trans("BackToList") . ''; + $morehtmlref='
      '; // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -186,11 +186,11 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
      '; - + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - + dol_banner_tab($object, 'ref', $linkback, 1, 'facnumber', 'ref', $morehtmlref, '', 0, '', '', 1); - + dol_fiche_end(); print '
      '; diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index 1ab0d7ceb93..fc824046a42 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -113,7 +113,7 @@ if ($id > 0 || ! empty($ref)) // Invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
      '; // Ref customer diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index 80912bffbad..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'); + } + } + } } @@ -969,31 +969,25 @@ if ($action == 'create') $note_private=GETPOST('note_private','none')?GETPOST('note_private','none'):$object->note_private; // Help of substitution key - $substitutionarray=array( - //'__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')', - //'__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')', - '__AMOUNT_EXCL_TAX__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')', - '__AMOUNT_VAT__' => $langs->trans("AmountVAT").' ('.$langs->trans("Example").': '.price($object->total_tva).')', - '__AMOUNT__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')', - '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%m').')', - '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%m').')', - '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'),'%m').')', - '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%B').')', - '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%B').')', - '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')', - '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'),'%Y').')', - '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%Y').')', - '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'),'%Y').')', - // Only on template invoices - '__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__' => $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')', - '__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__' => $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')', - ); - $substitutionarray['__(TransKey)__']=$langs->trans("TransKey"); + $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); + + $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%m').')'; + $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'm'),'%B').')'; + $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%B').')'; + $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'm'), '%B').')'; + $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, -1, 'y'),'%Y').')'; + $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($object->date,'%Y').')'; + $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date, 1, 'y'),'%Y').')'; + // Only on template invoices + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')'; + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')'; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
      '; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
      '; + $htmltext.=$key.' = '.$langs->trans($val).'
      '; } $htmltext.='
      '; @@ -1004,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 @@ -1089,7 +1083,7 @@ if ($action == 'create') print ""; - dol_fiche_end(); + dol_fiche_end(); $title = $langs->trans("ProductsAndServices"); @@ -1103,17 +1097,19 @@ if ($action == 'create') /* * Invoice lines */ + print '
      '; print ''; // 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"; + print '
      '; print ''; @@ -1129,9 +1125,9 @@ if ($action == 'create') print "\n"; print '
      '; - print '     '; - print ''; - print '
      '; + print '     '; + print ''; + print '
      '; print "\n"; } else @@ -1169,59 +1165,59 @@ else // Recurring invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref=''; 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 '"; @@ -1294,31 +1290,26 @@ else // Help of substitution key $dateexample=dol_now(); if (! empty($object->frequency) && ! empty($object->date_when)) $dateexample=$object->date_when; - $substitutionarray=array( - //'__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')', - //'__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->total_ttc).')', - '__AMOUNT_EXCL_TAX__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($object->total_ht).')', - '__AMOUNT_VAT__' => $langs->trans("AmountVAT").' ('.$langs->trans("Example").': '.price($object->total_tva).')', - '__AMOUNT__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($object->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').')', - // Only on template invoices - '__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__' => $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')', - '__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__' => $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')', - ); - $substitutionarray['__(TransKey)__']=$langs->trans("TransKey"); + + $substitutionarray = getCommonSubstitutionArray($langs, 2, null, $object); + + $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_MONTH__'] = $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')'; + $substitutionarray['__INVOICE_NEXT_MONTH__'] = $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')'; + $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')'; + $substitutionarray['__INVOICE_MONTH_TEXT__'] = $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')'; + $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')'; + $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')'; + $substitutionarray['__INVOICE_YEAR__'] = $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')'; + $substitutionarray['__INVOICE_NEXT_YEAR__'] = $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')'; + // Only on template invoices + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = $langs->trans("DateNextInvoiceBeforeGen").' ('.$langs->trans("Example").': '.dol_print_date($object->date_when, 'dayhour').')'; + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = $langs->trans("DateNextInvoiceAfterGen").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($object->date_when, $object->frequency, $object->unit_frequency),'dayhour').')'; $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
      '; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
      '; + $htmltext.=$key.' = '.$langs->trans($val).'
      '; } $htmltext.='
      '; @@ -1346,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 ''; @@ -1365,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 '
      '; /* @@ -1406,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 ''; @@ -1421,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'); + 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 ''; @@ -1439,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 ''; @@ -1460,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 '
      '; @@ -1523,32 +1514,34 @@ 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 '
      '; print ''; // 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"; + print '
      '; print "\n"; @@ -1577,13 +1570,13 @@ else else { print ''; - } - } + } + } } else { print ''; - } + } //} //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer) @@ -1601,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/info.php b/htdocs/compta/facture/info.php index fd43cc42982..49e5e77e7be 100644 --- a/htdocs/compta/facture/info.php +++ b/htdocs/compta/facture/info.php @@ -58,7 +58,7 @@ $totalpaye = $object->getSommePaiement(); // Invoice content -$linkback = '' . $langs->trans("BackToList") . ''; +$linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
      '; // Ref customer diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index e911f6eab74..c7c13b1628a 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.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'; @@ -116,30 +116,30 @@ $permissiondellink=$user->rights->facture->creer; // Used by the include of acti $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php $arrayfields=array( - 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>0), - 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>0), + 'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.tva'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>1), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>1), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>0), + 'f.fk_cond_reglement'=>array('label'=>$langs->trans("PaymentTerm"), 'checked'=>0), 'recurring'=>array('label'=>$langs->trans("RecurringInvoiceTemplate"), 'checked'=>1), - 'f.frequency'=>array('label'=>$langs->trans("Frequency"), 'checked'=>1), + 'f.frequency'=>array('label'=>$langs->trans("Frequency"), 'checked'=>1), 'f.unit_frequency'=>array('label'=>$langs->trans("FrequencyUnit"), 'checked'=>1), - 'f.nb_gen_done'=>array('label'=>$langs->trans("NbOfGenerationDone"), 'checked'=>1), - 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1), - 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>100), + 'f.nb_gen_done'=>array('label'=>$langs->trans("NbOfGenerationDoneShort"), 'checked'=>1), + 'f.date_last_gen'=>array('label'=>$langs->trans("DateLastGeneration"), 'checked'=>1), + 'f.date_when'=>array('label'=>$langs->trans("NextDateToExecution"), 'checked'=>1), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>100), 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -156,35 +156,35 @@ 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'; - // 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_payment_mode=''; - $search_payment_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_payment_mode=''; + $search_payment_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; @@ -241,29 +241,29 @@ if ($search_unit_frequency != '') $sql .= natural_search('f.unit_frequency', $se if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(f.date_last_gen, '%m') = '".$month."'"; } else if ($year > 0) { - $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; + $sql.= " AND f.date_last_gen BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_date_when > 0) { - if ($year_date_when > 0 && empty($day_date_when)) - $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; - else if ($year_date_when > 0 && ! empty($day_date_when)) - $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; + if ($year_date_when > 0 && empty($day_date_when)) + $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; + else if ($year_date_when > 0 && ! empty($day_date_when)) + $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; else $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'"; } else if ($year_date_when > 0) { - $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'"; + $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,12,false))."'"; } $nbtotalofrecords = ''; @@ -282,7 +282,7 @@ if ($resql) $num = $db->num_rows($resql); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); if ($socid) $param.='&socid='.urlencode($socid); if ($day) $param.='&day='.urlencode($day); @@ -306,9 +306,9 @@ if ($resql) // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); @@ -342,117 +342,117 @@ if ($resql) // Ref if (! empty($arrayfields['f.titre']['checked'])) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['f.total']['checked'])) { - // Amount net - print ''; - print ''; - print ''; + // Amount net + print ''; + print ''; + print ''; } if (! empty($arrayfields['f.tva']['checked'])) { - // Amount Vat - print ''; - print ''; - print ''; + // Amount Vat + print ''; + print ''; + print ''; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print ''; - print ''; - print ''; + // Amount + print ''; + print ''; + print ''; } if (! empty($arrayfields['f.fk_cond_reglement']['checked'])) { - // Payment term - print ''; - print $form->select_conditions_paiements($search_payment_term, 'search_payment_term', -1, 1, 1, 'maxwidth100'); - print ""; + // Payment term + print ''; + print $form->select_conditions_paiements($search_payment_term, 'search_payment_term', -1, 1, 1, 'maxwidth100'); + print ""; } if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - // Payment mode - print ''; - print $form->select_types_paiements($search_payment_mode, 'search_payment_mode', '', 0, 1, 1, 0, 1, 'maxwidth100'); - print ''; + // Payment mode + print ''; + print $form->select_types_paiements($search_payment_mode, 'search_payment_mode', '', 0, 1, 1, 0, 1, 'maxwidth100'); + print ''; } if (! empty($arrayfields['recurring']['checked'])) { - // Recurring or not - print ''; - print $form->selectyesno('search_recurring', $search_recurring, 1, false, 1); - print ''; + // Recurring or not + print ''; + print $form->selectyesno('search_recurring', $search_recurring, 1, false, 1); + print ''; } if (! empty($arrayfields['f.frequency']['checked'])) { - // Recurring or not - print ''; - print ''; - print ''; + // Recurring or not + print ''; + print ''; + print ''; } if (! empty($arrayfields['f.unit_frequency']['checked'])) { - // Frequency unit - print ''; - print ''; - print ''; + // Frequency unit + print ''; + print ''; + print ''; } if (! empty($arrayfields['f.nb_gen_done']['checked'])) { - // Nb generation - print ''; - print ''; + // Nb generation + print ''; + print ''; } // Date invoice if (! empty($arrayfields['f.date_last_gen']['checked'])) { - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; } // Date due if (! empty($arrayfields['f.date_when']['checked'])) { - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5); - print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year_date_when?$year_date_when:-1,'year_date_when',1, 20, 5); + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -461,20 +461,20 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print ''; - print ''; + print ''; + print ''; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print ''; - print ''; + print ''; + print ''; } // Status if (! empty($arrayfields['status']['checked'])) { - print ''; - print ''; + print ''; + print ''; } // Action column print ''; @@ -520,6 +520,8 @@ if ($resql) $invoicerectmp->frequency=$objp->frequency; $invoicerectmp->suspend=$objp->suspend; $invoicerectmp->unit_frequency=$objp->unit_frequency; + $invoicerectmp->nb_gen_max=$objp->nb_gen_max; + $invoicerectmp->nb_gen_done=$objp->nb_gen_done; print ''; @@ -588,10 +590,10 @@ if ($resql) } if (! empty($arrayfields['f.nb_gen_done']['checked'])) { - print ''; - print ($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : ''.$langs->trans('NA').''); - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + print ($objp->frequency ? $objp->nb_gen_done.($objp->nb_gen_max>0?' / '. $objp->nb_gen_max:'') : ''.$langs->trans('NA').''); + print ''; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['f.date_last_gen']['checked'])) { @@ -603,7 +605,7 @@ if ($resql) if (! empty($arrayfields['f.date_when']['checked'])) { print ''; - print ($objp->frequency ? dol_print_date($db->jdate($objp->date_when),'day') : ''.$langs->trans('NA').''); + print ($objp->frequency ? ($invoicerectmp->isMaxNbGenReached()?'':'').dol_print_date($db->jdate($objp->date_when),'day').($invoicerectmp->isMaxNbGenReached()?'':'') : ''.$langs->trans('NA').''); print ''; if (! $i) $totalarray['nbfield']++; } @@ -632,19 +634,19 @@ if ($resql) print ''; if ($user->rights->facture->creer) { - if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) - { + if (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) + { print ''; print $langs->trans("CreateBill").''; - } - else - { - print $langs->trans("DateIsNotEnough"); - } + } + else + { + print $langs->trans("DateIsNotEnough"); + } } else { - print " "; + print " "; } if (! $i) $totalarray['nbfield']++; print ""; @@ -656,9 +658,9 @@ if ($resql) } else { - $colspan=1; - foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } - print ''.$langs->trans("NoRecordFound").''; + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''.$langs->trans("NoRecordFound").''; } //var_dump($totalarray); diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 5a59b61e8a3..9241726aaec 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -95,8 +95,10 @@ $month_lim = GETPOST('month_lim','int'); $year_lim = GETPOST('year_lim','int'); $option = GETPOST('option'); -if ($option == 'late') $filter = 'paye:0'; -$filtre = GETPOST('filtre'); +if ($option == 'late') { + $search_status = '1'; +} +$filtre = GETPOST('filtre','alpha'); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -134,46 +136,46 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.facnumber'=>'Ref', - 'f.ref_client'=>'RefCustomer', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'f.note_public'=>'NotePublic', + 'f.facnumber'=>'Ref', + 'f.ref_client'=>'RefCustomer', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), - 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), - 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), - 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'dynamount_payed'=>array('label'=>$langs->trans("Received"), 'checked'=>0), - 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), - 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), + 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), + 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), + 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'dynamount_payed'=>array('label'=>$langs->trans("Received"), 'checked'=>0), + 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), + 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -193,44 +195,45 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests are required to be compatible with all browsers { - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_refcustomer=''; - $search_type=''; - $search_project=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_localtax1=''; - $search_montant_localtax2=''; - $search_montant_ttc=''; - $search_status=''; - $search_paymentmode=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $day=''; - $year=''; - $month=''; - $option=''; - $filter=''; - $day_lim=''; - $year_lim=''; - $month_lim=''; - $toselect=''; - $search_array_options=array(); + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_refcustomer=''; + $search_type=''; + $search_project=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_localtax1=''; + $search_montant_localtax2=''; + $search_montant_ttc=''; + $search_status=''; + $search_paymentmode=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $day=''; + $year=''; + $month=''; + $option=''; + $filter=''; + $day_lim=''; + $year_lim=''; + $month_lim=''; + $toselect=''; + $search_array_options=array(); } if (empty($reshook)) { $objectclass='Facture'; $objectlabel='Invoices'; - $permtoread = $user->rights->facture->lire; + $permtoread = $user->rights->facture->lire; + $permtocreate = $user->rights->facture->creer; $permtodelete = $user->rights->facture->supprimer; $uploaddir = $conf->facture->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; @@ -238,98 +241,98 @@ if (empty($reshook)) if ($massaction == 'withdrawrequest') { - $langs->load("withdrawals"); + $langs->load("withdrawals"); - if (!$user->rights->prelevement->bons->creer) - { - $error++; - setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); - } - else - { - //Checking error - $error = 0; + if (!$user->rights->prelevement->bons->creer) + { + $error++; + setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); + } + else + { + //Checking error + $error = 0; - $arrayofselected=is_array($toselect)?$toselect:array(); - $listofbills=array(); - foreach($arrayofselected as $toselectid) - { - $objecttmp=new Facture($db); - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $totalpaye = $objecttmp->getSommePaiement(); - $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); - $totaldeposits = $objecttmp->getSumDepositsUsed(); - $objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); - $listofbills[] = $objecttmp; - if($objecttmp->paye || $objecttmp->resteapayer==0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors'); - } else if($objecttmp->resteapayer<0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); - } - if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); - } + $arrayofselected=is_array($toselect)?$toselect:array(); + $listofbills=array(); + foreach($arrayofselected as $toselectid) + { + $objecttmp=new Facture($db); + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $totalpaye = $objecttmp->getSommePaiement(); + $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); + $totaldeposits = $objecttmp->getSumDepositsUsed(); + $objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits,'MT'); + $listofbills[] = $objecttmp; + if($objecttmp->paye || $objecttmp->resteapayer==0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors'); + } else if($objecttmp->resteapayer<0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); + } + if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); + } - $rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande"; - $rsql .= " , pfd.date_traite as date_traite"; - $rsql .= " , pfd.amount"; - $rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login"; - $rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - $rsql .= " , ".MAIN_DB_PREFIX."user as u"; - $rsql .= " WHERE fk_facture = ".$objecttmp->id; - $rsql .= " AND pfd.fk_user_demande = u.rowid"; - $rsql .= " AND pfd.traite = 0"; - $rsql .= " ORDER BY pfd.date_demande DESC"; + $rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande"; + $rsql .= " , pfd.date_traite as date_traite"; + $rsql .= " , pfd.amount"; + $rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login"; + $rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + $rsql .= " , ".MAIN_DB_PREFIX."user as u"; + $rsql .= " WHERE fk_facture = ".$objecttmp->id; + $rsql .= " AND pfd.fk_user_demande = u.rowid"; + $rsql .= " AND pfd.traite = 0"; + $rsql .= " ORDER BY pfd.date_demande DESC"; - $result_sql = $db->query($rsql); - if ($result_sql) - { - $numprlv = $db->num_rows($result_sql); - } + $result_sql = $db->query($rsql); + if ($result_sql) + { + $numprlv = $db->num_rows($result_sql); + } - if($numprlv>0){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); - } - if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ - $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); - } + if($numprlv>0){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); + } + if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ + $error++; + setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); + } - } - } + } + } - //Massive withdraw request - if(!empty($listofbills) && empty($error)) - { - $nbwithdrawrequestok=0; - foreach($listofbills as $aBill) - { - $db->begin(); - $result = $aBill->demande_prelevement($user, $aBill->resteapayer); - if ($result > 0) - { - $db->commit(); - $nbwithdrawrequestok++; - } - else - { + //Massive withdraw request + if(!empty($listofbills) && empty($error)) + { + $nbwithdrawrequestok=0; + foreach($listofbills as $aBill) + { + $db->begin(); + $result = $aBill->demande_prelevement($user, $aBill->resteapayer); + if ($result > 0) + { + $db->commit(); + $nbwithdrawrequestok++; + } + else + { - $db->rollback(); - setEventMessages($aBill->error, $aBill->errors, 'errors'); - } - } - if ($nbwithdrawrequestok > 0) - { - setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); - } - } - } + $db->rollback(); + setEventMessages($aBill->error, $aBill->errors, 'errors'); + } + } + if ($nbwithdrawrequestok > 0) + { + setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); + } + } + } } @@ -381,38 +384,38 @@ if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= ' AND f.entity IN ('.getEntity('facture').')'; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; -if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category; +if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category); if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; if ($userid) { - if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; - else $sql.=' AND f.fk_user_author = '.$userid; + if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL'; + else $sql.=' AND f.fk_user_author = '.$userid; } if ($filtre) { - $aFilter = explode(',', $filtre); - foreach ($aFilter as $filter) - { - $filt = explode(':', $filter); - $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]); - } + $aFilter = explode(',', $filtre); + foreach ($aFilter as $filter) + { + $filt = explode(':', $filter); + $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); + } } if ($search_ref) $sql .= natural_search('f.facnumber', $search_ref); if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); if ($search_type != '' && $search_type >= 0) { - if ($search_type == '0') $sql.=" AND f.type = 0"; // standard - if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement - if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note - if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit - if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma - if ($search_type == '5') $sql.=" AND f.type = 5"; // situation + if ($search_type == '0') $sql.=" AND f.type = 0"; // standard + if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement + if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note + if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit + if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma + if ($search_type == '5') $sql.=" AND f.type = 5"; // situation } if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); @@ -429,24 +432,24 @@ if ($search_montant_localtax2 != '') $sql.= natural_search('f.localtax2', $searc if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); if ($search_status != '' && $search_status >= 0) { - if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft - if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed - if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) - if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned + if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft + if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed + if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) + if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned } -if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode; +if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode); if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; } else if ($year > 0) { - $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($month_lim > 0) { @@ -462,25 +465,24 @@ else if ($year_lim > 0) $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,1,false))."' AND '".$db->idate(dol_get_last_day($year_lim,12,false))."'"; } if ($option == 'late') $sql.=" AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->client->warning_delay)."'"; -if ($filter == 'paye:0') $sql.= " AND f.fk_statut = 1"; if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) { - $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; + $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -489,22 +491,22 @@ $sql.=$hookmanager->resPrint; if (! $sall) { - $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; - $sql.= ' f.localtax1, f.localtax2,'; - $sql.= ' f.datef, f.date_lim_reglement,'; - $sql.= ' f.paye, f.fk_statut,'; - $sql.= ' f.datec, f.tms,'; - $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; - $sql.= ' state.code_departement, state.nom'; + $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; + $sql.= ' f.localtax1, f.localtax2,'; + $sql.= ' f.datef, f.date_lim_reglement,'; + $sql.= ' f.paye, f.fk_statut,'; + $sql.= ' f.datec, f.tms,'; + $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; + $sql.= ' state.code_departement, state.nom'; - foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by - { - $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); - } + foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by + { + $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + } } else { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); + $sql .= natural_search(array_keys($fieldstosearchall), $sall); } $sql.= ' ORDER BY '; @@ -525,55 +527,56 @@ $sql.= $db->plimit($limit+1,$offset); $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows($resql); + $num = $db->num_rows($resql); $arrayofselected=is_array($toselect)?$toselect:array(); - if ($socid) - { - $soc = new Societe($db); - $soc->fetch($socid); + if ($socid) + { + $soc = new Societe($db); + $soc->fetch($socid); if (empty($search_societe)) $search_societe = $soc->name; - } + } - $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + $param='&socid='.$socid; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.='&sall='.urlencode($sall); - if ($day) $param.='&day='.urlencode($day); - if ($month) $param.='&month='.urlencode($month); - if ($year) $param.='&year=' .urlencode($year); - if ($day_lim) $param.='&day_lim='.urlencode($day_lim); - if ($month_lim) $param.='&month_lim='.urlencode($month_lim); - if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); - if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); - if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); - if ($search_type != '') $param.='&search_type='.urlencode($search_type); - if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); - if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); - if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); - if ($search_product_category > 0) $param.='$search_product_category=' .urlencode($search_product_category); - if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($day) $param.='&day='.urlencode($day); + if ($month) $param.='&month='.urlencode($month); + if ($year) $param.='&year=' .urlencode($year); + if ($day_lim) $param.='&day_lim='.urlencode($day_lim); + if ($month_lim) $param.='&month_lim='.urlencode($month_lim); + if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); + if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); + if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); + if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); + if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); + if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); + if ($search_product_category > 0) $param.='$search_product_category=' .urlencode($search_product_category); + if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); + if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); + if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); + if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); + if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($option) $param.="&option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } $arrayofmassactions=array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'validate'=>$langs->trans("Validate"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); if ($conf->prelevement->enabled) { @@ -582,31 +585,31 @@ if ($resql) } if ($user->rights->facture->supprimer) { - //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - { - // mass deletion never possible on invoices on such situation - } - else - { - $arrayofmassactions['delete']=$langs->trans("Delete"); - } + //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) + if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) + { + // mass deletion never possible on invoices on such situation + } + else + { + $arrayofmassactions['delete']=$langs->trans("Delete"); + } } if ($massaction == 'presend') $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - $i = 0; - print '
      '."\n"; + $i = 0; + print ''."\n"; - if ($optioncss != '') print ''; - print ''; + if ($optioncss != '') print ''; + print ''; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit); @@ -620,14 +623,14 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; } - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } // If the user can view prospects other than his' - $moreforfilter=''; + $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); @@ -636,14 +639,14 @@ if ($resql) $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); $moreforfilter.='
      '; } - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { $moreforfilter.='
      '; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
      '; - } + } // If the user can view prospects other than his' if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { @@ -654,51 +657,51 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.='
      '; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; - if ($moreforfilter) - { + if ($moreforfilter) + { print '
      '; - print $moreforfilter; - print '
      '; - } + print $moreforfilter; + print '
      '; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
      '; - print ''."\n"; + print '
      '; + print '
      '."\n"; - // Filters lines - print ''; + // Filters lines + print ''; // Ref if (! empty($arrayfields['f.facnumber']['checked'])) { - print ''; + print ''; } // Ref customer if (! empty($arrayfields['f.ref_client']['checked'])) { - print ''; + print ''; } // Type if (! empty($arrayfields['f.type']['checked'])) { print ''; @@ -706,26 +709,26 @@ if ($resql) // Date invoice if (! empty($arrayfields['f.date']['checked'])) { - print ''; + print ''; } // Date due if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { - print ''; + print ''; } // Project if (! empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) @@ -739,98 +742,98 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print ''; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + print ''; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + print ''; } // Payment mode if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['f.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_localtax1']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_localtax2']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print ''; - } - if (! empty($arrayfields['rtp']['checked'])) - { - print ''; - } - // Extra fields + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print ''; + } + if (! empty($arrayfields['rtp']['checked'])) + { + print ''; + } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -839,360 +842,360 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['f.fk_statut']['checked'])) { - print ''; + print ''; } // Action column print ''; - print "\n"; + print ''; + print "\n"; - print ''; - if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'],$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'],$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; + print ''; + if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'],$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'],$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'],$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "\n"; - if ($num > 0) - { - $i=0; - $totalarray=array(); - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + if ($num > 0) + { + $i=0; + $totalarray=array(); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - $datelimit=$db->jdate($obj->datelimite); - $facturestatic->id=$obj->id; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - $facturestatic->statut=$obj->fk_statut; - $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); - $facturestatic->note_public=$obj->note_public; - $facturestatic->note_private=$obj->note_private; + $datelimit=$db->jdate($obj->datelimite); + $facturestatic->id=$obj->id; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + $facturestatic->statut=$obj->fk_statut; + $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); + $facturestatic->note_public=$obj->note_public; + $facturestatic->note_private=$obj->note_private; - $paiement = $facturestatic->getSommePaiement(); - $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); - $totaldeposits = $facturestatic->getSumDepositsUsed(); - $totalpay = $paiement + $totalcreditnotes + $totaldeposits; - $remaintopay = $obj->total_ttc - $totalpay; + $paiement = $facturestatic->getSommePaiement(); + $totalcreditnotes = $facturestatic->getSumCreditNotesUsed(); + $totaldeposits = $facturestatic->getSumDepositsUsed(); + $totalpay = $paiement + $totalcreditnotes + $totaldeposits; + $remaintopay = $obj->total_ttc - $totalpay; - print ''; - if (! empty($arrayfields['f.facnumber']['checked'])) - { - print ''; + if (! empty($arrayfields['f.facnumber']['checked'])) + { + print ''; + print ''; + print '
      '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; $listtype=array( - Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), - Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), - Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), - Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), - ); + Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), + Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), + Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), + Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), + ); //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); - print '
      '.$langs->trans("Late"); - print '
      '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); + print '
      '.$langs->trans("Late"); + print '
      '; - print ''; - print ''; + print ''; + print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); + print ''; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); - print ''; + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; - print ''; + print ''; - print ''; + print ''; - $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); - print $form->selectarray('search_status', $liststatus, $search_status, 1); - print ''; + $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print ''; $searchpicto=$form->showFilterButtons(); print $searchpicto; - print '
      '; + print '
      '; - print ''; + print '
      '; - print ''; + print ''; - print ''; - print ''; - print '
      '; - print $facturestatic->getNomUrl(1,'',200,0,'',0,1); - print empty($obj->increment)?'':' ('.$obj->increment.')'; - print ''; + print $facturestatic->getNomUrl(1,'',200,0,'',0,1); + print empty($obj->increment)?'':' ('.$obj->increment.')'; + print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->id; - print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); - print '
      '; + print '
      '; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->id; + print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir); + print '
      '; - print "\n"; - if (! $i) $totalarray['nbfield']++; - } + print "\n"; + if (! $i) $totalarray['nbfield']++; + } // Customer ref - if (! empty($arrayfields['f.ref_client']['checked'])) - { - print ''; - print $obj->ref_client; - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.ref_client']['checked'])) + { + print ''; + print $obj->ref_client; + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Type - if (! empty($arrayfields['f.type']['checked'])) - { - print ''; - print $facturestatic->getLibType(); - print ""; - if (! $i) $totalarray['nbfield']++; - } + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print ''; + print $facturestatic->getLibType(); + print ""; + if (! $i) $totalarray['nbfield']++; + } // Date - if (! empty($arrayfields['f.date']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->df),'day'); - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.date']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->df),'day'); + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Date limit - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) - { - print ''.dol_print_date($datelimit,'day'); - if ($facturestatic->hasDelay()) - { - print img_warning($langs->trans('Late')); - } - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Date limit + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) + { + print ''.dol_print_date($datelimit,'day'); + if ($facturestatic->hasDelay()) + { + print img_warning($langs->trans('Late')); + } + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Project - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - if ($obj->project_id > 0) - { - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - print $projectstatic->getNomUrl(1); - } - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Project + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + if ($obj->project_id > 0) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print $projectstatic->getNomUrl(1); + } + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->name=$obj->name; - $thirdpartystatic->client=$obj->client; - $thirdpartystatic->code_client=$obj->code_client; - $thirdpartystatic->email=$obj->email; - print $thirdpartystatic->getNomUrl(1,'customer'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - print $obj->town; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - print $obj->zip; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "".$obj->state_name."\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + $thirdpartystatic->id=$obj->socid; + $thirdpartystatic->name=$obj->name; + $thirdpartystatic->client=$obj->client; + $thirdpartystatic->code_client=$obj->code_client; + $thirdpartystatic->email=$obj->email; + print $thirdpartystatic->getNomUrl(1,'customer'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + print $obj->town; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + print $obj->zip; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "".$obj->state_name."\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Payment mode - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) - { - print ''; - $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Payment mode + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + print ''; + $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Amount HT - if (! empty($arrayfields['f.total_ht']['checked'])) - { - print ''.price($obj->total_ht)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['f.total_vat']['checked'])) - { - print ''.price($obj->total_vat)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount LocalTax1 - if (! empty($arrayfields['f.total_localtax1']['checked'])) - { - print ''.price($obj->total_localtax1)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; - $totalarray['totallocaltax1'] += $obj->total_localtax1; - } - // Amount LocalTax2 - if (! empty($arrayfields['f.total_localtax2']['checked'])) - { - print ''.price($obj->total_localtax2)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; - $totalarray['totallocaltax2'] += $obj->total_localtax2; - } - // Amount TTC - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - print ''.price($obj->total_ttc)."\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + // Amount HT + if (! empty($arrayfields['f.total_ht']['checked'])) + { + print ''.price($obj->total_ht)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['f.total_vat']['checked'])) + { + print ''.price($obj->total_vat)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount LocalTax1 + if (! empty($arrayfields['f.total_localtax1']['checked'])) + { + print ''.price($obj->total_localtax1)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; + $totalarray['totallocaltax1'] += $obj->total_localtax1; + } + // Amount LocalTax2 + if (! empty($arrayfields['f.total_localtax2']['checked'])) + { + print ''.price($obj->total_localtax2)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; + $totalarray['totallocaltax2'] += $obj->total_localtax2; + } + // Amount TTC + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + print ''.price($obj->total_ttc)."\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print ''.(! empty($totalpay)?price($totalpay,0,$langs):' ').''; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; - $totalarray['totalam'] += $totalpay; - } + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print ''.(! empty($totalpay)?price($totalpay,0,$langs):' ').''; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; + $totalarray['totalam'] += $totalpay; + } - if (! empty($arrayfields['rtp']['checked'])) - { - print ''.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').''; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; - $totalarray['totalrtp'] += $remaintopay; - } + if (! empty($arrayfields['rtp']['checked'])) + { + print ''.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').''; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; + $totalarray['totalrtp'] += $remaintopay; + } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['f.datec']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { - print ''; - print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); - print ""; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['f.datec']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { + print ''; + print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); + print ""; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->id, $arrayofselected)) $selected=1; - print ''; - } - print '' ; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->id, $arrayofselected)) $selected=1; + print ''; + } + print '' ; + if (! $i) $totalarray['nbfield']++; - print "\n"; + print "\n"; - $i++; - } + $i++; + } - // Show total line - if (isset($totalarray['totalhtfield']) + // Show total line + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totallocaltax1field']) || isset($totalarray['totallocaltax2field']) @@ -1200,62 +1203,62 @@ if ($resql) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) - { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; - else print ''.$langs->trans("Totalforthispage").''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; - elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; - elseif ($totalarray['totallocaltax1field'] == $i) print ''.price($totalarray['totallocaltax1']).''; - elseif ($totalarray['totallocaltax2field'] == $i) print ''.price($totalarray['totallocaltax2']).''; - elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; - elseif ($totalarray['totalamfield'] == $i) print ''.price($totalarray['totalam']).''; - elseif ($totalarray['totalrtpfield'] == $i) print ''.price($totalarray['totalrtp']).''; - else print ''; - } - print ''; + { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; + else print ''.$langs->trans("Totalforthispage").''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; + elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; + elseif ($totalarray['totallocaltax1field'] == $i) print ''.price($totalarray['totallocaltax1']).''; + elseif ($totalarray['totallocaltax2field'] == $i) print ''.price($totalarray['totallocaltax2']).''; + elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; + elseif ($totalarray['totalamfield'] == $i) print ''.price($totalarray['totalam']).''; + elseif ($totalarray['totalrtpfield'] == $i) print ''.price($totalarray['totalrtp']).''; + else print ''; + } + print ''; - } - } + } + } - $db->free($resql); + $db->free($resql); $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print "\n"; - print '
      '; + print '
      '; - print "\n"; + print "\n"; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->lire; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->lire; - print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
      '.$langs->trans("ShowTempMassFilesArea").''; - } + print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
      '.$langs->trans("ShowTempMassFilesArea").''; + } } else { - dol_print_error($db); + dol_print_error($db); } llxFooter(); diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index 223480e4ba8..3428ccddd4b 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -74,14 +74,14 @@ if ($id > 0 || ! empty($ref)) $object->fetch_thirdparty(); $head = facture_prepare_head($object); - + $totalpaye = $object->getSommePaiement(); - + dol_fiche_head($head, 'note', $langs->trans("InvoiceCustomer"), -1, 'bill'); // Invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
      '; // Ref customer @@ -130,8 +130,8 @@ if ($id > 0 || ! empty($ref)) print '
      '; print '
      '; - - + + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index e9b1694808b..9f2245d38a5 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -151,7 +151,7 @@ if ($object->id > 0) // Invoice content - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
      '; // Ref customer @@ -425,28 +425,28 @@ if ($object->id > 0) print ''.$langs->trans("RIB").''; print $object->thirdparty->display_rib(); print ''; - + print ''; print '
      '; print '
      '; print '
      '; print '
      '; - + print ''; - + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print ''; print ''; print ''; - + // Multicurrency Amount VAT print ''; print ''; print ''; - + // Multicurrency Amount TTC print ''; print ''; @@ -507,16 +507,16 @@ if ($object->id > 0) // TODO Replace this by an include with same code to show already done payment visible in invoice card 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('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)) . '
      '.$langs->trans('RemainderToPay').''.price($resteapayer, 1, '', 1, - 1, - 1, $conf->currency).'
      '; - + print '
      '; print '
      '; print '
      '; print '
      '; - - + + dol_fiche_end(); @@ -612,7 +612,7 @@ if ($object->id > 0) while ($i < $num) { $obj = $db->fetch_object($result_sql); - + print ''; print ''.dol_print_date($db->jdate($obj->date_demande),'day')."\n"; @@ -640,7 +640,7 @@ if ($object->id > 0) } // Closed requests - + $sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande,"; $sql.= " pfd.date_traite, pfd.fk_prelevement_bons, pfd.amount,"; $sql.= " pb.ref,"; @@ -663,7 +663,7 @@ if ($object->id > 0) while ($i < $num) { $obj = $db->fetch_object($result); - + print ''; diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index bf54e4f58ab..d85255fbf4e 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -74,7 +74,7 @@ if ($mode == 'customer') if ($mode == 'supplier') { $title=$langs->trans("BillsStatisticsSuppliers"); - $dir=$conf->fournisseur->dir_output.'/facture/temp'; + $dir=$conf->fournisseur->facture->dir_temp; } print load_fiche_titre($title, $mesg, 'title_accountancy.png'); @@ -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.php b/htdocs/compta/paiement.php index 7a494113090..866529fd5dd 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -251,7 +251,7 @@ if (empty($reshook)) $paiement->datepaye = $datepaye; $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching - $paiement->paiementid = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement'); + $paiement->paiementid = dol_getIdFromCode($db,GETPOST('paiementcode'),'c_paiement','code','id',1); $paiement->num_paiement = GETPOST('num_paiement'); $paiement->note = GETPOST('comment'); @@ -526,21 +526,19 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie * List of unpaid invoices */ - $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type, '; + $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type,'; $sql.= ' f.datef as df, f.fk_soc as socid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - - if(!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS)) { - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON (f.fk_soc = s.rowid)'; - } - - $sql.= ' WHERE f.entity = '.$conf->entity; + $sql.= ' WHERE f.entity IN ('.getEntity('facture', $conf->entity).')'; $sql.= ' AND (f.fk_soc = '.$facture->socid; - + // Can pay invoices of all child of parent company if(!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) { $sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')'; } - + // Can pay invoices of all child of myself + if(!empty($conf->global->FACTURE_PAYMENTS_ON_SUBSIDIARY_COMPANIES)){ + $sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->id.')'; + } $sql.= ') AND f.paye = 0'; $sql.= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled if ($facture->type != 2) @@ -831,7 +829,8 @@ if (! GETPOST('action','aZ09')) $sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p, '.MAIN_DB_PREFIX.'facture as f, '.MAIN_DB_PREFIX.'c_paiement as c'; $sql.= ' WHERE p.fk_facture = f.rowid AND p.fk_paiement = c.id'; - $sql.= ' AND f.entity = '.$conf->entity; + $sql.= ' AND f.entity IN (' . getEntity('facture').')'; + $sql.= ' AND c.entity IN (' . getEntity('c_paiement').')'; if ($socid) { $sql.= ' AND f.fk_soc = '.$socid; diff --git a/htdocs/compta/paiement/avalider.php b/htdocs/compta/paiement/avalider.php index 370fbdfdd05..4c7fafe4429 100644 --- a/htdocs/compta/paiement/avalider.php +++ b/htdocs/compta/paiement/avalider.php @@ -71,7 +71,8 @@ if ($socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON pf.fk_facture = f.rowid"; } $sql.= " WHERE p.fk_paiement = c.id"; -$sql.= " AND p.entity = ".$conf->entity; +$sql.= " AND p.entity = " . $conf->entity; +$sql.= " AND c.entity = " . getEntity('c_paiement'); if ($socid) { $sql.= " AND f.fk_soc = ".$socid; diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 808d2cbb00b..3458e6bc82a 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -36,7 +36,7 @@ class RemiseCheque extends CommonObject public $element='chequereceipt'; public $table_element='bordereau_cheque'; public $picto = 'payment'; - + var $num; var $intitule; //! Numero d'erreur Plage 1024-1279 @@ -345,7 +345,7 @@ class RemiseCheque extends CommonObject $this->errno = 0; $this->db->begin(); - + $numref = $this->getNextNumRef(); if ($this->errno == 0 && $numref) @@ -481,10 +481,10 @@ class RemiseCheque extends CommonObject /** - * Load indicators for dashboard (this->nbtodo and this->nbtodolate) - * - * @param User $user Objet user - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @param User $user Objet user + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ function load_board($user) { @@ -533,6 +533,45 @@ class RemiseCheque extends CommonObject } + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 if ko, >0 if ok + */ + function load_state_board() + { + global $user; + + if ($user->societe_id) return -1; // protection pour eviter appel par utilisateur externe + + $sql = "SELECT count(b.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; + $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; + $sql.= " WHERE b.fk_account = ba.rowid"; + $sql.= " AND ba.entity IN (".getEntity('bank_account').")"; + $sql.= " AND b.fk_type = 'CHQ'"; + $sql.= " AND b.amount > 0"; + + $resql=$this->db->query($sql); + if ($resql) + { + + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["cheques"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + + /** * Build document * @@ -716,7 +755,7 @@ class RemiseCheque extends CommonObject * * @param int $bank_id Id of bank transaction line concerned * @param date $rejection_date Date to use on the negative payment - * @return int Id of negative payment line created + * @return int Id of negative payment line created */ function rejectCheck($bank_id, $rejection_date) { @@ -727,19 +766,19 @@ class RemiseCheque extends CommonObject $bankline = new AccountLine($db); $bankline->fetch($bank_id); - + /* Conciliation is allowed because when check is returned, a new line is created onto bank transaction log. if ($bankline->rappro) { $this->error='ActionRefusedLineAlreadyConciliated'; return -1; }*/ - + $this->db->begin(); - + // Not conciliated, we can delete it - //$bankline->delete($user); // We delete - + //$bankline->delete($user); // We delete + $bankaccount = $payment->fk_account; // Get invoices list to reopen them @@ -753,7 +792,7 @@ class RemiseCheque extends CommonObject $rejectedPayment = new Paiement($db); $rejectedPayment->amounts = array(); $rejectedPayment->datepaye = $rejection_date; - $rejectedPayment->paiementid = dol_getIdFromCode($this->db, 'CHQ', 'c_paiement'); + $rejectedPayment->paiementid = dol_getIdFromCode($this->db, 'CHQ', 'c_paiement','code','id',1); $rejectedPayment->num_paiement = $payment->numero; while($obj = $db->fetch_object($resql)) diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php index d08b6c734cc..76c52215281 100644 --- a/htdocs/compta/paiement/cheque/list.php +++ b/htdocs/compta/paiement/cheque/list.php @@ -203,7 +203,7 @@ if ($resql) // Bank print ''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; else print ' '; print ''; diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 594cd1e03cb..10d1f0fa884 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -93,6 +93,7 @@ class Paiement extends CommonObject $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid '; $sql.= ' WHERE p.fk_paiement = c.id'; + $sql.= ' AND c.entity IN (' . getEntity('c_paiement').')'; if ($id > 0) $sql.= ' AND p.rowid = '.$id; else if ($ref) diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php index dd03cb86df9..b7b0b0489e2 100644 --- a/htdocs/compta/paiement/list.php +++ b/htdocs/compta/paiement/list.php @@ -119,7 +119,8 @@ if (GETPOST("orphelins")) $sql.= " ".MAIN_DB_PREFIX."c_paiement as c)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; $sql.= " WHERE p.fk_paiement = c.id"; - $sql.= " AND p.entity = ".$conf->entity; + $sql.= " AND p.entity = " . $conf->entity; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " AND pf.fk_facture IS NULL"; // Add where from hooks $parameters=array(); @@ -150,7 +151,8 @@ else $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; } $sql.= " WHERE p.fk_paiement = c.id"; - $sql.= " AND p.entity = ".$conf->entity; + $sql.= " AND p.entity = " . $conf->entity; + $sql.= " AND c.entity = " . getEntity('c_paiement'); if (! $user->rights->societe->client->voir && ! $socid) { $sql.= " AND sc.fk_user = " .$user->id; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index bd262eaa675..e966eba4a47 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -60,18 +60,21 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes if (! $_POST["paiementtype"] > 0) { - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")); + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")), null, 'errors'); $error++; + $action = 'create'; } if ($datepaye == '') { - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("Date")); + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("Date")), null, 'errors'); $error++; + $action = 'create'; } if (! empty($conf->banque->enabled) && ! $_POST["accountid"] > 0) { - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("AccountToCredit")); + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("AccountToCredit")), null, 'errors'); $error++; + $action = 'create'; } if (! $error) @@ -91,7 +94,8 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes if (count($amounts) <= 0) { $error++; - $errmsg='ErrorNoPaymentDefined'; + setEventMessages($langs->trans("ErrorNoPaymentDefined"), null, 'errors'); + $action='create'; } if (! $error) @@ -112,18 +116,20 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes $paymentid = $paiement->create($user, (GETPOST('closepaidcontrib')=='on'?1:0)); if ($paymentid < 0) { - $errmsg=$paiement->error; - $error++; + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action='create'; } } if (! $error) { - $result=$paiement->addPaymentToBank($user,'payment_sc','(SocialContributionPayment)',$_POST['accountid'],'',''); - if (! $result > 0) + $result=$paiement->addPaymentToBank($user,'payment_sc','(SocialContributionPayment)', GETPOST('accountid','int'),'',''); + if (! ($result > 0)) { - $errmsg=$paiement->error; - $error++; + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action='create'; } } @@ -141,7 +147,6 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes } } - $_GET["action"]='create'; } @@ -164,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"; @@ -183,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"; @@ -202,12 +219,8 @@ if ($action == 'create') $sumpaid = $obj->total; $db->free(); } - print ''; - print ''; - - print ''; - print "'; - print ''; + /*print ''; + print '';*/ print ''; @@ -289,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/payment_sc/card.php b/htdocs/compta/payment_sc/card.php index 45762ed95bb..ea9bc5af42a 100644 --- a/htdocs/compta/payment_sc/card.php +++ b/htdocs/compta/payment_sc/card.php @@ -44,10 +44,10 @@ if ($user->societe_id) $socid=$user->societe_id; // TODO ajouter regle pour restreindre acces paiement //$result = restrictedArea($user, 'facture', $id,''); -$paiement = new PaymentSocialContribution($db); -if ($id > 0) +$object = new PaymentSocialContribution($db); +if ($id > 0) { - $result=$paiement->fetch($id); + $result=$object->fetch($id); if (! $result) dol_print_error($db,'Failed to get payment id '.$id); } @@ -61,7 +61,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->tax->char { $db->begin(); - $result = $paiement->delete($user); + $result = $object->delete($user); if ($result > 0) { $db->commit(); @@ -70,7 +70,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->tax->char } else { - setEventMessages($paiement->error, $paiement->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); } } @@ -80,8 +80,8 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->tax->char { $db->begin(); - $result=$paiement->valide(); - + $result=$object->valide(); + if ($result > 0) { $db->commit(); @@ -103,12 +103,12 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->tax->char } } - header('Location: card.php?id='.$paiement->id); + header('Location: card.php?id='.$object->id); exit; } else { - setEventMessages($paiement->error, $paiement->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); } } @@ -137,15 +137,15 @@ $h++; */ -dol_fiche_head($head, $hselected, $langs->trans("PaymentSocialContribution"), 0, 'payment'); +dol_fiche_head($head, $hselected, $langs->trans("PaymentSocialContribution"), -1, 'payment'); /* * Deletion confirmation of payment */ if ($action == 'delete') { - print $form->formconfirm('card.php?id='.$paiement->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete','',0,2); - + print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete','',0,2); + } /* @@ -154,41 +154,49 @@ if ($action == 'delete') if ($action == 'valide') { $facid = $_GET['facid']; - print $form->formconfirm('card.php?id='.$paiement->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); - + print $form->formconfirm('card.php?id='.$object->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); + } +$linkback = '' . $langs->trans("BackToList") . ''; + +dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'id', ''); + + +print '
      '; +print '
      '; + 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"]); @@ -266,7 +279,7 @@ if ($action == 'create') { $objp = $charge; - + print '
      '; // Ref -print ''; +/*print ''; print ''; +print $form->showrefnav($object,'id','',1,'rowid','id'); +print '';*/ // Date -print ''; +print ''; // Mode -print ''; +print ''; // Numero -print ''; +print ''; // Montant -print ''; +print ''; // Note -print ''; +print ''; // Bank account if (! empty($conf->banque->enabled)) { - if ($paiement->bank_account) + if ($object->bank_account) { $bankline=new AccountLine($db); - $bankline->fetch($paiement->bank_line); + $bankline->fetch($object->bank_line); print ''; print ''; @@ -201,6 +209,10 @@ if (! empty($conf->banque->enabled)) print '
      '.$langs->trans('Ref').'
      '.$langs->trans('Ref').''; -print $form->showrefnav($paiement,'id','',1,'rowid','id'); -print '
      '.$langs->trans('Date').''.dol_print_date($paiement->datep,'day').'
      '.$langs->trans('Date').''.dol_print_date($object->datep,'day').'
      '.$langs->trans('Mode').''.$langs->trans("PaymentType".$paiement->type_code).'
      '.$langs->trans('Mode').''.$langs->trans("PaymentType".$object->type_code).'
      '.$langs->trans('Numero').''.$paiement->num_paiement.'
      '.$langs->trans('Numero').''.$object->num_paiement.'
      '.$langs->trans('Amount').''.price($paiement->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
      '.$langs->trans('Amount').''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
      '.$langs->trans('Note').''.nl2br($paiement->note).'
      '.$langs->trans('Note').''.nl2br($object->note).'
      '.$langs->trans('BankTransactionLine').'
      '; +print '
      '; + +dol_fiche_end(); + /* * List of social contributions payed @@ -211,7 +223,7 @@ $sql = 'SELECT f.rowid as scid, f.libelle, f.paye, f.amount as sc_amount, pf.amo $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementcharge as pf,'.MAIN_DB_PREFIX.'chargesociales as f, '.MAIN_DB_PREFIX.'c_chargesociales as pc'; $sql.= ' WHERE pf.fk_charge = f.rowid AND f.fk_type = pc.id'; $sql.= ' AND f.entity = '.$conf->entity; -$sql.= ' AND pf.rowid = '.$paiement->id; +$sql.= ' AND pf.rowid = '.$object->id; dol_syslog("compta/payment_sc/card.php", LOG_DEBUG); $resql=$db->query($sql); @@ -239,7 +251,7 @@ if ($resql) { $objp = $db->fetch_object($resql); - + print ''; // Ref print ''; @@ -268,7 +280,7 @@ if ($resql) $i++; } } - + print "\n"; $db->free($resql); @@ -278,7 +290,6 @@ else dol_print_error($db); } -dol_fiche_end(); /* @@ -289,7 +300,7 @@ print '
      '; /* if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { - if ($user->societe_id == 0 && $paiement->statut == 0 && $_GET['action'] == '') + if ($user->societe_id == 0 && $object->statut == 0 && $_GET['action'] == '') { if ($user->rights->facture->paiement) { @@ -299,7 +310,7 @@ if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) } */ -if ($_GET['action'] == '') +if ($action == '') { if ($user->rights->tax->charges->supprimer) { diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index a3d50d58143..188b0236e5f 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -42,417 +42,418 @@ class BonPrelevement extends CommonObject public $table_element='prelevement_bons'; public $picto = 'payment'; - var $date_echeance; - var $raison_sociale; - var $reference_remise; - var $emetteur_code_guichet; - var $emetteur_numero_compte; - var $emetteur_code_banque; - var $emetteur_number_key; + var $date_echeance; + var $raison_sociale; + var $reference_remise; + var $emetteur_code_guichet; + var $emetteur_numero_compte; + var $emetteur_code_banque; + var $emetteur_number_key; - var $emetteur_iban; - var $emetteur_bic; - var $emetteur_ics; + var $emetteur_iban; + var $emetteur_bic; + var $emetteur_ics; - var $total; - var $_fetched; - var $statut; // 0-Wait, 1-Trans, 2-Done - var $labelstatut=array(); + var $total; + var $_fetched; + var $statut; // 0-Wait, 1-Trans, 2-Done + var $labelstatut=array(); - var $invoice_in_error=array(); + var $invoice_in_error=array(); + var $thirdparty_in_error=array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param string $filename Filename of withdraw receipt - */ - function __construct($db, $filename='') - { - global $conf,$langs; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $filename Filename of withdraw receipt + */ + function __construct($db, $filename='') + { + global $conf,$langs; - $error = 0; - $this->db = $db; + $error = 0; + $this->db = $db; - $this->filename=$filename; + $this->filename=$filename; - $this->date_echeance = time(); - $this->raison_sociale = ""; - $this->reference_remise = ""; + $this->date_echeance = time(); + $this->raison_sociale = ""; + $this->reference_remise = ""; - $this->emetteur_code_guichet = ""; - $this->emetteur_numero_compte = ""; - $this->emetteur_code_banque = ""; - $this->emetteur_number_key = ""; + $this->emetteur_code_guichet = ""; + $this->emetteur_numero_compte = ""; + $this->emetteur_code_banque = ""; + $this->emetteur_number_key = ""; - $this->emetteur_iban = ""; - $this->emetteur_bic = ""; - $this->emetteur_ics = ""; + $this->emetteur_iban = ""; + $this->emetteur_bic = ""; + $this->emetteur_ics = ""; - $this->factures = array(); + $this->factures = array(); - $this->methodes_trans = array(); + $this->methodes_trans = array(); - $this->methodes_trans[0] = "Internet"; + $this->methodes_trans[0] = "Internet"; - $this->_fetched = 0; + $this->_fetched = 0; - $langs->load("withdrawals"); - $this->labelstatut[0]=$langs->trans("StatusWaiting"); - $this->labelstatut[1]=$langs->trans("StatusTrans"); - $this->labelstatut[2]=$langs->trans("StatusCredited"); + $langs->load("withdrawals"); + $this->labelstatut[0]=$langs->trans("StatusWaiting"); + $this->labelstatut[1]=$langs->trans("StatusTrans"); + $this->labelstatut[2]=$langs->trans("StatusCredited"); - return 1; - } + return 1; + } - /** - * Add invoice to withdrawal - * - * @param int $facture_id id invoice to add - * @param int $client_id id invoice customer - * @param string $client_nom customer name - * @param int $amount amount of invoice - * @param string $code_banque code of bank withdrawal - * @param string $code_guichet code of bank's office - * @param string $number bank account number - * @param string $number_key number key of account number - * @return int >0 if OK, <0 if KO - */ - function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) - { - $result = 0; - $line_id = 0; + /** + * Add invoice to withdrawal + * + * @param int $facture_id id invoice to add + * @param int $client_id id invoice customer + * @param string $client_nom customer name + * @param int $amount amount of invoice + * @param string $code_banque code of bank withdrawal + * @param string $code_guichet code of bank's office + * @param string $number bank account number + * @param string $number_key number key of account number + * @return int >0 if OK, <0 if KO + */ + function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) + { + $result = 0; + $line_id = 0; - $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key); + $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key); - if ($result == 0) - { - if ($line_id > 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ("; - $sql.= "fk_facture"; - $sql.= ",fk_prelevement_lignes"; - $sql.= ") VALUES ("; - $sql.= $facture_id; - $sql.= ", ".$line_id; - $sql.= ")"; + if ($result == 0) + { + if ($line_id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture ("; + $sql.= "fk_facture"; + $sql.= ",fk_prelevement_lignes"; + $sql.= ") VALUES ("; + $sql.= $facture_id; + $sql.= ", ".$line_id; + $sql.= ")"; - if ($this->db->query($sql)) - { - $result = 0; - } - else - { - $result = -1; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - } - else - { - $result = -2; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } - } - else - { - $result = -3; - dol_syslog(get_class($this)."::AddFacture Erreur $result"); - } + if ($this->db->query($sql)) + { + $result = 0; + } + else + { + $result = -1; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } + } + else + { + $result = -2; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } + } + else + { + $result = -3; + dol_syslog(get_class($this)."::AddFacture Erreur $result"); + } - return $result; + return $result; - } + } - /** - * Add line to withdrawal - * - * @param int $line_id id line to add - * @param int $client_id id invoice customer - * @param string $client_nom customer name - * @param int $amount amount of invoice - * @param string $code_banque code of bank withdrawal - * @param string $code_guichet code of bank's office - * @param string $number bank account number - * @param string $number_key number key of account number - * @return int >0 if OK, <0 if KO - */ - function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) - { - $result = -1; - $concat = 0; + /** + * Add line to withdrawal + * + * @param int $line_id id line to add + * @param int $client_id id invoice customer + * @param string $client_nom customer name + * @param int $amount amount of invoice + * @param string $code_banque code of bank withdrawal + * @param string $code_guichet code of bank's office + * @param string $number bank account number + * @param string $number_key number key of account number + * @return int >0 if OK, <0 if KO + */ + function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key) + { + $result = -1; + $concat = 0; - if ($concat == 1) - { - /* + if ($concat == 1) + { + /* * We aggregate the lines */ - $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; - $sql.= " AND fk_soc =".$client_id; - $sql.= " AND code_banque ='".$code_banque."'"; - $sql.= " AND code_guichet ='".$code_guichet."'"; - $sql.= " AND number ='".$number."'"; + $sql = "SELECT rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; + $sql.= " AND fk_soc =".$client_id; + $sql.= " AND code_banque ='".$code_banque."'"; + $sql.= " AND code_guichet ='".$code_guichet."'"; + $sql.= " AND number ='".$number."'"; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - } - else - { - $result = -1; - } - } - else - { - /* + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + } + else + { + $result = -1; + } + } + else + { + /* * No aggregate */ - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes ("; - $sql.= "fk_prelevement_bons"; - $sql.= ", fk_soc"; - $sql.= ", client_nom"; - $sql.= ", amount"; - $sql.= ", code_banque"; - $sql.= ", code_guichet"; - $sql.= ", number"; - $sql.= ", cle_rib"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".$client_id; - $sql.= ", '".$this->db->escape($client_nom)."'"; - $sql.= ", '".price2num($amount)."'"; - $sql.= ", '".$code_banque."'"; - $sql.= ", '".$code_guichet."'"; - $sql.= ", '".$number."'"; - $sql.= ", '".$number_key."'"; - $sql.= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes ("; + $sql.= "fk_prelevement_bons"; + $sql.= ", fk_soc"; + $sql.= ", client_nom"; + $sql.= ", amount"; + $sql.= ", code_banque"; + $sql.= ", code_guichet"; + $sql.= ", number"; + $sql.= ", cle_rib"; + $sql.= ") VALUES ("; + $sql.= $this->id; + $sql.= ", ".$client_id; + $sql.= ", '".$this->db->escape($client_nom)."'"; + $sql.= ", '".price2num($amount)."'"; + $sql.= ", '".$code_banque."'"; + $sql.= ", '".$code_guichet."'"; + $sql.= ", '".$number."'"; + $sql.= ", '".$number_key."'"; + $sql.= ")"; - if ($this->db->query($sql)) - { - $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); - $result = 0; - } - else - { - dol_syslog(get_class($this)."::addline Error -2"); - $result = -2; - } + if ($this->db->query($sql)) + { + $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); + $result = 0; + } + else + { + dol_syslog(get_class($this)."::addline Error -2"); + $result = -2; + } - } + } - return $result; - } + return $result; + } - /** - * Return error string - * - * @param int $error Id of error - * @return string Error string - */ - function getErrorString($error) - { - global $langs; + /** + * Return error string + * + * @param int $error Id of error + * @return string Error string + */ + function getErrorString($error) + { + global $langs; - $errors = array(); + $errors = array(); - $errors[1027] = $langs->trans("DateInvalid"); + $errors[1027] = $langs->trans("DateInvalid"); - return $errors[abs($error)]; - } + return $errors[abs($error)]; + } - /** - * Get object and lines from database - * - * @param int $rowid Id of object to load - * @param string $ref Ref of direct debit - * @return int >0 if OK, <0 if KO - */ - function fetch($rowid, $ref='') - { - global $conf; + /** + * Get object and lines from database + * + * @param int $rowid Id of object to load + * @param string $ref Ref of direct debit + * @return int >0 if OK, <0 if KO + */ + function fetch($rowid, $ref='') + { + global $conf; - $sql = "SELECT p.rowid, p.ref, p.amount, p.note"; - $sql.= ", p.datec as dc"; - $sql.= ", p.date_trans as date_trans"; - $sql.= ", p.method_trans, p.fk_user_trans"; - $sql.= ", p.date_credit as date_credit"; - $sql.= ", p.fk_user_credit"; - $sql.= ", p.statut"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql.= " WHERE p.entity = ".$conf->entity; - if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid; - else $sql.= " AND p.ref = '".$this->db->escape($ref)."'"; + $sql = "SELECT p.rowid, p.ref, p.amount, p.note"; + $sql.= ", p.datec as dc"; + $sql.= ", p.date_trans as date_trans"; + $sql.= ", p.method_trans, p.fk_user_trans"; + $sql.= ", p.date_credit as date_credit"; + $sql.= ", p.fk_user_credit"; + $sql.= ", p.statut"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + if ($rowid > 0) $sql.= " AND p.rowid = ".$rowid; + else $sql.= " AND p.ref = '".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->amount = $obj->amount; - $this->note = $obj->note; - $this->datec = $this->db->jdate($obj->dc); + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->amount = $obj->amount; + $this->note = $obj->note; + $this->datec = $this->db->jdate($obj->dc); - $this->date_trans = $this->db->jdate($obj->date_trans); - $this->method_trans = $obj->method_trans; - $this->user_trans = $obj->fk_user_trans; + $this->date_trans = $this->db->jdate($obj->date_trans); + $this->method_trans = $obj->method_trans; + $this->user_trans = $obj->fk_user_trans; - $this->date_credit = $this->db->jdate($obj->date_credit); - $this->user_credit = $obj->fk_user_credit; + $this->date_credit = $this->db->jdate($obj->date_credit); + $this->user_credit = $obj->fk_user_credit; - $this->statut = $obj->statut; + $this->statut = $obj->statut; - $this->_fetched = 1; + $this->_fetched = 1; - return 0; - } - else - { - dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee"); - return -1; - } - } - else - { - return -2; - } - } + return 0; + } + else + { + dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee"); + return -1; + } + } + else + { + return -2; + } + } - /** - * Set credite and set status of linked invoices. Still used ?? - * - * @return int <0 if KO, >=0 if OK - */ - function set_credite() - { - global $user,$conf; + /** + * Set credite and set status of linked invoices. Still used ?? + * + * @return int <0 if KO, >=0 if OK + */ + function set_credite() + { + global $user,$conf; - $error = 0; + $error = 0; - if ($this->db->begin()) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql.= " SET statut = 1"; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + if ($this->db->begin()) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; + $sql.= " SET statut = 1"; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; - $result=$this->db->query($sql); - if (! $result) - { - dol_syslog(get_class($this)."::set_credite Erreur 1"); - $error++; - } + $result=$this->db->query($sql); + if (! $result) + { + dol_syslog(get_class($this)."::set_credite Erreur 1"); + $error++; + } - if (! $error) - { - $facs = array(); - $facs = $this->getListInvoices(); + if (! $error) + { + $facs = array(); + $facs = $this->getListInvoices(); - $num=count($facs); - for ($i = 0; $i < $num; $i++) - { - /* Tag invoice as payed */ - dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); - $fac = new Facture($this->db); - $fac->fetch($facs[$i]); - $result = $fac->set_paid($user); - } - } + $num=count($facs); + for ($i = 0; $i < $num; $i++) + { + /* Tag invoice as payed */ + dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); + $fac = new Facture($this->db); + $fac->fetch($facs[$i]); + $result = $fac->set_paid($user); + } + } - if (! $error) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " SET statut = 2"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; + if (! $error) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " SET statut = 2"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; - if (! $this->db->query($sql)) - { - dol_syslog(get_class($this)."::set_credite Erreur 1"); - $error++; - } - } + if (! $this->db->query($sql)) + { + dol_syslog(get_class($this)."::set_credite Erreur 1"); + $error++; + } + } - /* + /* * End of procedure */ - if (! $error) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::set_credite ROLLBACK "); + if (! $error) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::set_credite ROLLBACK "); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible "); - return -2; - } - } + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_credite Ouverture transaction SQL impossible "); + return -2; + } + } - /** - * Set direct debit order to "credited" status. - * - * @param User $user Id of user - * @param int $date date of action - * @return int >0 if OK, <0 if KO - */ - function set_infocredit($user, $date) - { - global $conf,$langs; + /** + * Set direct debit order to "credited" status. + * + * @param User $user Id of user + * @param int $date date of action + * @return int >0 if OK, <0 if KO + */ + function set_infocredit($user, $date) + { + global $conf,$langs; - $error = 0; + $error = 0; - if ($this->_fetched == 1) - { - if ($date >= $this->date_trans) - { - if ($this->db->begin()) - { - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; - $sql.= " SET fk_user_credit = ".$user->id; - $sql.= ", statut = 2"; - $sql.= ", date_credit = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid=".$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND statut = 1"; + if ($this->_fetched == 1) + { + if ($date >= $this->date_trans) + { + if ($this->db->begin()) + { + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; + $sql.= " SET fk_user_credit = ".$user->id; + $sql.= ", statut = 2"; + $sql.= ", date_credit = '".$this->db->idate($date)."'"; + $sql.= " WHERE rowid=".$this->id; + $sql.= " AND entity = ".$conf->entity; + $sql.= " AND statut = 1"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) + { - $langs->load('withdrawals'); - $subject = $langs->trans("InfoCreditSubject", $this->ref); - $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour')); + $langs->load('withdrawals'); + $subject = $langs->trans("InfoCreditSubject", $this->ref); + $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date,'dayhour')); - //Add payment of withdrawal into bank - $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; - $facs = array(); - $amounts = array(); - $amountsperthirdparty = array(); + //Add payment of withdrawal into bank + $bankaccount = $conf->global->PRELEVEMENT_ID_BANKACCOUNT; + $facs = array(); + $amounts = array(); + $amountsperthirdparty = array(); - $facs = $this->getListInvoices(1); + $facs = $this->getListInvoices(1); - // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) - $num=count($facs); - for ($i = 0; $i < $num; $i++) - { - $fac = new Facture($this->db); - $fac->fetch($facs[$i][0]); - $amounts[$fac->id] = $facs[$i][1]; - $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; + // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) + $num=count($facs); + for ($i = 0; $i < $num; $i++) + { + $fac = new Facture($this->db); + $fac->fetch($facs[$i][0]); + $amounts[$fac->id] = $facs[$i][1]; + $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; $totalpaye = $fac->getSommePaiement(); $totalcreditnotes = $fac->getSumCreditNotesUsed(); @@ -462,462 +463,477 @@ class BonPrelevement extends CommonObject if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) { $result = $fac->set_paid($user); } - } + } - // Make one payment per customer - foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) - { - $paiement = new Paiement($this->db); - $paiement->datepaye = $date; - $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice - $paiement->paiementid = 3; // - $paiement->num_paiement = $this->ref; // Set ref of direct debit note + // Make one payment per customer + foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) + { + $paiement = new Paiement($this->db); + $paiement->datepaye = $date; + $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice + $paiement->paiementid = 3; // + $paiement->num_paiement = $this->ref; // Set ref of direct debit note $paiement->id_prelevement = $this->id; - $paiement_id = $paiement->create($user); - if ($paiement_id < 0) - { - dol_syslog(get_class($this)."::set_infocredit AddPayment Error"); - $error++; - } - else - { - $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'',''); - if ($result < 0) - { - dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error"); - $error++; - } - } - //var_dump($paiement->amounts); - //var_dump($thirdpartyid); - //var_dump($cursoramounts); - } + $paiement_id = $paiement->create($user); + if ($paiement_id < 0) + { + dol_syslog(get_class($this)."::set_infocredit AddPayment Error"); + $error++; + } + else + { + $result=$paiement->addPaymentToBank($user,'payment','(WithdrawalPayment)',$bankaccount,'',''); + if ($result < 0) + { + dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error"); + $error++; + } + } + //var_dump($paiement->amounts); + //var_dump($thirdpartyid); + //var_dump($cursoramounts); + } // Update withdrawal line - // TODO: Translate to ligneprelevement.class.php - $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; - $sql.= " SET statut = 2"; - $sql.= " WHERE fk_prelevement_bons = ".$this->id; + // TODO: Translate to ligneprelevement.class.php + $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes"; + $sql.= " SET statut = 2"; + $sql.= " WHERE fk_prelevement_bons = ".$this->id; - if (! $this->db->query($sql)) - { - dol_syslog(get_class($this)."::set_infocredit Update lines Error"); - $error++; - } + if (! $this->db->query($sql)) + { + dol_syslog(get_class($this)."::set_infocredit Update lines Error"); + $error++; + } - } - else - { - dol_syslog(get_class($this)."::set_infocredit Update Bons Error"); - $error++; - } + } + else + { + dol_syslog(get_class($this)."::set_infocredit Update Bons Error"); + $error++; + } - /* + /* * End of procedure */ - if ($error == 0) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog("bon-prelevment::set_infocredit ROLLBACK "); - return -1; - } - } - else - { - dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible "); - return -1025; - } - } - else - { - dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans "); - return -1027; - } - } - else - { - return -1026; - } - } + if ($error == 0) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog("bon-prelevment::set_infocredit ROLLBACK "); + return -1; + } + } + else + { + dol_syslog(get_class($this)."::set_infocredit 1025 Open SQL transaction impossible "); + return -1025; + } + } + else + { + dol_syslog("bon-prelevment::set_infocredit 1027 Date de credit < Date de trans "); + return -1027; + } + } + else + { + return -1026; + } + } - /** - * Set withdrawal to transmited status - * - * @param User $user id of user - * @param int $date date of action - * @param string $method method of transmision to bank - * @return int >0 if OK, <0 if KO - */ - function set_infotrans($user, $date, $method) - { - global $conf,$langs; + /** + * Set withdrawal to transmited status + * + * @param User $user id of user + * @param int $date date of action + * @param string $method method of transmision to bank + * @return int >0 if OK, <0 if KO + */ + function set_infotrans($user, $date, $method) + { + global $conf,$langs; - $error = 0; + $error = 0; - dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO); - if ($this->db->begin()) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; - $sql.= " SET fk_user_trans = ".$user->id; - $sql.= " , date_trans = '".$this->db->idate($date)."'"; - $sql.= " , method_trans = ".$method; - $sql.= " , statut = 1"; - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND statut = 0"; + dol_syslog(get_class($this)."::set_infotrans Start",LOG_INFO); + if ($this->db->begin()) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; + $sql.= " SET fk_user_trans = ".$user->id; + $sql.= " , date_trans = '".$this->db->idate($date)."'"; + $sql.= " , method_trans = ".$method; + $sql.= " , statut = 1"; + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; + $sql.= " AND statut = 0"; - if ($this->db->query($sql)) - { - $this->method_trans = $method; - $langs->load('withdrawals'); - $subject = $langs->trans("InfoTransSubject", $this->ref); - $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname)); - $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day')); + if ($this->db->query($sql)) + { + $this->method_trans = $method; + $langs->load('withdrawals'); + $subject = $langs->trans("InfoTransSubject", $this->ref); + $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname)); + $message .=$langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date,'day')); - // TODO Call trigger to create a notification using notification module - } - else - { - $error++; - } + // TODO Call trigger to create a notification using notification module + } + else + { + $error++; + } - if ($error == 0) - { - $this->db->commit(); - return 0; - } - else - { - $this->db->rollback(); - dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR); + if ($error == 0) + { + $this->db->commit(); + return 0; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR); - return -1; - } - } - else - { + return -1; + } + } + else + { - dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT); - return -2; - } - } + dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT); + return -2; + } + } - /** - * Get invoice list - * - * @param int $amounts If you want to get the amount of the order for each invoice - * @return array Id of invoices - */ - private function getListInvoices($amounts=0) - { - global $conf; + /** + * Get invoice list + * + * @param int $amounts If you want to get the amount of the order for each invoice + * @return array Id of invoices + */ + private function getListInvoices($amounts=0) + { + global $conf; - $arr = array(); + $arr = array(); - /* + /* * Returns all invoices presented * within a withdrawal receipt */ - $sql = "SELECT fk_facture"; - if ($amounts) $sql .= ", SUM(pl.amount)"; - $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; - $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid"; - $sql.= " AND pl.fk_prelevement_bons = p.rowid"; - $sql.= " AND p.rowid = ".$this->id; - $sql.= " AND p.entity = ".$conf->entity; - if ($amounts) $sql.= " GROUP BY fk_facture"; + $sql = "SELECT fk_facture"; + if ($amounts) $sql .= ", SUM(pl.amount)"; + $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; + $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; + $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; + $sql.= " WHERE pf.fk_prelevement_lignes = pl.rowid"; + $sql.= " AND pl.fk_prelevement_bons = p.rowid"; + $sql.= " AND p.rowid = ".$this->id; + $sql.= " AND p.entity = ".$conf->entity; + if ($amounts) $sql.= " GROUP BY fk_facture"; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); - if ($num) - { - $i = 0; - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - if (!$amounts) $arr[$i] = $row[0]; - else - { - $arr[$i] = array( - $row[0], - $row[1] - ); - } - $i++; - } - } - $this->db->free($resql); - } - else - { - dol_syslog(get_class($this)."::getListInvoices Erreur"); - } - - return $arr; - } - - /** - * Returns amount of withdrawal - * - * @return double Total amount - */ - function SommeAPrelever() - { - global $conf; - - $sql = "SELECT sum(pfd.amount) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp"; - $sql.= " WHERE f.fk_statut = 1"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND f.rowid = pfd.fk_facture"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - - $resql = $this->db->query($sql); - if ( $resql ) - { - $obj = $this->db->fetch_object($resql); - - $this->db->free($resql); - - return $obj->nb; - } - else - { - $error = 1; - dol_syslog(get_class($this)."::SommeAPrelever Erreur -1"); - dol_syslog($this->db->error()); - } - } - - /** - * Get number of invoices to withdrawal - * TODO delete params banque and agence when not necesary - * - * @param int $banque dolibarr mysoc bank - * @param int $agence dolibarr mysoc agence - * @return int entity; - $sql.= " AND f.rowid = pfd.fk_facture"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - - dol_syslog(get_class($this)."::SommeAPrelever"); - $resql = $this->db->query($sql); - - if ( $resql ) - { - $obj = $this->db->fetch_object($resql); - - $this->db->free($resql); - - return $obj->nb; - } - else - { - $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); - return -1; - } - } - - - /** - * Create a withdraw - * TODO delete params banque and agence when not necesary - * - * @param int $banque dolibarr mysoc bank - * @param int $agence dolibarr mysoc bank office (guichet) - * @param string $mode real=do action, simu=test only - * @return int <0 if KO, nbre of invoice withdrawed if OK - */ - function Create($banque=0, $agence=0, $mode='real') - { - global $conf,$langs; - - dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence, LOG_DEBUG); - - require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); - require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); - - $error = 0; - - $datetimeprev = time(); - - $month = strftime("%m", $datetimeprev); - $year = strftime("%Y", $datetimeprev); - - $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); - - /* - * Read invoices - */ - $factures = array(); - $factures_prev = array(); - $factures_result = array(); - $factures_prev_id=array(); - $factures_errors=array(); - - if (! $error) - { - $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; - $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; - $sql.= ", pfd.amount"; - $sql.= ", s.nom as name"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; - $sql.= " WHERE f.rowid = pfd.fk_facture"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND s.rowid = f.fk_soc"; - //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; - $sql.= " AND f.fk_statut = 1"; - $sql.= " AND f.paye = 0"; - $sql.= " AND pfd.traite = 0"; - $sql.= " AND f.total_ttc > 0"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - - dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG); - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - - while ($i < $num) - { - $row = $this->db->fetch_row($resql); - $factures[$i] = $row; // All fields - $i++; - } - $this->db->free($resql); - dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG); - } - else - { - $error++; - dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR); - } - } - - if (! $error) - { - require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; - $soc = new Societe($this->db); - - // Check RIB - $i = 0; - dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG); - - if (count($factures) > 0) - { - foreach ($factures as $key => $fac) - { - $fact = new Facture($this->db); - if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice - { - if ($soc->fetch($fact->socid) >= 0) - { - $bac = new CompanyBankAccount($this->db); - $bac->fetch(0,$soc->id); - - if ($bac->verif() >= 1) - //if (true) - { - $factures_prev[$i] = $fac; - /* second tableau necessaire pour BonPrelevement */ - $factures_prev_id[$i] = $fac[0]; - $i++; - } - else - { - dol_syslog(__METHOD__."::Check RIB Error on default bank number RIB/IBAN for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR); - $this->invoice_in_error[$fac[0]]="Error on default bank number RIB/IBAN for invoice ".$fact->getNomUrl(0)." for thirdparty (reported by function verif) ".$soc->getNomUrl(0); - } - } - else - { - dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR); - } - } - else - { - dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR); - } - } - } - else + if ($num) { - dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR); - } - } + $i = 0; + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + if (!$amounts) $arr[$i] = $row[0]; + else + { + $arr[$i] = array( + $row[0], + $row[1] + ); + } + $i++; + } + } + $this->db->free($resql); + } + else + { + dol_syslog(get_class($this)."::getListInvoices Erreur"); + } - $ok=0; + return $arr; + } - // Withdraw invoices in factures_prev array - $out=count($factures_prev)." invoices will be withdrawn."; - //print $out."\n"; - dol_syslog($out); + /** + * Returns amount of withdrawal + * + * @return double Total amount + */ + function SommeAPrelever() + { + global $conf; + + $sql = "SELECT sum(pfd.amount) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //$sql.= " ,".MAIN_DB_PREFIX."c_paiement as cp"; + $sql.= " WHERE f.fk_statut = 1"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.rowid = pfd.fk_facture"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + + $resql = $this->db->query($sql); + if ( $resql ) + { + $obj = $this->db->fetch_object($resql); + + $this->db->free($resql); + + return $obj->nb; + } + else + { + $error = 1; + dol_syslog(get_class($this)."::SommeAPrelever Erreur -1"); + dol_syslog($this->db->error()); + } + } + + /** + * Get number of invoices to withdrawal + * TODO delete params banque and agence when not necesary + * + * @param int $banque dolibarr mysoc bank + * @param int $agence dolibarr mysoc agence + * @return int entity; + $sql.= " AND f.rowid = pfd.fk_facture"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; + //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; + //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + + dol_syslog(get_class($this)."::SommeAPrelever"); + $resql = $this->db->query($sql); + + if ( $resql ) + { + $obj = $this->db->fetch_object($resql); + + $this->db->free($resql); + + return $obj->nb; + } + else + { + $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); + return -1; + } + } - if (count($factures_prev) > 0) + /** + * Create a withdraw + * TODO delete params banque and agence when not necesary + * + * @param int $banque dolibarr mysoc bank + * @param int $agence dolibarr mysoc bank office (guichet) + * @param string $mode real=do action, simu=test only + * @param string $format FRST, RCUR or ALL + * @return int <0 if KO, nbre of invoice withdrawed if OK + */ + function Create($banque=0, $agence=0, $mode='real', $format='ALL') + { + global $conf,$langs; + + dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG); + + require_once (DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"); + require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); + + if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate'; + + $error = 0; + + $datetimeprev = time(); + + $month = strftime("%m", $datetimeprev); + $year = strftime("%Y", $datetimeprev); + + $puser = new User($this->db, $conf->global->PRELEVEMENT_USER); + + $this->invoice_in_error = array(); + $this->thirdparty_in_error = array(); + + // Read invoices + $factures = array(); + $factures_prev = array(); + $factures_result = array(); + $factures_prev_id=array(); + $factures_errors=array(); + + if (! $error) + { + $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; + $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; + $sql.= ", pfd.amount"; + $sql.= ", s.nom as name"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= ", ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; + //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; + $sql.= " WHERE f.rowid = pfd.fk_facture"; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND s.rowid = f.fk_soc"; + //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; + $sql.= " AND f.fk_statut = 1"; + $sql.= " AND f.paye = 0"; + $sql.= " AND pfd.traite = 0"; + $sql.= " AND f.total_ttc > 0"; + //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; + //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + + dol_syslog(__METHOD__."::Read invoices, sql=".$sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + + while ($i < $num) + { + $row = $this->db->fetch_row($resql); + $factures[$i] = $row; // All fields + $i++; + } + $this->db->free($resql); + dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG); + } + else + { + $error++; + dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR); + } + } + + if (! $error) + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $soc = new Societe($this->db); + + // Check RIB + $i = 0; + dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG); + + if (count($factures) > 0) + { + foreach ($factures as $key => $fac) + { + $fact = new Facture($this->db); + if ($fact->fetch($fac[0]) >= 0) // Field 0 of $fac is rowid of invoice + { + if ($soc->fetch($fact->socid) >= 0) + { + $bac = new CompanyBankAccount($this->db); + $bac->fetch(0, $soc->id); + + if ($format == 'FRST' && $bac->frstrecur != 'FRST') continue; + if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) continue; + + if ($bac->verif() >= 1) + { + $factures_prev[$i] = $fac; + /* second tableau necessaire pour BonPrelevement */ + $factures_prev_id[$i] = $fac[0]; + $i++; + } + else + { + dol_syslog(__METHOD__."::Check RIB Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR); + $this->invoice_in_error[$fac[0]]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0); + $this->thirdparty_in_error[$soc->id]="Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0); + } + } + else + { + dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_ERR); + } + } + else + { + dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_ERR); + } + } + } + else + { + dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_ERR); + } + } + + $ok=0; + + // Withdraw invoices in factures_prev array + $out=count($factures_prev)." invoices will be withdrawn."; + //print $out."\n"; + dol_syslog($out); + + // Return warning + /*$i=0; + foreach ($this->thirdparty_in_error as $key => $val) { - if ($mode=='real') - { - $ok=1; - } - else - { - print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; - } - } + if ($i < 10) setEventMessages($val, null, 'warnings'); + else setEventMessages('More error were discarded...', null, 'warnings'); + $i++; + }*/ + + if (count($factures_prev) > 0) + { + if ($mode=='real') + { + $ok=1; + } + else + { + print $langs->trans("ModeWarning"); //"Option for real mode was not set, we stop after this simulation\n"; + } + } - if ($ok) - { - /* + if ($ok) + { + /* * We are in real mode. * We create withdraw receipt and build withdraw into disk */ - $this->db->begin(); + $this->db->begin(); - $now=dol_now(); + $now=dol_now(); - /* + /* * Traitements */ - if (!$error) - { + if (!$error) + { $ref = substr($year,-2).$month; $sql = "SELECT substring(ref from char_length(ref) - 1)"; @@ -939,48 +955,48 @@ class BonPrelevement extends CommonObject $this->filename = $dir.'/'.$ref.'.xml'; - // Create withdraw receipt in database - $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons ("; - $sql.= " ref, entity, datec"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->escape($ref)."'"; - $sql.= ", ".$conf->entity; - $sql.= ", '".$this->db->idate($now)."'"; - $sql.= ")"; + // Create withdraw receipt in database + $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons ("; + $sql.= " ref, entity, datec"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($ref)."'"; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->idate($now)."'"; + $sql.= ")"; - $resql = $this->db->query($sql); - if ($resql) - { - $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons"); + $resql = $this->db->query($sql); + if ($resql) + { + $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons"); $this->id = $prev_id; $this->ref = $ref; - } - else + } + else { - $error++; - dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR); - } + $error++; + dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR); + } } else { $error++; dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR); } - } + } - if (!$error) - { - /* + if (!$error) + { + /* * Create withdrawal receipt in database */ - if (count($factures_prev) > 0) - { - foreach ($factures_prev as $fac) // Add a link in database for each invoice - { - // Fetch invoice - $fact = new Facture($this->db); - $fact->fetch($fac[0]); - /* + if (count($factures_prev) > 0) + { + foreach ($factures_prev as $fac) // Add a link in database for each invoice + { + // Fetch invoice + $fact = new Facture($this->db); + $fact->fetch($fac[0]); + /* * Add standing order * * @@ -992,128 +1008,128 @@ class BonPrelevement extends CommonObject * $fac[8] : client nom * $fac[2] : client id */ - $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); - if ($ri <> 0) - { - $error++; - } + $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]); + if ($ri <> 0) + { + $error++; + } - // Update invoice requests as done - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande"; - $sql.= " SET traite = 1"; - $sql.= ", date_traite = '".$this->db->idate($now)."'"; - $sql.= ", fk_prelevement_bons = ".$this->id; - $sql.= " WHERE rowid = ".$fac[1]; + // Update invoice requests as done + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande"; + $sql.= " SET traite = 1"; + $sql.= ", date_traite = '".$this->db->idate($now)."'"; + $sql.= ", fk_prelevement_bons = ".$this->id; + $sql.= " WHERE rowid = ".$fac[1]; - dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG); + $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR); - } + if (! $resql) + { + $error++; + dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR); + } - } - } + } + } - } + } - if (!$error) - { - /* + if (!$error) + { + /* * Create direct debit order in a XML file */ - dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG); + dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG); - if (count($factures_prev) > 0) - { - $this->date_echeance = $datetimeprev; - $this->reference_remise = $ref; + if (count($factures_prev) > 0) + { + $this->date_echeance = $datetimeprev; + $this->reference_remise = $ref; - $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT; - $account = new Account($this->db); - if ($account->fetch($id)>0) - { - $this->emetteur_code_banque = $account->code_banque; - $this->emetteur_code_guichet = $account->code_guichet; - $this->emetteur_numero_compte = $account->number; - $this->emetteur_number_key = $account->cle_rib; - $this->emetteur_iban = $account->iban; - $this->emetteur_bic = $account->bic; + $id=$conf->global->PRELEVEMENT_ID_BANKACCOUNT; + $account = new Account($this->db); + if ($account->fetch($id)>0) + { + $this->emetteur_code_banque = $account->code_banque; + $this->emetteur_code_guichet = $account->code_guichet; + $this->emetteur_numero_compte = $account->number; + $this->emetteur_number_key = $account->cle_rib; + $this->emetteur_iban = $account->iban; + $this->emetteur_bic = $account->bic; - $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; + $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; - $this->raison_sociale = $account->proprio; - } + $this->raison_sociale = $account->proprio; + } - $this->factures = $factures_prev_id; + $this->factures = $factures_prev_id; - // Generation of SEPA file $this->filename - $this->generate(); - } - dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); - } + // Generation of SEPA file $this->filename + $this->generate($format); + } + dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); + } //var_dump($factures_prev);exit; - /* + /* * Update total */ - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql.= " SET amount = ".price2num($this->total); - $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND entity = ".$conf->entity; + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; + $sql.= " SET amount = ".price2num($this->total); + $sql.= " WHERE rowid = ".$this->id; + $sql.= " AND entity = ".$conf->entity; - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR); - } + $resql=$this->db->query($sql); + if (! $resql) + { + $error++; + dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR); + } - if (!$error) - { - $this->db->commit(); - } - else - { - $this->db->rollback(); - } + if (!$error) + { + $this->db->commit(); + } + else + { + $this->db->rollback(); + } - return count($factures_prev); - } - else - { - return 0; - } - } + return count($factures_prev); + } + else + { + return 0; + } + } - /** - * Get object and lines from database - * - * @return int >0 if OK, <0 if KO - */ - function delete() - { - $this->db->begin(); + /** + * Get object and lines from database + * + * @return int >0 if OK, <0 if KO + */ + function delete() + { + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")"; - $resql1=$this->db->query($sql); - if (! $resql1) dol_print_error($this->db); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id.")"; + $resql1=$this->db->query($sql); + if (! $resql1) dol_print_error($this->db); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id; - $resql2=$this->db->query($sql); - if (! $resql2) dol_print_error($this->db); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".$this->id; + $resql2=$this->db->query($sql); + if (! $resql2) dol_print_error($this->db); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id; - $resql3=$this->db->query($sql); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".$this->id; + $resql3=$this->db->query($sql); if (! $resql3) dol_print_error($this->db); - $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id; - $resql4=$this->db->query($sql); + $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".$this->id; + $resql4=$this->db->query($sql); if (! $resql4) dol_print_error($this->db); if ($resql1 && $resql2 && $resql3) @@ -1126,151 +1142,153 @@ class BonPrelevement extends CommonObject $this->db->rollback(); return -1; } - } + } - /** - * Returns clickable name (with picto) - * - * @param int $withpicto link with picto - * @param string $option link target - * @return string URL of target - */ - function getNomUrl($withpicto=0,$option='') - { - global $langs; + /** + * Returns clickable name (with picto) + * + * @param int $withpicto link with picto + * @param string $option link target + * @return string URL of target + */ + function getNomUrl($withpicto=0,$option='') + { + global $langs; - $result=''; - $label = $langs->trans("ShowWithdraw").': '.$this->ref; + $result=''; + $label = $langs->trans("ShowWithdraw").': '.$this->ref; - $link = ''; - $linkend=''; + $link = ''; + $linkend=''; - if ($option == 'xxx') - { - $link = ''; - $linkend=''; - } + if ($option == 'xxx') + { + $link = ''; + $linkend=''; + } - if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->ref.$linkend; - return $result; - } + if ($withpicto) $result.=($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + $result.=$link.$this->ref.$linkend; + return $result; + } - /** - * Delete a notification def by id - * - * @param int $rowid id of notification - * @return int 0 if OK, <0 if KO - */ - function DeleteNotificationById($rowid) - { - $result = 0; + /** + * Delete a notification def by id + * + * @param int $rowid id of notification + * @return int 0 if OK, <0 if KO + */ + function DeleteNotificationById($rowid) + { + $result = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql.= " WHERE rowid = '".$rowid."'"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; + $sql.= " WHERE rowid = '".$rowid."'"; - if ($this->db->query($sql)) - { - return 0; - } - else - { - return -1; - } - } + if ($this->db->query($sql)) + { + return 0; + } + else + { + return -1; + } + } - /** - * Delete a notification - * - * @param int $user notification user - * @param string $action notification action - * @return int >0 if OK, <0 if KO - */ - function DeleteNotification($user, $action) - { - $result = 0; + /** + * Delete a notification + * + * @param int $user notification user + * @param string $action notification action + * @return int >0 if OK, <0 if KO + */ + function DeleteNotification($user, $action) + { + $result = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; - $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def"; + $sql .= " WHERE fk_user=".$user." AND fk_action='".$action."'"; - if ($this->db->query($sql)) - { - return 0; - } - else - { - return -1; - } - } + if ($this->db->query($sql)) + { + return 0; + } + else + { + return -1; + } + } - /** - * Add a notification - * - * @param DoliDB $db database handler - * @param int $user notification user - * @param string $action notification action - * @return int 0 if OK, <0 if KO - */ - function AddNotification($db, $user, $action) - { - $result = 0; + /** + * Add a notification + * + * @param DoliDB $db database handler + * @param int $user notification user + * @param string $action notification action + * @return int 0 if OK, <0 if KO + */ + function AddNotification($db, $user, $action) + { + $result = 0; - if ($this->DeleteNotification($user, $action) == 0) - { - $now=dol_now(); + if ($this->DeleteNotification($user, $action) == 0) + { + $now=dol_now(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; - $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)"; + $sql .= " VALUES (".$db->idate($now).",".$user.", 'NULL', 'NULL', '".$action."')"; - dol_syslog("adnotiff: ".$sql); - if ($this->db->query($sql)) - { - $result = 0; - } - else - { - $result = -1; - dol_syslog(get_class($this)."::AddNotification Error $result"); - } - } + dol_syslog("adnotiff: ".$sql); + if ($this->db->query($sql)) + { + $result = 0; + } + else + { + $result = -1; + dol_syslog(get_class($this)."::AddNotification Error $result"); + } + } - return $result; - } + return $result; + } - /** - * Generate a withdrawal file. - * Generation Formats: - * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled) - * - Others countries: Warning message - * File is generated with name this->filename - * - * @return int 0 if OK, <0 if KO - */ - //TODO: Optimize code to read lines in a single function - function generate() - { - global $conf,$langs,$mysoc; + /** + * Generate a withdrawal file. + * Generation Formats: + * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled) + * - Others countries: Warning message + * File is generated with name this->filename + * + * @param string $format FRST, RCUR or ALL + * @return int 0 if OK, <0 if KO + */ + function generate($format='ALL') + { + global $conf,$langs,$mysoc; - $result = 0; + //TODO: Optimize code to read lines in a single function - dol_syslog(get_class($this)."::generate build file ".$this->filename); + $result = 0; - $this->file = fopen($this->filename,"w"); + dol_syslog(get_class($this)."::generate build file ".$this->filename); + + $this->file = fopen($this->filename,"w"); if (empty($this->file)) { $this->error=$langs->trans('ErrorFailedToOpenFile', $this->filename); return -1; } - $found=0; + $found=0; - // Build file for European countries - if ($mysoc->isInEEC()) - { - $found++; + // Build file for European countries + if ($mysoc->isInEEC()) + { + $found++; /** * SECTION CREATION FICHIER SEPA @@ -1332,7 +1350,7 @@ class BonPrelevement extends CommonObject // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all DrctDbtTxInf if ($result != -2) { - $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf); + $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format); } else { @@ -1373,163 +1391,163 @@ class BonPrelevement extends CommonObject fputs($this->file, ' '.$CrLf); fputs($this->file, ' '.$CrLf); fputs($this->file, ''.$CrLf); - } + } - // Build file for Other Countries with unknow format - if (! $found) + // Build file for Other Countries with unknow format + if (! $found) { - $this->total = 0; - $sql = "SELECT pl.amount"; - $sql.= " FROM"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; - $sql.= " ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; - $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; - $sql.= " AND pf.fk_facture = f.rowid"; + $this->total = 0; + $sql = "SELECT pl.amount"; + $sql.= " FROM"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; + $sql.= " ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; + $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; + $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; + $sql.= " AND pf.fk_facture = f.rowid"; - //Lines - $i = 0; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $this->total = $this->total + $obj->amount; - $i++; - } - } - else + //Lines + $i = 0; + $resql=$this->db->query($sql); + if ($resql) { - $result = -2; - } + $num = $this->db->num_rows($resql); - $langs->load('withdrawals'); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $this->total = $this->total + $obj->amount; + $i++; + } + } + else + { + $result = -2; + } - // TODO Add here code to generate a generic file - fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); - } + $langs->load('withdrawals'); - fclose($this->file); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($this->file, octdec($conf->global->MAIN_UMASK)); - return $result; + // TODO Add here code to generate a generic file + fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); + } - } + fclose($this->file); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($this->file, octdec($conf->global->MAIN_UMASK)); + return $result; + + } - /** - * Write recipient of request (customer) - * - * @param int $rowid id of line - * @param string $client_nom name of customer - * @param string $rib_banque code of bank - * @param string $rib_guichet code of bank office - * @param string $rib_number bank account - * @param float $amount amount - * @param string $facnumber ref of invoice - * @param int $facid id of invoice + /** + * Write recipient of request (customer) + * + * @param int $rowid id of line + * @param string $client_nom name of customer + * @param string $rib_banque code of bank + * @param string $rib_guichet code of bank office + * @param string $rib_number bank account + * @param float $amount amount + * @param string $facnumber ref of invoice + * @param int $facid id of invoice * @param string $rib_dom rib domiciliation - * @return void - */ - function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='') - { - fputs($this->file, "06"); - fputs($this->file, "08"); // Prelevement ordinaire + * @return void + */ + function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $facnumber, $facid, $rib_dom='') + { + fputs($this->file, "06"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Date d'echeance C1 + // Date d'echeance C1 - fputs($this->file, " "); - fputs($this->file, strftime("%d%m", $this->date_echeance)); - fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); + fputs($this->file, " "); + fputs($this->file, strftime("%d%m", $this->date_echeance)); + fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); - // Raison Sociale Destinataire C2 + // Raison Sociale Destinataire C2 - fputs($this->file, substr(strtoupper($client_nom)." ",0,24)); + fputs($this->file, substr(strtoupper($client_nom)." ",0,24)); - // Domiciliation facultative D1 - $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => "")); - fputs($this->file, substr($domiciliation." ",0,24)); + // Domiciliation facultative D1 + $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => "")); + fputs($this->file, substr($domiciliation." ",0,24)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,8)); + fputs($this->file, substr(" ",0,8)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, $rib_guichet); + fputs($this->file, $rib_guichet); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr("000000000000000".$rib_number, -11)); + fputs($this->file, substr("000000000000000".$rib_number, -11)); - // Zone E Montant + // Zone E Montant - $montant = (round($amount,2) * 100); + $montant = (round($amount,2) * 100); - fputs($this->file, substr("000000000000000".$montant, -16)); + fputs($this->file, substr("000000000000000".$montant, -16)); - // Libelle F + // Libelle F - fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31)); + fputs($this->file, substr("*_".$facnumber."_RDVnet".$rowid." ", 0, 31)); - // Code etablissement G1 + // Code etablissement G1 - fputs($this->file, $rib_banque); + fputs($this->file, $rib_banque); - // Zone Reservee G2 + // Zone Reservee G2 - fputs($this->file, substr(" ", 0, 5)); + fputs($this->file, substr(" ", 0, 5)); - fputs($this->file, "\n"); - } + fputs($this->file, "\n"); + } - /** - * Build RUM number for a customer bank account - * - * @param string $row_code_client Customer code (soc.code_client) - * @param int $row_datec Creation date of bank account (rib.datec) - * @param string $row_drum Id of customer bank account (rib.rowid) - * @return string RUM number - */ - static function buildRumNumber($row_code_client, $row_datec, $row_drum) - { - global $langs; - $pre = ($row_datec > 1359673200) ? $langs->trans('RUM').'-' : '++R'; + /** + * Build RUM number for a customer bank account + * + * @param string $row_code_client Customer code (soc.code_client) + * @param int $row_datec Creation date of bank account (rib.datec) + * @param string $row_drum Id of customer bank account (rib.rowid) + * @return string RUM number + */ + static function buildRumNumber($row_code_client, $row_datec, $row_drum) + { + global $langs; + $pre = $langs->trans('RUM').'-'; return $pre.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec); - } + } - /** - * Write recipient of request (customer) - * - * @param string $row_code_client soc.code_client as code, - * @param string $row_nom pl.client_nom AS name, - * @param string $row_address soc.address AS adr, - * @param string $row_zip soc.zip - * @param string $row_town soc.town - * @param string $row_country_code c.code AS country, - * @param string $row_cb pl.code_banque AS cb, - * @param string $row_cg pl.code_guichet AS cg, - * @param string $row_cc pl.number AS cc, - * @param string $row_somme pl.amount AS somme, - * @param string $row_facnumber f.facnumber - * @param string $row_idfac pf.fk_facture AS idfac, - * @param string $row_iban rib.iban_prefix AS iban, - * @param string $row_bic rib.bic AS bic, - * @param string $row_datec rib.datec, - * @param string $row_drum rib.rowid used to generate rum - * @return string Return string with SEPA part DrctDbtTxInf - */ - function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum) - { + /** + * Write recipient of request (customer) + * + * @param string $row_code_client soc.code_client as code, + * @param string $row_nom pl.client_nom AS name, + * @param string $row_address soc.address AS adr, + * @param string $row_zip soc.zip + * @param string $row_town soc.town + * @param string $row_country_code c.code AS country, + * @param string $row_cb pl.code_banque AS cb, Not used for SEPA + * @param string $row_cg pl.code_guichet AS cg, Not used for SEPA + * @param string $row_cc pl.number AS cc, Not used for SEPA + * @param string $row_somme pl.amount AS somme, + * @param string $row_facnumber f.facnumber + * @param string $row_idfac pf.fk_facture AS idfac, + * @param string $row_iban rib.iban_prefix AS iban, + * @param string $row_bic rib.bic AS bic, + * @param string $row_datec rib.datec, + * @param string $row_drum rib.rowid used to generate rum + * @return string Return string with SEPA part DrctDbtTxInf + */ + function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_facnumber, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum) + { $CrLf = "\n"; $Rowing = sprintf("%06d", $row_idfac); @@ -1562,8 +1580,10 @@ class BonPrelevement extends CommonObject $XML_DEBITOR .=' '.dolEscapeXML(strtoupper(dol_string_unaccent($row_nom))).''.$CrLf; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$row_country_code.''.$CrLf; - $XML_DEBITOR .=' '.dolEscapeXML(dol_trunc(dol_string_unaccent(strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""))),70,'right','UTF-8',true)).''.$CrLf; - $XML_DEBITOR .=' '.dolEscapeXML(dol_string_unaccent($row_zip.' '.$row_town)).''.$CrLf; + $addressline1 = dol_string_unaccent(strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""))); + $addressline2 = dol_string_unaccent(strtr($row_zip.(($row_zip && $row_town)?' ':''.$row_town), array(CHR(13) => ", ", CHR(10) => ""))); + if (trim($addressline1)) $XML_DEBITOR .=' '.dolEscapeXML(dol_trunc($addressline1,70,'right','UTF-8',true)).''.$CrLf; + if (trim($addressline2)) $XML_DEBITOR .=' '.dolEscapeXML(dol_trunc($addressline2,70,'right','UTF-8',true)).''.$CrLf; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; @@ -1577,89 +1597,90 @@ class BonPrelevement extends CommonObject $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; return $XML_DEBITOR; - } + } - /** - * Write sender of request (me) - * - * @return void - */ - function EnregEmetteur() - { - fputs($this->file, "03"); - fputs($this->file, "08"); // Prelevement ordinaire + /** + * Write sender of request (me) + * + * @return void + */ + function EnregEmetteur() + { + fputs($this->file, "03"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Date d'echeance C1 + // Date d'echeance C1 - fputs($this->file, " "); - fputs($this->file, strftime("%d%m", $this->date_echeance)); - fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); + fputs($this->file, " "); + fputs($this->file, strftime("%d%m", $this->date_echeance)); + fputs($this->file, substr(strftime("%y", $this->date_echeance),1)); - // Raison Sociale C2 + // Raison Sociale C2 - fputs($this->file, substr($this->raison_sociale. " ",0,24)); + fputs($this->file, substr($this->raison_sociale. " ",0,24)); - // Reference de la remise creancier D1 sur 7 caracteres + // Reference de la remise creancier D1 sur 7 caracteres - fputs($this->file, substr($this->reference_remise. " ",0,7)); + fputs($this->file, substr($this->reference_remise. " ",0,7)); - // Zone Reservee D1-2 + // Zone Reservee D1-2 - fputs($this->file, substr(" ",0,17)); + fputs($this->file, substr(" ",0,17)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,2)); - fputs($this->file, "E"); - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,2)); + fputs($this->file, "E"); + fputs($this->file, substr(" ",0,5)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, $this->emetteur_code_guichet); + fputs($this->file, $this->emetteur_code_guichet); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11)); + fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11)); - // Zone Reservee E + // Zone Reservee E - fputs($this->file, substr(" ",0,16)); + fputs($this->file, substr(" ",0,16)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,31)); + fputs($this->file, substr(" ",0,31)); - // Code etablissement + // Code etablissement - fputs($this->file, $this->emetteur_code_banque); + fputs($this->file, $this->emetteur_code_banque); - // Zone Reservee G + // Zone Reservee G - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - fputs($this->file, "\n"); + fputs($this->file, "\n"); - } + } - /** - * Write sender of request (me). - * Note: The tag PmtInf is opened here but closed into caller - * - * @param string $configuration conf - * @param int $ladate Date - * @param int $nombre 0 or 1 - * @param float $total Total - * @param string $CrLf End of line character - * @return string String with SEPA Sender - */ - function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n') - { - // SEPA INITIALISATION + /** + * Write sender of request (me). + * Note: The tag PmtInf is opened here but closed into caller + * + * @param string $configuration conf + * @param int $ladate Date + * @param int $nombre 0 or 1 + * @param float $total Total + * @param string $CrLf End of line character + * @param string $format FRST or RCUR or ALL + * @return string String with SEPA Sender + */ + function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf='\n', $format='FRST') + { + // SEPA INITIALISATION global $conf; $dateTime_YMD = dol_print_date($ladate, '%Y%m%d'); @@ -1671,16 +1692,16 @@ class BonPrelevement extends CommonObject $account = new Account($this->db); if ($account->fetch($id)>0) { - $this->emetteur_code_banque = $account->code_banque; - $this->emetteur_code_guichet = $account->code_guichet; - $this->emetteur_numero_compte = $account->number; - $this->emetteur_number_key = $account->cle_rib; - $this->emetteur_iban = $account->iban; - $this->emetteur_bic = $account->bic; + $this->emetteur_code_banque = $account->code_banque; + $this->emetteur_code_guichet = $account->code_guichet; + $this->emetteur_numero_compte = $account->number; + $this->emetteur_number_key = $account->cle_rib; + $this->emetteur_iban = $account->iban; + $this->emetteur_bic = $account->bic; - $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; + $this->emetteur_ics = $conf->global->PRELEVEMENT_ICS; // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456"; - $this->raison_sociale = $account->proprio; + $this->raison_sociale = $account->proprio; } // Récupération info demandeur @@ -1698,7 +1719,7 @@ class BonPrelevement extends CommonObject $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY); $IdBon = sprintf("%05d", $obj->rowid); $RefBon = $obj->ref; - $type = ($nombre == 1) ? 'FRST' : 'RCUR' ; + // SEPA Paiement Information $XML_SEPA_INFO = ''; $XML_SEPA_INFO .= ' '.$CrLf; @@ -1713,15 +1734,17 @@ class BonPrelevement extends CommonObject $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' CORE'.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; - $XML_SEPA_INFO .= ' '.$type.''.$CrLf; + $XML_SEPA_INFO .= ' '.$format.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$dateTime_ETAD.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.strtoupper(dol_string_unaccent($this->raison_sociale)).''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$country[1].''.$CrLf; - $XML_SEPA_INFO .= ' '.strtoupper(dol_string_unaccent($configuration->global->MAIN_INFO_SOCIETE_ADDRESS)).''.$CrLf; - $XML_SEPA_INFO .= ' '.strtoupper(dol_string_unaccent($configuration->global->MAIN_INFO_SOCIETE_ZIP.' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN)).''.$CrLf; + $addressline1 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""))); + $addressline2 = dol_string_unaccent(strtr($configuration->global->MAIN_INFO_SOCIETE_ZIP.(($configuration->global->MAIN_INFO_SOCIETE_ZIP || ' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN)?' ':'').$configuration->global->MAIN_INFO_SOCIETE_TOWN, array(CHR(13) => ", ", CHR(10) => ""))); + if ($addressline1) $XML_SEPA_INFO .= ' '.$addressline1.''.$CrLf; + if ($addressline2) $XML_SEPA_INFO .= ' '.$addressline2.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; @@ -1764,131 +1787,131 @@ class BonPrelevement extends CommonObject return $XML_SEPA_INFO; } - /** - * Write end - * - * @param int $total total amount - * @return void - */ - function EnregTotal($total) - { - fputs($this->file, "08"); - fputs($this->file, "08"); // Prelevement ordinaire + /** + * Write end + * + * @param int $total total amount + * @return void + */ + function EnregTotal($total) + { + fputs($this->file, "08"); + fputs($this->file, "08"); // Prelevement ordinaire - fputs($this->file, " "); // Zone Reservee B2 + fputs($this->file, " "); // Zone Reservee B2 - fputs($this->file, $this->emetteur_ics); // ICS + fputs($this->file, $this->emetteur_ics); // ICS - // Reserve C1 + // Reserve C1 - fputs($this->file, substr(" ",0,12)); + fputs($this->file, substr(" ",0,12)); - // Raison Sociale C2 + // Raison Sociale C2 - fputs($this->file, substr(" ",0,24)); + fputs($this->file, substr(" ",0,24)); - // D1 + // D1 - fputs($this->file, substr(" ",0,24)); + fputs($this->file, substr(" ",0,24)); - // Zone Reservee D2 + // Zone Reservee D2 - fputs($this->file, substr(" ",0,8)); + fputs($this->file, substr(" ",0,8)); - // Code Guichet D3 + // Code Guichet D3 - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - // Numero de compte D4 + // Numero de compte D4 - fputs($this->file, substr(" ",0,11)); + fputs($this->file, substr(" ",0,11)); - // Zone E Montant + // Zone E Montant - $montant = ($total * 100); + $montant = ($total * 100); - fputs($this->file, substr("000000000000000".$montant, -16)); + fputs($this->file, substr("000000000000000".$montant, -16)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,31)); + fputs($this->file, substr(" ",0,31)); - // Code etablissement + // Code etablissement - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - // Zone Reservee F + // Zone Reservee F - fputs($this->file, substr(" ",0,5)); + fputs($this->file, substr(" ",0,5)); - fputs($this->file, "\n"); - } + fputs($this->file, "\n"); + } - /** - * Return status label of object - * - * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut,$mode); - } + /** + * Return status label of object + * + * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } - /** - * Return status label for a status - * - * @param int $statut id statut + /** + * Return status label for a status + * + * @param int $statut id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label - */ - function LibStatut($statut,$mode=0) - { - global $langs; + * @return string Label + */ + function LibStatut($statut,$mode=0) + { + global $langs; - if ($mode == 0) - { - return $langs->trans($this->labelstatut[$statut]); - } + if ($mode == 0) + { + return $langs->trans($this->labelstatut[$statut]); + } - if ($mode == 1) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); - } - if ($mode == 2) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 3) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 4) - { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); - } - if ($mode == 5) - { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - if ($mode == 6) - { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); - } - } + if ($mode == 1) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + } + if ($mode == 2) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 3) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 4) + { + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + } + if ($mode == 5) + { + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + if ($mode == 6) + { + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); + if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + } + } } diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index 09102ec1309..d9775250853 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -28,6 +28,7 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -44,6 +45,8 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); // Get supervariables $action = GETPOST('action','alpha'); +$mode = GETPOST('mode','alpha')?GETPOST('mode','alpha'):'real'; +$format = GETPOST('format','aZ09'); /* @@ -53,35 +56,35 @@ $action = GETPOST('action','alpha'); // Change customer bank information to withdraw if ($action == 'modify') { - for ($i = 1 ; $i < 9 ; $i++) - { - dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"),'chaine',0,'',$conf->entity); - } + for ($i = 1 ; $i < 9 ; $i++) + { + dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"),'chaine',0,'',$conf->entity); + } } if ($action == 'create') { // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty - $bprev = new BonPrelevement($db); - $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET); - if ($result < 0) - { - setEventMessages($bprev->error, $bprev->errors, 'errors'); - } - elseif ($result == 0) - { - $mesg=''; - $mesg=$langs->trans("NoInvoiceCouldBeWithdrawed"); - setEventMessages($mesg, null, 'errors'); - $mesg.='
      '."\n"; - foreach($bprev->invoice_in_error as $key => $val) - { - $mesg.=$val."
      \n"; - } - } - else - { - setEventMessages($langs->trans("DirectDebitOrderCreated", $bprev->getNomUrl(1)), null); - } + $bprev = new BonPrelevement($db); + $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format); + if ($result < 0) + { + setEventMessages($bprev->error, $bprev->errors, 'errors'); + } + elseif ($result == 0) + { + $mesg=''; + $mesg=$langs->trans("NoInvoiceCouldBeWithdrawed"); + setEventMessages($mesg, null, 'errors'); + $mesg.='
      '."\n"; + foreach($bprev->invoice_in_error as $key => $val) + { + $mesg.=''.$val."
      \n"; + } + } + else + { + setEventMessages($langs->trans("DirectDebitOrderCreated", $bprev->getNomUrl(1)), null); + } } @@ -121,7 +124,7 @@ $nb11=$bprev->NbFactureAPrelever(1,1); $pricetowithdraw=$bprev->SommeAPrelever(); if ($nb < 0 || $nb1 < 0 || $nb11 < 0) { - dol_print_error($bprev->error); + dol_print_error($bprev->error); } print ''; @@ -145,12 +148,34 @@ print "
      \n"; if ($nb) { - if ($pricetowithdraw) print ''.$langs->trans("CreateAll")."\n"; - else print ''.$langs->trans("CreateAll")."\n"; + if ($pricetowithdraw) + { + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("CreateForSepaFRST")."\n"; + print ''.$langs->trans("CreateForSepaRCUR")."\n"; + } + else + { + print ''.$langs->trans("CreateAll")."\n"; + } + } + else + { + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("CreateForSepaFRST")."\n"; + print ''.$langs->trans("CreateForSepaRCUR")."\n"; + } + else + { + print ''.$langs->trans("CreateAll")."\n"; + } + } } else { - print 'transnoentitiesnoconv("StandingOrders"))).'">'.$langs->trans("CreateAll")."\n"; + print 'transnoentitiesnoconv("StandingOrders"))).'">'.$langs->trans("CreateAll")."\n"; } print "
      \n"; @@ -175,66 +200,72 @@ if ($socid) $sql.= " AND f.fk_soc = ".$socid; $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; + $num = $db->num_rows($resql); + $i = 0; - print load_fiche_titre($langs->trans("InvoiceWaitingWithdraw").($num > 0?' ('.$num.')':''),'',''); + print load_fiche_titre($langs->trans("InvoiceWaitingWithdraw").($num > 0?' ('.$num.')':''),'',''); - print '
      '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print '
      '.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("RIB").''.$langs->trans("RUM").''.$langs->trans("AmountTTC").''.$langs->trans("DateRequest").'
      '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - if ($num) - { - $var = True; - while ($i < $num && $i < 20) - { - $obj = $db->fetch_object($resql); + if ($num) + { + require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; + $bac = new CompanyBankAccount($db); - print ''; - print ''; - // Thirdparty - print ''; - // RIB - print ''; - // RUM - print ''; - // Amount - print ''; - // Date - print ''; - print ''; - $i++; - } - } - else print ''; - print "
      '.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("RIB").''.$langs->trans("RUM").''.$langs->trans("AmountTTC").''.$langs->trans("DateRequest").'
      '; - $invoicestatic->id=$obj->rowid; - $invoicestatic->ref=$obj->facnumber; - print $invoicestatic->getNomUrl(1,'withdraw'); - print ''; - $thirdpartystatic->fetch($obj->socid); - print $thirdpartystatic->getNomUrl(1,'card'); - print ''; - print $thirdpartystatic->display_rib(); - print ''; - print $thirdpartystatic->display_rib('rum'); - print ''; - print price($obj->amount,0,$langs,0,0,-1,$conf->currency); - print ''; - print dol_print_date($db->jdate($obj->date_demande),'day'); - print '
      '.$langs->trans("None").'
      "; - print "
      \n"; + while ($i < $num && $i < 20) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + $invoicestatic->id=$obj->rowid; + $invoicestatic->ref=$obj->facnumber; + print $invoicestatic->getNomUrl(1,'withdraw'); + print ''; + // Thirdparty + print ''; + $thirdpartystatic->fetch($obj->socid); + print $thirdpartystatic->getNomUrl(1,'ban'); + print ''; + // RIB + print ''; + print $thirdpartystatic->display_rib(); + $bac->fetch(0, $obj->socid); + if ($bac->verif() <= 0) print img_warning('Error on default bank number for IBAN : '.$bac->error_message); + print ''; + // RUM + print ''; + print $thirdpartystatic->display_rib('rum'); + $format = $thirdpartystatic->display_rib('format'); + if ($format) print ' ('.$format.')'; + print ''; + // Amount + print ''; + print price($obj->amount,0,$langs,0,0,-1,$conf->currency); + print ''; + // Date + print ''; + print dol_print_date($db->jdate($obj->date_demande),'day'); + print ''; + print ''; + $i++; + } + } + else print ''.$langs->trans("None").''; + print ""; + print "
      \n"; } else { - dol_print_error($db); + dol_print_error($db); } diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 8b67cf318c7..485b9a9b47a 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -338,7 +338,7 @@ else /* * Factures clients */ - print ''.$langs->trans("CustomersInvoices").''; + print ''.$langs->trans("CustomersInvoices").''; if ($modecompta == 'CREANCES-DETTES') { @@ -500,7 +500,7 @@ else $sql .= " GROUP BY name, socid"; $sql.= $db->order($sortfield, $sortorder); - print ''.$langs->trans("SuppliersInvoices").''; + print ''.$langs->trans("SuppliersInvoices").''; $subtotal_ht = 0; $subtotal_ttc = 0; @@ -554,7 +554,7 @@ else * Charges sociales non deductibles */ - print ''.$langs->trans("SocialContributionsNondeductibles").''; + print ''.$langs->trans("SocialContributionsNondeductibles").''; if ($modecompta == 'CREANCES-DETTES') { @@ -630,7 +630,7 @@ else * Charges sociales deductibles */ - print ''.$langs->trans("SocialContributionsDeductibles").''; + print ''.$langs->trans("SocialContributionsDeductibles").''; if ($modecompta == 'CREANCES-DETTES') { @@ -727,7 +727,7 @@ else if (! empty($conf->salaries->enabled)) { - print ''.$langs->trans("Salaries").''; + print ''.$langs->trans("Salaries").''; if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') { @@ -822,7 +822,7 @@ else $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); $sql.= " WHERE p.entity = ".getEntity('expensereport'); $sql.= " AND p.fk_statut>=5"; @@ -840,7 +840,7 @@ else $sql.= $db->order($newsortfield, $sortorder); } - print ''.$langs->trans("ExpenseReport").''; + print ''.$langs->trans("ExpenseReport").''; dol_syslog("get expense report outcome"); $result=$db->query($sql); @@ -890,7 +890,7 @@ else if (! empty($conf->don->enabled)) { - print ''.$langs->trans("Donations").''; + print ''.$langs->trans("Donations").''; if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'RECETTES-DEPENSES') { @@ -906,7 +906,7 @@ else $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); $sql.= " WHERE p.entity = ".getEntity('donation'); $sql.= " AND fk_statut >= 2"; } @@ -972,7 +972,7 @@ else * VAT */ - print ''.$langs->trans("VAT").''; + print ''.$langs->trans("VAT").''; $subtotal_ht = 0; $subtotal_ttc = 0; diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 49d8766127e..20333675542 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -698,7 +698,7 @@ if (! empty($conf->expensereport->enabled) && ($modecompta == 'CREANCES-DETTES' $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); $sql.= " WHERE p.entity = ".getEntity('expensereport'); $sql.= " AND p.fk_statut>=5"; @@ -761,7 +761,7 @@ if (! empty($conf->don->enabled) && ($modecompta == 'CREANCES-DETTES' || $modeco $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(pe.datep,'%Y-%m') as dm, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity = " . getEntity('c_paiement'); $sql.= " WHERE p.entity = ".getEntity('donation'); $sql.= " AND fk_statut >= 2"; if (! empty($date_start) && ! empty($date_end)) @@ -893,10 +893,19 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) } print ''; print ''.$langs->trans("Month").''; +// Loop on each year to ouput for ($annee = $year_start ; $annee <= $year_end ; $annee++) { - print ''.$langs->trans("Outcome").''; - print ''.$langs->trans("Income").''; + print ''; + $htmlhelp=''; + // if ($modecompta == 'RECETTES-DEPENSES') $htmlhelp=$langs->trans("PurchasesPlusVATEarnedAndDue"); + print $form->textwithpicto($langs->trans("Outcome"), $htmlhelp); + print ''; + print ''; + $htmlhelp=''; + // if ($modecompta == 'RECETTES-DEPENSES') $htmlhelp=$langs->trans("SalesPlusVATToRetreive"); + print $form->textwithpicto($langs->trans("Income"), $htmlhelp); + print ''; } print ''; @@ -967,7 +976,7 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) { $in=(isset($totentrees[$annee])?price2num($totentrees[$annee], 'MT'):0); $out=(isset($totsorties[$annee])?price2num($totsorties[$annee],'MT'):0); - print price($in-$out).''; + print price(price2num($in-$out, 'MT')).''; // print ' '; } } diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php index 2b8b6a6fe5b..47d4c027185 100644 --- a/htdocs/compta/salaries/card.php +++ b/htdocs/compta/salaries/card.php @@ -214,6 +214,12 @@ if ($action == 'create') $pastmonthyear--; } + $datespmonth = GETPOST('datespmonth', 'int'); + $datespday = GETPOST('datespday', 'int'); + $datespyear = GETPOST('datespyear', 'int'); + $dateepmonth = GETPOST('dateepmonth', 'int'); + $dateepday = GETPOST('dateepday', 'int'); + $dateepyear = GETPOST('dateepyear', 'int'); $datesp=dol_mktime(0, 0, 0, $datespmonth, $datespday, $datespyear); $dateep=dol_mktime(23, 59, 59, $dateepmonth, $dateepday, $dateepyear); @@ -253,7 +259,7 @@ if ($action == 'create') // Label print ''; print fieldLabel('Label','label',1).''; - print 'trans("SalaryPayment")).'">'; + print 'trans("SalaryPayment")).'">'; print ''; // Date start period diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index f7c722e3e1d..6928d3e38f6 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -105,7 +105,7 @@ $sql.= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datep as datep, s.da $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id AND pst.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid,"; $sql.= " ".MAIN_DB_PREFIX."user as u"; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 0ab82a7cae3..6149a2a92b1 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -25,6 +25,7 @@ */ require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; @@ -33,6 +34,9 @@ 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'; } +if (! empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; +} $langs->load("compta"); $langs->load("bills"); @@ -63,50 +67,50 @@ if ($action == 'confirm_paid' && $user->rights->tax->charges->creer && $confirm } if ($action == 'reopen' && $user->rights->tax->charges->creer) { - $result = $object->fetch($id); - if ($object->paye) - { - $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->paye) + { + $result = $object->set_unpaid($user); + if ($result > 0) + { + header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); + exit(); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } // Link to a project if ($action == 'classin' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $object->setProject(GETPOST('projectid')); + $object->fetch($id); + $object->setProject(GETPOST('projectid')); } if ($action == 'setlib' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $result = $object->setValueFrom('libelle', GETPOST('lib'), '', '', 'text', '', $user, 'TAX_MODIFY'); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + $object->fetch($id); + $result = $object->setValueFrom('libelle', GETPOST('lib'), '', '', 'text', '', $user, 'TAX_MODIFY'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); } // payment mode if ($action == 'setmode' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + $object->fetch($id); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); } // bank account if ($action == 'setbankaccount' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Delete social contribution @@ -131,8 +135,8 @@ if ($action == 'add' && $user->rights->tax->charges->creer) { $dateech=dol_mktime(GETPOST('echhour'),GETPOST('echmin'),GETPOST('echsec'),GETPOST('echmonth'),GETPOST('echday'),GETPOST('echyear')); $dateperiod=dol_mktime(GETPOST('periodhour'),GETPOST('periodmin'),GETPOST('periodsec'),GETPOST('periodmonth'),GETPOST('periodday'),GETPOST('periodyear')); - $amount=price2num(GETPOST('amount')); - $actioncode=GETPOST('actioncode'); + $amount=price2num(GETPOST('amount')); + $actioncode=GETPOST('actioncode'); if (! $dateech) { @@ -166,8 +170,8 @@ if ($action == 'add' && $user->rights->tax->charges->creer) $object->date_ech = $dateech; $object->periode = $dateperiod; $object->amount = $amount; - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->fk_project = GETPOST('fk_project'); $id=$object->create($user); @@ -182,43 +186,43 @@ if ($action == 'add' && $user->rights->tax->charges->creer) if ($action == 'update' && ! $_POST["cancel"] && $user->rights->tax->charges->creer) { - $dateech=dol_mktime(GETPOST('echhour'),GETPOST('echmin'),GETPOST('echsec'),GETPOST('echmonth'),GETPOST('echday'),GETPOST('echyear')); - $dateperiod=dol_mktime(GETPOST('periodhour'),GETPOST('periodmin'),GETPOST('periodsec'),GETPOST('periodmonth'),GETPOST('periodday'),GETPOST('periodyear')); - $amount=price2num(GETPOST('amount')); + $dateech=dol_mktime(GETPOST('echhour'),GETPOST('echmin'),GETPOST('echsec'),GETPOST('echmonth'),GETPOST('echday'),GETPOST('echyear')); + $dateperiod=dol_mktime(GETPOST('periodhour'),GETPOST('periodmin'),GETPOST('periodsec'),GETPOST('periodmonth'),GETPOST('periodday'),GETPOST('periodyear')); + $amount=price2num(GETPOST('amount')); - if (! $dateech) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateDue")), null, 'errors'); - $action = 'edit'; - } - elseif (! $dateperiod) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Period")), null, 'errors'); - $action = 'edit'; - } - elseif (empty($amount)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); - $action = 'edit'; - } + if (! $dateech) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("DateDue")), null, 'errors'); + $action = 'edit'; + } + elseif (! $dateperiod) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Period")), null, 'errors'); + $action = 'edit'; + } + elseif (empty($amount)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); + $action = 'edit'; + } elseif (! is_numeric($amount)) { setEventMessages($langs->trans("ErrorFieldMustBeANumeric",$langs->transnoentities("Amount")), null, 'errors'); $action = 'create'; } - else + else { - $result=$object->fetch($id); + $result=$object->fetch($id); - $object->date_ech = $dateech; - $object->periode = $dateperiod; - $object->amount = price2num($amount); + $object->date_ech = $dateech; + $object->periode = $dateperiod; + $object->amount = price2num($amount); - $result=$object->update($user); - if ($result <= 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->update($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } } @@ -281,6 +285,7 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->tax->char $form = new Form($db); $formsocialcontrib = new FormSocialContrib($db); +$bankaccountstatic = new Account($db); if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $title = $langs->trans("SocialContribution") . ' - ' . $langs->trans("Card"); @@ -293,51 +298,49 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("NewSocialContribution")); - $var=false; + print '
      '; + print ''; + print ''; - print ''; - print ''; - print ''; - - dol_fiche_head(); + dol_fiche_head(); print ''; - // Label - print ""; - print ''; - print ''; - print ''; - print ''; + // Label + print ""; + print ''; + print ''; + print ''; + print ''; - // Type - print ''; - print ''; - print ''; + // Type + print ''; + print ''; + print ''; // Date end period - print ''; - print ''; - print ''; + print ''; - print ''; + print ''; + print ''; - // Amount - print ''; - print ''; - print ''; - print ''; + // Amount + print ''; + print ''; + print ''; + print ''; // Project if (! empty($conf->projet->enabled)) @@ -354,30 +357,30 @@ if ($action == 'create') print ''; } - // Payment Mode - print ''; + // Payment Mode + print ''; - // Bank Account - if (! empty($conf->banque->enabled)) - { - print ''; - } + // Bank Account + if (! empty($conf->banque->enabled)) + { + print ''; + } - // Date due - print ''; - print ''; - print ''; + print ''; - print "\n"; + print ''; + print "\n"; - print '
      '; - print $langs->trans("Label"); - print '
      '; + print $langs->trans("Label"); + print '
      '; - print $langs->trans("Type"); - print ''; - $formsocialcontrib->select_type_socialcontrib(GETPOST("actioncode")?GETPOST("actioncode"):'','actioncode',1); - print '
      '; + print $langs->trans("Type"); + print ''; + $formsocialcontrib->select_type_socialcontrib(GETPOST("actioncode",'alpha')?GETPOST("actioncode",'alpha'):'','actioncode',1); + print '
      '; - print $langs->trans("PeriodEndDate"); - print ''; - print $form->select_date(! empty($dateperiod)?$dateperiod:'-1', 'period', 0, 0, 0, 'charge', 1); + print '
      '; + print $langs->trans("PeriodEndDate"); print '
      '; + print $form->select_date(! empty($dateperiod)?$dateperiod:'-1', 'period', 0, 0, 0, 'charge', 1); + print '
      '; - print $langs->trans("Amount"); - print '
      '; + print $langs->trans("Amount"); + print '
      ' . $langs->trans('PaymentMode') . ''; - $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); - print '
      ' . $langs->trans('PaymentMode') . ''; + $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); + 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 '
      '; - print $langs->trans("DateDue"); - print ''; - print $form->select_date(! empty($dateech)?$dateech:'-1', 'ech', 0, 0, 0, 'charge', 1); + // Date due + print '
      '; + print $langs->trans("DateDue"); print '
      '; + print $form->select_date(! empty($dateech)?$dateech:'-1', 'ech', 0, 0, 0, 'charge', 1); + print '
      '; + print ''; dol_fiche_end(); @@ -387,7 +390,7 @@ if ($action == 'create') print ''; print '
      '; - print ''; + print ''; } /* *************************************************************************** */ @@ -398,7 +401,7 @@ if ($action == 'create') if ($id > 0) { $object = new ChargeSociales($db); - $result=$object->fetch($id); + $result=$object->fetch($id); if ($result > 0) { @@ -414,7 +417,7 @@ if ($id > 0) ); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneTax'),$langs->trans('ConfirmCloneTax',$object->ref),'confirm_clone',$formclone,'yes'); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneTax'),$langs->trans('ConfirmCloneTax',$object->ref),'confirm_clone',$formclone,'yes'); } // Confirmation de la suppression de la charge @@ -445,34 +448,34 @@ if ($id > 0) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
      '.$langs->trans('Project') . ' '; - if ($user->rights->tax->charges->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(0, $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->tax->charges->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(0, $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.='
      '; @@ -492,7 +495,7 @@ if ($id > 0) print ''.$langs->trans("Type")."".$object->type_libelle.""; print ""; - // Period end date + // Period end date print "".$langs->trans("PeriodEndDate").""; print ""; if ($action == 'edit') @@ -517,51 +520,51 @@ if ($id > 0) } // Amount - if ($action == 'edit') - { - print ''.$langs->trans("AmountTTC").""; - print ''; - print ""; - } - else { - print ''.$langs->trans("AmountTTC").''.price($object->amount,0,$outputlangs,1,-1,-1,$conf->currency).''; - } + if ($action == 'edit') + { + print ''.$langs->trans("AmountTTC").""; + print ''; + print ""; + } + else { + print ''.$langs->trans("AmountTTC").''.price($object->amount,0,$outputlangs,1,-1,-1,$conf->currency).''; + } - // Mode of payment - print ''; - print ''; - if ($action != 'editmode') - print ''; - print '
      '; - print $langs->trans('PaymentMode'); - print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . '
      '; - print ''; - if ($action == 'editmode') { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); - } else { - $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); - } - print ''; + // Mode of payment + print ''; + print ''; + if ($action != 'editmode') + print ''; + print '
      '; + print $langs->trans('PaymentMode'); + print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . '
      '; + print ''; + if ($action == 'editmode') { + $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); + } else { + $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); + } + print ''; - // Bank Account - if (! empty($conf->banque->enabled)) - { - print ''; - print ''; - print '
      '; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->tax->charges->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 + if (! empty($conf->banque->enabled)) + { + print ''; + print ''; + print '
      '; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->tax->charges->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 ''; @@ -569,77 +572,108 @@ if ($id > 0) print '
      '; print '
      '; + $nbcols = 3; + if (! empty($conf->banque->enabled)) { + $nbcols ++; + } + /* * Payments */ $sql = "SELECT p.rowid, p.num_paiement, datep as dp, p.amount,"; - $sql.= "c.code as type_code,c.libelle as paiement_type"; + $sql.= " c.code as type_code,c.libelle as paiement_type,"; + $sql.= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal'; $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge 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.= ", ".MAIN_DB_PREFIX."c_paiement as c "; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " WHERE p.fk_charge = ".$id; $sql.= " AND p.fk_charge = cs.rowid"; $sql.= " AND cs.entity = ".$conf->entity; $sql.= " AND p.fk_typepaiement = c.id"; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " ORDER BY dp DESC"; //print $sql; $resql = $db->query($sql); if ($resql) { - $totalpaye = 0; + $totalpaye = 0; - $num = $db->num_rows($resql); - $i = 0; $total = 0; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + $num = $db->num_rows($resql); + $i = 0; $total = 0; + print '
      '.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").''.$langs->trans("Amount").'
      '; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; - $var=true; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($resql); + if ($num > 0) + { + while ($i < $num) + { + $objp = $db->fetch_object($resql); - print "'; - print '\n"; - $labeltype=$langs->trans("PaymentType".$objp->type_code)!=("PaymentType".$objp->type_code)?$langs->trans("PaymentType".$objp->type_code):$objp->paiement_type; - print "\n"; - print '\n"; - print ""; - $totalpaye += $objp->amount; - $i++; - } - } - else - { + print ''; + print '\n"; + $labeltype=$langs->trans("PaymentType".$objp->type_code)!=("PaymentType".$objp->type_code)?$langs->trans("PaymentType".$objp->type_code):$objp->paiement_type; + print "\n"; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; + $bankaccountstatic->number = $objp->banumber; - print ''; - } + if (! empty($conf->accounting->enabled)) { + $bankaccountstatic->account_number = $objp->account_number; - //if ($object->status == ChargeSociales::STATUS_DRAFT) - //{ - print "\n"; - print "\n"; + $accountingjournal = new AccountingJournal($db); + $accountingjournal->fetch($objp->fk_accountancy_journal); + $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0,1,1,'',1); + } - $resteapayer = $object->amount - $totalpaye; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + print ''; + } + print '\n"; + print ""; + $totalpaye += $objp->amount; + $i++; + } + } + else + { - print ""; - print '\n"; - //} - print "
      '.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").'' . $langs->trans('BankAccount') . ''.$langs->trans("Amount").'
      "; - print ''.img_object($langs->trans("Payment"),"payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp),'day')."".$labeltype.' '.$objp->num_paiement."'.price($objp->amount)."
      '; + print ''.img_object($langs->trans("Payment"),"payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp),'day')."".$labeltype.' '.$objp->num_paiement."
      '.$langs->trans("None").'
      ".$langs->trans("AlreadyPaid")." :".price($totalpaye)."
      ".$langs->trans("AmountExpected")." :".price($object->amount)."
      '; + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print ''.price($objp->amount)."
      ".$langs->trans("RemainderToPay")." :'.price($resteapayer)."
      "; - $db->free($resql); + print ''.$langs->trans("None").''; + print ''; + print ''; + } + + print ''.$langs->trans("AlreadyPaid")." :".price($totalpaye)."\n"; + print ''.$langs->trans("AmountExpected")." :".price($object->amount)."\n"; + + $resteapayer = $object->amount - $totalpaye; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + + print ''.$langs->trans("RemainderToPay")." :"; + print ''.price($resteapayer)."\n"; + + print ""; + $db->free($resql); } else { - dol_print_error($db); + dol_print_error($db); } print '
      '; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 83fe7d8b6b6..dc089c13e30 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -83,7 +83,7 @@ class ChargeSociales extends CommonObject $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id AND p.entity IN (' . getEntity('c_paiement').')'; if ($ref) $sql.= " WHERE cs.rowid = ".$ref; else $sql.= " WHERE cs.rowid = ".$id; diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 1d553831f99..0036c61fef9 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -33,6 +33,7 @@ class PaymentSocialContribution extends CommonObject { public $element='paiementcharge'; //!< Id that identify managed objects public $table_element='paiementcharge'; //!< Name of table without prefix where object is stored + public $picto = 'payment'; var $fk_charge; var $datec=''; @@ -78,7 +79,7 @@ class PaymentSocialContribution extends CommonObject $now=dol_now(); dol_syslog(get_class($this)."::create", LOG_DEBUG); - + // Validate parametres if (! $this->datepaye) { @@ -125,7 +126,7 @@ class PaymentSocialContribution extends CommonObject if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."paiementcharge"); - + // Insere tableau des montants / factures foreach ($this->amounts as $key => $amount) { @@ -137,7 +138,7 @@ class PaymentSocialContribution extends CommonObject // If we want to closed payed invoices if ($closepaidcontrib) { - + $contrib=new ChargeSociales($this->db); $contrib->fetch($contribid); $paiement = $contrib->getSommePaiement(); @@ -205,6 +206,7 @@ class PaymentSocialContribution extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."paiementcharge as t)"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepaiement = pt.id"; + $sql.= " AND pt.entity = " . getEntity('c_paiement'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -612,6 +614,68 @@ class PaymentSocialContribution extends CommonObject } } + + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + function LibStatut($status,$mode=0) + { + global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + + $langs->load('compta'); + /*if ($mode == 0) + { + if ($status == 0) return $langs->trans('ToValidate'); + if ($status == 1) return $langs->trans('Validated'); + } + if ($mode == 1) + { + if ($status == 0) return $langs->trans('ToValidate'); + if ($status == 1) return $langs->trans('Validated'); + } + if ($mode == 2) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); + } + if ($mode == 3) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4'); + } + if ($mode == 4) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); + } + if ($mode == 5) + { + if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); + } + if ($mode == 6) + { + if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); + }*/ + return ''; + } + /** * Return clicable name (with picto eventually) * 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 ''; 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/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index 879e9b69ee7..0bdff23007a 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -133,7 +133,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs,"; $sql.= " ".MAIN_DB_PREFIX."paiementcharge as pc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " WHERE cs.fk_type = c.id AND pc.fk_charge = cs.rowid"; $sql.= " AND cs.entity = ".$conf->entity; if ($year > 0) diff --git a/htdocs/compta/tva/reglement.php b/htdocs/compta/tva/reglement.php index 0d4d827e694..c22fb4ed30a 100644 --- a/htdocs/compta/tva/reglement.php +++ b/htdocs/compta/tva/reglement.php @@ -100,7 +100,7 @@ $bankstatic = new Account($db); $sql = "SELECT t.rowid, t.amount, t.label, t.datev as dv, t.datep as dp, t.fk_typepayment as type, t.num_payment, t.fk_bank, pst.code as payment_code,"; $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id AND pst.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE t.entity = ".$conf->entity; diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index 04c62107e83..c885f0869de 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -210,7 +210,7 @@ else dol_fiche_head($head, 'agenda', $title, -1, 'contact'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
      '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) @@ -257,30 +257,33 @@ else } - print '
      '; + //print '
      '; + //print '
      '; + + $morehtmlcenter=''; if (! empty($conf->agenda->enabled)) { if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.= ''.$langs->trans("AddAction").''; } else { - print ''.$langs->trans("AddAction").''; + $morehtmlcenter.= ''.$langs->trans("AddAction").''; } } - print '
      '; if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) { + print '
      '; + $param='&id='.$id; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - - print load_fiche_titre($langs->trans("TasksHistoryForThisContact"),'',''); + print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); // List of all actions $filters=array(); diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 2d6f728b502..dc6d19614f9 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -396,6 +396,15 @@ if (empty($reshook)) $action = 'edit'; } } + + if (! $error && empty($errors)) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + } } } @@ -541,7 +550,7 @@ else { print ''; print ''; - print $objsoc->getNomUrl(1); + print $objsoc->getNomUrl(1, 'contact'); print ''; print ''; print ''; @@ -1055,7 +1064,7 @@ else } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
      '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) @@ -1063,7 +1072,7 @@ else $objsoc->fetch($object->socid); // Thirdparty $morehtmlref.=$langs->trans('ThirdParty') . ' : '; - if ($objsoc->id > 0) $morehtmlref.=$objsoc->getNomUrl(1); + if ($objsoc->id > 0) $morehtmlref.=$objsoc->getNomUrl(1, 'contact'); else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
      '; diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 2329ae63685..7e9437f5442 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -987,38 +987,52 @@ class Contact extends CommonObject * Return name of contact with link (and eventually picto) * Use $this->id, $this->lastname, $this->firstname, this->civility_id * - * @param int $withpicto Include picto with link - * @param string $option Where the link point to - * @param int $maxlen Max length of - * @param string $moreparam Add more param into URL - * @return string String with URL + * @param int $withpicto Include picto with link + * @param string $option Where the link point to + * @param int $maxlen Max length of + * @param string $moreparam Add more param into URL + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$option='',$maxlen=0,$moreparam='') + function getNomUrl($withpicto=0, $option='', $maxlen=0, $moreparam='', $save_lastsearch_value=-1) { global $conf, $langs, $hookmanager; $result=''; - $label = '' . $langs->trans("ShowContact") . ''; - $label.= '
      ' . $langs->trans("Name") . ': '.$this->getFullName($langs); - //if ($this->civility_id) $label.= '
      ' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code - if (! empty($this->poste)) $label.= '
      ' . $langs->trans("Poste") . ': '.$this->poste; - $label.= '
      ' . $langs->trans("EMail") . ': '.$this->email; - $phonelist=array(); - if ($this->phone_pro) $phonelist[]=$this->phone_pro; - if ($this->phone_mobile) $phonelist[]=$this->phone_mobile; - if ($this->phone_perso) $phonelist[]=$this->phone_perso; - $label.= '
      ' . $langs->trans("Phone") . ': '.join(', ',$phonelist); - $label.= '
      ' . $langs->trans("Address") . ': '.dol_format_address($this, 1, ' ', $langs); - $link = 'global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowContact"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.= ' class="classfortooltip">'; + $label = '' . $langs->trans("ShowContact") . ''; + $label.= '
      ' . $langs->trans("Name") . ': '.$this->getFullName($langs); + //if ($this->civility_id) $label.= '
      ' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code + if (! empty($this->poste)) $label.= '
      ' . $langs->trans("Poste") . ': '.$this->poste; + $label.= '
      ' . $langs->trans("EMail") . ': '.$this->email; + $phonelist=array(); + if ($this->phone_pro) $phonelist[]=$this->phone_pro; + if ($this->phone_mobile) $phonelist[]=$this->phone_mobile; + if ($this->phone_perso) $phonelist[]=$this->phone_perso; + $label.= '
      ' . $langs->trans("Phone") . ': '.join(', ',$phonelist); + $label.= '
      ' . $langs->trans("Address") . ': '.dol_format_address($this, 1, ' ', $langs); + + $url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id; + + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $url .= $moreparam; + + $linkstart = '
      global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowContact"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.= ' class="classfortooltip">'; if (! is_object($hookmanager)) { @@ -1030,18 +1044,17 @@ class Contact extends CommonObject $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook > 0) $linkclose = $hookmanager->resPrint; - $link.=$linkclose; - + $linkstart.=$linkclose; $linkend=''; if ($option == 'xxx') { - $link = ''; + $linkstart = ''; $linkend=''; } - if ($withpicto) $result.=($link.img_object($label, 'contact', 'class="classfortooltip"').$linkend.' '); - $result.=$link.($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)).$linkend; + if ($withpicto) $result.=($linkstart.img_object($label, 'contact', 'class="classfortooltip"').$linkend.' '); + $result.=$linkstart.($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)).$linkend; return $result; } diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index da8ef616a4f..a016fa87b31 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -107,8 +107,8 @@ if ($object->id) $totalsize+=$file['size']; } - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
      '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { @@ -120,11 +120,11 @@ if ($object->id) else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
      '; - + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - + print '
      '; - + print '
      '; print ''; @@ -147,7 +147,7 @@ if ($object->id) print ''; } }*/ - + // Civility print ''; + print ''; } if (! empty($arrayfields['p.firstname']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.poste']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.zip']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.town']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.phone']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.phone_perso']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.phone_mobile']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.fax']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.email']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.skype']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.thirdparty']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.priv']['checked'])) { - print ''; @@ -581,12 +581,12 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; + print ''; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['p.statut']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['p.import_key']['checked'])) { @@ -655,13 +655,13 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + } } } // Hook fields @@ -680,9 +680,9 @@ $i = 0; $totalarray=array(); while ($i < min($num,$limit)) { - $obj = $db->fetch_object($result); + $obj = $db->fetch_object($result); - print ''; + print ''; $contactstatic->lastname=$obj->lastname; $contactstatic->firstname=''; @@ -702,98 +702,98 @@ while ($i < min($num,$limit)) print '\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } // Name - if (! empty($arrayfields['p.lastname']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.lastname']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Firstname - if (! empty($arrayfields['p.firstname']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.firstname']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Zip - if (! empty($arrayfields['p.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['p.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Town - if (! empty($arrayfields['p.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Function - if (! empty($arrayfields['p.poste']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone - if (! empty($arrayfields['p.phone']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone perso - if (! empty($arrayfields['p.phone_perso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone mobile - if (! empty($arrayfields['p.phone_mobile']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Fax - if (! empty($arrayfields['p.fax']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // EMail - if (! empty($arrayfields['p.email']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Skype - if (! empty($arrayfields['p.skype']['checked'])) - { - if (! empty($conf->skype->enabled)) { print ''; } - if (! $i) $totalarray['nbfield']++; - } - // Company - if (! empty($arrayfields['p.thirdparty']['checked'])) - { + if (! empty($arrayfields['p.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Function + if (! empty($arrayfields['p.poste']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Phone + if (! empty($arrayfields['p.phone']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Phone perso + if (! empty($arrayfields['p.phone_perso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Phone mobile + if (! empty($arrayfields['p.phone_mobile']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Fax + if (! empty($arrayfields['p.fax']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // EMail + if (! empty($arrayfields['p.email']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Skype + if (! empty($arrayfields['p.skype']['checked'])) + { + if (! empty($conf->skype->enabled)) { print ''; } + if (! $i) $totalarray['nbfield']++; + } + // Company + if (! empty($arrayfields['p.thirdparty']['checked'])) + { print ''; - if (! $i) $totalarray['nbfield']++; - } + } + else + print ' '; + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Private/Public - if (! empty($arrayfields['p.priv']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Private/Public + if (! empty($arrayfields['p.priv']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -809,57 +809,57 @@ while ($i < min($num,$limit)) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['p.statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['p.import_key']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['p.import_key']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + } + print ''; + if (! $i) $totalarray['nbfield']++; - print "\n"; - $i++; + print "\n"; + $i++; } $db->free($result); diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index b52f9bf8727..1fa766e0913 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -74,8 +74,8 @@ if ($id > 0) $head = contact_prepare_head($object); dol_fiche_head($head, 'note', $title, -1, 'contact'); - - $linkback = ''.$langs->trans("BackToList").''; + + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
      '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) @@ -88,13 +88,13 @@ if ($id > 0) else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
      '; - + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - + $cssclass='titlefield'; //if ($action == 'editnote_public') $cssclass='titlefieldcreate'; //if ($action == 'editnote_private') $cssclass='titlefieldcreate'; - + print '
      '; print '
      '; @@ -107,12 +107,12 @@ if ($id > 0) print "
      '.$langs->trans("UserTitle").''; print $object->getCivilityLabel(); @@ -160,7 +160,7 @@ if ($object->id) print ''; dol_fiche_end(); - + $modulepart = 'contact'; $permission = $user->rights->societe->contact->creer; $permtoedit = $user->rights->societe->contact->creer; diff --git a/htdocs/contact/info.php b/htdocs/contact/info.php index 20d379b50d0..287c27d8b10 100644 --- a/htdocs/contact/info.php +++ b/htdocs/contact/info.php @@ -61,7 +61,7 @@ if ($id > 0) dol_fiche_head($head, 'info', $title, -1, 'contact'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', ''); @@ -71,11 +71,11 @@ if ($id > 0) print '
      '; print '
      '; - + dol_print_object_info($object); print ''; - + dol_fiche_end(); } diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 759831f7d57..02a25d8005c 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -90,6 +90,8 @@ $head = contact_prepare_head($object); dol_fiche_head($head, 'ldap', $title, -1, 'contact'); +$linkback = ''.$langs->trans("BackToList").''; + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', ''); print '
      '; diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index ebf7bc611f9..4b0356c8e52 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -95,25 +95,25 @@ $contextpage='contactlist'; $titre = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); if ($type == "p") { - $contextpage='contactprospectlist'; + $contextpage='contactprospectlist'; $titre.=' ('.$langs->trans("ThirdPartyProspects").')'; $urlfiche="card.php"; } if ($type == "c") { - $contextpage='contactcustomerlist'; + $contextpage='contactcustomerlist'; $titre.=' ('.$langs->trans("ThirdPartyCustomers").')'; $urlfiche="card.php"; } else if ($type == "f") { - $contextpage='contactsupplierlist'; + $contextpage='contactsupplierlist'; $titre.=' ('.$langs->trans("ThirdPartySuppliers").')'; $urlfiche="card.php"; } else if ($type == "o") { - $contextpage='contactotherlist'; + $contextpage='contactotherlist'; $titre.=' ('.$langs->trans("OthersNotLinkedToThirdParty").')'; $urlfiche=""; } @@ -128,31 +128,31 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'p.lastname'=>'Lastname', - 'p.firstname'=>'Firstname', - 'p.email'=>'EMail', - 's.nom'=>"ThirdParty", + 'p.lastname'=>'Lastname', + 'p.firstname'=>'Firstname', + 'p.email'=>'EMail', + 's.nom'=>"ThirdParty", ); // Definition of fields for list $arrayfields=array( 'p.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)), 'p.lastname'=>array('label'=>"Lastname", 'checked'=>1), - 'p.firstname'=>array('label'=>"Firstname", 'checked'=>1), - 'p.poste'=>array('label'=>"PostOrFunction", 'checked'=>1), - 'p.town'=>array('label'=>"Town", 'checked'=>0), - 'p.zip'=>array('label'=>"Zip", 'checked'=>0), - 'p.phone'=>array('label'=>"Phone", 'checked'=>1), - 'p.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), - 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1), - 'p.fax'=>array('label'=>"Fax", 'checked'=>1), - 'p.email'=>array('label'=>"EMail", 'checked'=>1), - 'p.skype'=>array('label'=>"Skype", 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), - 'p.thirdparty'=>array('label'=>"ThirdParty", 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), - 'p.priv'=>array('label'=>"ContactVisibility", 'checked'=>1, 'position'=>200), - 'p.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500), - 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), - 'p.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), + 'p.firstname'=>array('label'=>"Firstname", 'checked'=>1), + 'p.poste'=>array('label'=>"PostOrFunction", 'checked'=>1), + 'p.town'=>array('label'=>"Town", 'checked'=>0), + 'p.zip'=>array('label'=>"Zip", 'checked'=>0), + 'p.phone'=>array('label'=>"Phone", 'checked'=>1), + 'p.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), + 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1), + 'p.fax'=>array('label'=>"Fax", 'checked'=>1), + 'p.email'=>array('label'=>"EMail", 'checked'=>1), + 'p.skype'=>array('label'=>"Skype", 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), + 'p.thirdparty'=>array('label'=>"ThirdParty", 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), + 'p.priv'=>array('label'=>"ContactVisibility", 'checked'=>1, 'position'=>200), + 'p.datec'=>array('label'=>"DateCreationShort", 'checked'=>0, 'position'=>500), + 'p.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), + 'p.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), 'p.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), ); // Extra fields @@ -160,15 +160,15 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); } } $object=new Contact($db); if (($id > 0 || ! empty($ref)) && $action != 'add') { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); + $result=$object->fetch($id,$ref); + if ($result < 0) dol_print_error($db); } @@ -185,43 +185,43 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // 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'; - // Did we click on purge search criteria ? - if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers - { - $sall=""; - $search_id=''; - $search_firstlast_only=""; - $search_lastname=""; - $search_firstname=""; - $search_societe=""; - $search_poste=""; - $search_phone=""; - $search_phone_perso=""; - $search_phone_pro=""; - $search_phone_mobile=""; - $search_fax=""; - $search_email=""; - $search_skype=""; - $search_priv=""; - $search_status=-1; - $search_categ=''; - $search_categ_thirdparty=''; - $search_categ_supplier=''; - $search_import_key=''; - $toselect=''; - $search_array_options=array(); - } + // Did we click on purge search criteria ? + if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers + { + $sall=""; + $search_id=''; + $search_firstlast_only=""; + $search_lastname=""; + $search_firstname=""; + $search_societe=""; + $search_poste=""; + $search_phone=""; + $search_phone_perso=""; + $search_phone_pro=""; + $search_phone_mobile=""; + $search_fax=""; + $search_email=""; + $search_skype=""; + $search_priv=""; + $search_status=-1; + $search_categ=''; + $search_categ_thirdparty=''; + $search_categ_supplier=''; + $search_import_key=''; + $toselect=''; + $search_array_options=array(); + } - // Mass actions - $objectclass='Contact'; - $objectlabel='Contact'; - $permtoread = $user->rights->societe->lire; - $permtodelete = $user->rights->societe->supprimer; - $uploaddir = $conf->societe->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='Contact'; + $objectlabel='Contact'; + $permtoread = $user->rights->societe->lire; + $permtodelete = $user->rights->societe->supprimer; + $uploaddir = $conf->societe->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } if ($search_priv < 0) $search_priv=''; @@ -262,7 +262,7 @@ if (!$user->rights->societe->client->voir && !$socid) //restriction } if (! empty($userid)) // propre au commercial { - $sql .= " AND p.fk_user_creat=".$db->escape($userid); + $sql .= " AND p.fk_user_creat=".$db->escape($userid); } // Filter to exclude not owned private contacts @@ -303,37 +303,37 @@ if ($search_status != '' && $search_status >= 0) $sql.= " AND p.statut = ".$db-> if ($search_import_key) $sql.= natural_search("p.import_key",$search_import_key); if ($type == "o") // filtre sur type { - $sql .= " AND p.fk_soc IS NULL"; + $sql .= " AND p.fk_soc IS NULL"; } else if ($type == "f") // filtre sur type { - $sql .= " AND s.fournisseur = 1"; + $sql .= " AND s.fournisseur = 1"; } else if ($type == "c") // filtre sur type { - $sql .= " AND s.client IN (1, 3)"; + $sql .= " AND s.client IN (1, 3)"; } else if ($type == "p") // filtre sur type { - $sql .= " AND s.client IN (2, 3)"; + $sql .= " AND s.client IN (2, 3)"; } if (! empty($socid)) { - $sql .= " AND s.rowid = ".$socid; + $sql .= " AND s.rowid = ".$socid; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -342,19 +342,19 @@ $sql.=$hookmanager->resPrint; // Add order if ($view == "recent") { - $sql.= $db->order("p.datec","DESC"); + $sql.= $db->order("p.datec","DESC"); } else { - $sql.= $db->order($sortfield,$sortorder); + $sql.= $db->order($sortfield,$sortorder); } // Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); @@ -362,8 +362,8 @@ $sql.= $db->plimit($limit+1, $offset); $result = $db->query($sql); if (! $result) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($result); @@ -372,10 +372,10 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $seearch_cti != '')) { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); + exit; } $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'; @@ -409,9 +409,9 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available @@ -437,37 +437,37 @@ print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } if ($search_firstlast_only) { - print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); + print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); } $moreforfilter=''; if (! empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
      '; + $moreforfilter.='
      '; $moreforfilter.=$langs->trans('Categories'). ': '; $moreforfilter.=$formother->select_categories(Categorie::TYPE_CONTACT,$search_categ,'search_categ',1); $moreforfilter.='
      '; if (empty($type) || $type == 'c' || $type == 'p') { - $moreforfilter.='
      '; - if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; - else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; - else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); - $moreforfilter.='
      '; + $moreforfilter.='
      '; + if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; + else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; + else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); + $moreforfilter.='
      '; } if (empty($type) || $type == 'f') { - $moreforfilter.='
      '; + $moreforfilter.='
      '; $moreforfilter.=$langs->trans('SuppliersCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); - $moreforfilter.='
      '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); + $moreforfilter.='
      '; } } if ($moreforfilter) @@ -476,7 +476,7 @@ if ($moreforfilter) print $moreforfilter; $parameters=array('type'=>$type); $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; print '
      '; } @@ -497,79 +497,79 @@ if (! empty($arrayfields['p.rowid']['checked'])) } if (! empty($arrayfields['p.lastname']['checked'])) { - print '
      '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; + print ''; $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); print $form->selectarray('search_priv',$selectarray,$search_priv,1); print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { - $crit=$val; + $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); $searchclass=''; if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; @@ -604,21 +604,21 @@ print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print ''; - print ''; + print ''; - print ''; + print ''; - print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); - print ''; + print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); + print '
      '; print $obj->rowid; print "'; - print $contactstatic->getNomUrl(1,'',0); - print ''; + print $contactstatic->getNomUrl(1,'',0); + print ''.$obj->firstname.''.$obj->firstname.''.$obj->zip.''.$obj->zip.''.$obj->town.''.dol_trunc($obj->poste,20).''.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->fax,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).''.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).''.$obj->town.''.dol_trunc($obj->poste,20).''.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->fax,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).''.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).''; - if ($obj->socid) - { + if ($obj->socid) + { $objsoc = new Societe($db); $objsoc->fetch($obj->socid); print $objsoc->getNomUrl(1); - } - else - print ' '; - print ''.$contactstatic->LibPubPriv($obj->priv).''.$contactstatic->LibPubPriv($obj->priv).''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$contactstatic->getLibStatut(3).''; - print $obj->import_key; - print "'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$contactstatic->getLibStatut(3).''; + print $obj->import_key; + print "'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; + // Action column + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; if (in_array($obj->rowid, $arrayofselected)) $selected=1; print ''; - } - print '
      "; - + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
      '; - + dol_fiche_end(); } diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index 30fa10b5ddc..9e85ef98294 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -60,7 +60,7 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->societe->contact $object->old_firstname=''; // Logo/Photo save $dir= $conf->societe->dir_output.'/contact/' . get_exdir($object->id,0,0,1,$object,'contact').'/photos'; - + $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); if ($file_OK) { @@ -88,7 +88,7 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->societe->contact else { // Create thumbs - $object->addThumbs($newfile); + $object->addThumbs($newfile); } } } @@ -147,26 +147,26 @@ if ($action == 'edit') print ''; dol_fiche_head($head, 'perso', $title, 0, 'contact'); - + print ''; // Ref print ''; - + // Photo print ''; // Name @@ -216,7 +216,7 @@ if ($action == 'edit') print "
      '.$langs->trans("Ref").''; print $object->id; print ''; print $form->showphoto('contact',$object)."\n"; if ($object->photo) print "
      \n"; - + print ''; - + if ($object->photo) print ''; print ''; print ''; print '
      '.$langs->trans("Delete").'

      '.$langs->trans("PhotoFile").'
      '; - + print '
      "; dol_fiche_end(); - + print '
      '; print ''; print '     '; @@ -228,11 +228,11 @@ if ($action == 'edit') else { // View mode - + dol_fiche_head($head, 'perso', $title, -1, 'contact'); - - $linkback = ''.$langs->trans("BackToList").''; - + + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
      '; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { @@ -244,13 +244,13 @@ else else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany"); } $morehtmlref.='
      '; - - + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); - - + + print '
      '; - + print '
      '; print ''; diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 46fa2b3ca87..2122c958e34 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 @@ -327,11 +327,11 @@ if (empty($reshook)) $label = $lines[$i]->product_label; } - $desc .= ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):''; + $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,64 +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++; + } - // 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]); - } - } + $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++; + } - if (! $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]); + } + } + + 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'; @@ -509,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']; @@ -546,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; @@ -616,149 +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')) { - $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid'))) - { - $db->begin(); + 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 ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; + if (!$error) { + $objectline = new ContratLigne($db); + if ($objectline->fetch(GETPOST('elrowid'))) + { + $db->begin(); - $vat_rate = GETPOST('eltva_tx'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; + if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; - // 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); + $vat_rate = GETPOST('eltva_tx'); + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - $txtva = $vat_rate; + // 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); - // 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. - } + $txtva = $vat_rate; - // ajout prix d'achat - $fk_fournprice = $_POST['fournprice']; - if ( ! empty($_POST['buying_price']) ) - $pa_ht = $_POST['buying_price']; - else - $pa_ht = null; + // 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. + } - $fk_unit = GETPOST('unit', 'alpha'); + // ajout prix d'achat + $fk_fournprice = $_POST['fournprice']; + if ( ! empty($_POST['buying_price']) ) + $pa_ht = $_POST['buying_price']; + else + $pa_ht = null; - $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; + $fk_unit = GETPOST('unit', 'alpha'); - if ($fk_unit > 0) { - $objectline->fk_unit = GETPOST('unit'); - } else { - $objectline->fk_unit = null; - } + $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; - // 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; + if ($fk_unit > 0) { + $objectline->fk_unit = GETPOST('unit'); + } else { + $objectline->fk_unit = null; + } - // TODO verifier price_min si fk_product et multiprix + // 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; - $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'); - } + // 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'); + } + } } 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) @@ -830,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'; @@ -839,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') { @@ -855,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 { @@ -864,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; + } } @@ -1033,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 ''; @@ -1112,7 +1130,7 @@ if ($action == 'create') print ''; print ''; - // Thirdparty + // Thirdparty print ''; print ''; if ($socid>0) @@ -1126,7 +1144,7 @@ if ($action == 'create') { print ''; } print ''."\n"; @@ -1145,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 /* *************************************************************************** */ @@ -1222,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 @@ -1331,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 ''; @@ -1396,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 '
      @@ -1976,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; @@ -1997,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->creer; + $delallowed = $user->rights->contrat->supprimer; - $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'; @@ -2127,8 +2145,8 @@ else $somethingshown = $formactions->showactions($object, 'contract', $socid, 1); - print '
      '; - } + print '
      '; + } // Presend form $modelmail='contract'; @@ -2137,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..7e92b8d6efe --- /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 an 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 61cd62bd338..d54c2b521ff 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -1400,13 +1400,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 +1617,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 +1626,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 +1703,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 +1774,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; @@ -1938,19 +1940,29 @@ class Contrat extends CommonObject /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $maxlength Max length of ref - * @param int $notooltip 1=Disable tooltip - * @return string Chaine avec URL + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlength Max length of ref + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlength=0,$notooltip=0) + function getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1) { global $conf, $langs, $user; $result=''; $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id; - $picto = 'contract'; + + //if ($option !== 'nolink') + //{ + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + //} + + $picto = 'contract'; $label = ''; if ($user->rights->contrat->lire) { @@ -2333,7 +2345,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) @@ -3023,7 +3045,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)."',"; @@ -3041,8 +3063,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/contrat/contact.php b/htdocs/contrat/contact.php index 8510888cf35..aeb433cf455 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -134,9 +134,9 @@ if ($id > 0 || ! empty($ref)) // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; + - $morehtmlref=''; //if (! empty($modCodeContract->code_auto)) { $morehtmlref.=$object->ref; @@ -144,7 +144,7 @@ if ($id > 0 || ! empty($ref)) $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); }*/ - + $morehtmlref.='
      '; // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1); @@ -196,10 +196,10 @@ if ($id > 0 || ! empty($ref)) print '
      '; print '
      '; - + print ''; - + // Ligne info remises tiers print '\n"; + $i++; + } + $db->free($resql); - print ''; + print '
      '.$langs->trans('Discount').''; if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); @@ -225,7 +225,7 @@ if ($id > 0 || ! empty($ref)) print ''; dol_fiche_end(); - + print '
      '; // Contacts lines diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index 132ab187777..351bdc74a46 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -107,7 +107,7 @@ if ($object->id) // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; @@ -170,7 +170,7 @@ if ($object->id) print '
      '; print '
      '; - + print ''; print ''; print ''; @@ -179,7 +179,7 @@ if ($object->id) print ''; dol_fiche_end(); - + $modulepart = 'contract'; $permission = $user->rights->contrat->creer; $permtoedit = $user->rights->contrat->creer; diff --git a/htdocs/contrat/info.php b/htdocs/contrat/info.php index 95ab0b9ca25..7f5d0c103fa 100644 --- a/htdocs/contrat/info.php +++ b/htdocs/contrat/info.php @@ -62,7 +62,7 @@ dol_fiche_head($head, 'info', $langs->trans("Contract"), -1, 'contract'); // Contract card -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 2afee019bed..611eae49e4c 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -62,6 +62,9 @@ $socid=GETPOST('socid'); $search_user=GETPOST('search_user','int'); $search_sale=GETPOST('search_sale','int'); $search_product_category=GETPOST('search_product_category','int'); +$search_dfmonth=GETPOST('search_dfmonth','int'); +$search_dfyear=GETPOST('search_dfyear','int'); +$search_op2df=GETPOST('search_op2df'); $day=GETPOST("day","int"); $year=GETPOST("year","int"); $month=GETPOST("month","int"); @@ -103,38 +106,39 @@ $extralabels = $extrafields->fetch_name_optionals_label('contrat'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'c.ref'=>'Ref', - 'c.ref_customer'=>'RefCustomer', - 'c.ref_supplier'=>'RefSupplier', - 's.nom'=>"ThirdParty", - 'cd.description'=>'Description', - 'c.note_public'=>'NotePublic', + 'c.ref'=>'Ref', + 'c.ref_customer'=>'RefCustomer', + 'c.ref_supplier'=>'RefSupplier', + 's.nom'=>"ThirdParty", + 'cd.description'=>'Description', + 'c.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["c.note_private"]="NotePrivate"; $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.email'=>array('label'=>$langs->trans("ThirdPartyEmail"), 'checked'=>0), + 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'c.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'c.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.email'=>array('label'=>$langs->trans("ThirdPartyEmail"), 'checked'=>0), 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'sale_representative'=>array('label'=>$langs->trans("SalesRepresentative"), 'checked'=>1), - 'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1), - 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'sale_representative'=>array('label'=>$langs->trans("SalesRepresentative"), 'checked'=>1), + 'c.date_contrat'=>array('label'=>$langs->trans("DateContract"), 'checked'=>1), + 'c.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'c.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'lower_planned_end_date'=>array('label'=>$langs->trans("LowerDateEndPlannedShort"), 'checked'=>1, 'position'=>900), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -157,9 +161,12 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $day=''; $month=''; $year=''; - $search_name=""; - $search_email=""; - $search_town=''; + $search_dfmonth=''; + $search_dfyear=''; + $search_op2df=''; + $search_name=""; + $search_email=""; + $search_town=''; $search_zip=""; $search_state=""; $search_type=''; @@ -167,9 +174,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_contract=""; $search_ref_customer=""; $search_ref_supplier=""; - $search_user=''; - $search_sale=''; - $search_product_category=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; $sall=""; $search_status=""; $toselect=''; @@ -178,12 +185,12 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', if (empty($reshook)) { - $objectclass='Contrat'; - $objectlabel='Contracts'; - $permtoread = $user->rights->contrat->lire; - $permtodelete = $user->rights->contrat->supprimer; - $uploaddir = $conf->contrat->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass='Contrat'; + $objectlabel='Contracts'; + $permtoread = $user->rights->contrat->lire; + $permtodelete = $user->rights->contrat->supprimer; + $uploaddir = $conf->contrat->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -205,6 +212,7 @@ $sql.= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_ $sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name,"; +$sql.= " MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") as lower_planned_end_date,"; $sql.= ' SUM('.$db->ifsql("cd.statut=0",1,0).') as nb_initial,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NULL OR cd.date_fin_validite >= '".$db->idate($now)."')",1,0).') as nb_running,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now)."')",1,0).') as nb_expired,'; @@ -227,8 +235,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= " WHERE c.fk_soc = s.rowid "; $sql.= ' AND c.entity IN ('.getEntity('contract').')'; @@ -237,12 +245,12 @@ if ($socid) $sql.= " AND s.rowid = ".$db->escape($socid); if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($month > 0) { - if ($year > 0 && empty($day)) - $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; - else if ($year > 0 && ! empty($day)) - $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; - else - $sql.= " AND date_format(c.date_contrat, '%m') = '".$month."'"; + if ($year > 0 && empty($day)) + $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND c.date_contrat BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(c.date_contrat, '%m') = '".$month."'"; } else if ($year > 0) { @@ -262,26 +270,32 @@ if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.elemen // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; +if ($search_dfyear > 0) +{ +// $sql.= " AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") ".$search_op2df."= '".$db->idate(($search_op2df == "<" ? dol_get_last_day($search_dfyear,$search_dfmonth,false) : dol_get_first_day($search_dfyear,$search_dfmonth,false)))."'"; +} + $sql.= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; $sql.= ' s.rowid, s.nom, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; $sql.= " typent.code,"; $sql.= " state.code_departement, state.nom"; +//$sql.= " MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").")"; // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); // Add where from hooks @@ -289,20 +303,25 @@ $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; +if ($search_dfyear > 0) +{ + $sql.= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") ".$search_op2df."= '".$db->idate(($search_op2df == "<" ? dol_get_last_day($search_dfyear,$search_dfmonth,false) : dol_get_first_day($search_dfyear,$search_dfmonth,false)))."'"; +} + $sql.= $db->order($sortfield,$sortorder); $totalnboflines=0; $result=$db->query($sql); if ($result) { - $totalnboflines = $db->num_rows($result); + $totalnboflines = $db->num_rows($result); } $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit + 1, $offset); @@ -310,10 +329,10 @@ $sql.= $db->plimit($limit + 1, $offset); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; + $num = $db->num_rows($resql); + $i = 0; - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected=is_array($toselect)?$toselect:array(); if ($socid > 0) { @@ -322,36 +341,42 @@ if ($resql) if (empty($search_name)) $search_name = $soc->name; } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall != '') $param.='&sall='.$sall; - if ($search_contract != '') $param.='&search_contract='.$search_contract; - if ($search_name != '') $param.='&search_name='.$search_name; - if ($search_email != '') $param.='&search_email='.$search_email; - if ($search_ref_supplier != '') $param.='&search_ref_supplier='.$search_ref_supplier; - if ($search_sale != '') $param.='&search_sale=' .$search_sale; - if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall != '') $param.='&sall='.urlencode($sall); + if ($search_contract != '') $param.='&search_contract='.urlencode($search_contract); + if ($search_name != '') $param.='&search_name='.urlencode($search_name); + if ($search_email != '') $param.='&search_email='.urlencode($search_email); + if ($search_ref_customer != '') $param.='&search_ref_customer='.urlencode($search_ref_customer); + if ($search_ref_supplier != '') $param.='&search_ref_supplier='.urlencode($search_ref_supplier); + if ($search_op2df != '') $param.='&search_op2df='.urlencode($search_op2df); + if ($search_dfyear != '') $param.='&search_dfyear='.urlencode($search_dfyear); + if ($search_dfmonth != '') $param.='&search_dfmonth='.urlencode($search_dfmonth); + if ($search_sale != '') $param.='&search_sale=' .urlencode($search_sale); + if ($search_user != '') $param.='&search_user=' .urlencode($search_user); + if ($search_product_category != '') $param.='&search_product_category=' .urlencode($search_product_category); + if ($show_files) $param.='&show_files=' .urlencode($show_files); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } - // List of mass actions available - $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + // List of mass actions available + $arrayofmassactions = array( + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), + ); + if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - print ''; - if ($optioncss != '') print ''; + print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; @@ -359,41 +384,41 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); + print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); - if ($massaction == 'presend') - { - $topicmail="SendContractRef"; - $modelmail="contract"; - $objecttmp=new Contrat($db); - $trackid='con'.$object->id; + if ($massaction == 'presend') + { + $topicmail="SendContractRef"; + $modelmail="contract"; + $objecttmp=new Contrat($db); + $trackid='con'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; - } + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_form.tpl.php'; + } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - $moreforfilter=''; + $moreforfilter=''; - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter.='
      '; - $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; - $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); - $moreforfilter.='
      '; - } + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { + $langs->load("commercial"); + $moreforfilter.='
      '; + $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; + $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); + $moreforfilter.='
      '; + } // If the user can view other users if ($user->rights->user->user->lire) { $moreforfilter.='
      '; $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
      '; } // If the user can view categories of products @@ -407,409 +432,440 @@ if ($resql) $moreforfilter.=''; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; - if (! empty($moreforfilter)) - { - print '
      '; - print $moreforfilter; - print '
      '; - } + if (! empty($moreforfilter)) + { + print '
      '; + print $moreforfilter; + print '
      '; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
      '; - print '
      '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
      '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
      '."\n"; + print '
      '; + print '
      '."\n"; - print ''; - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.email']['checked'])) - { - print ''; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) print ''; - // Zip - if (! empty($arrayfields['s.zip']['checked'])) print ''; - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print ''; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - } - // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - // Date contract - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print ''; - } - print ''; - print "\n"; + print ''; + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.ref_customer']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.ref_supplier']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print ''; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) print ''; + // Zip + if (! empty($arrayfields['s.zip']['checked'])) print ''; + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + } + // Company type + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + } + if (! empty($arrayfields['sale_representative']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + // Date contract + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print ''; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print ''; + } + // First end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print ''; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print ''; + } + print ''; + print "\n"; - print ''; - if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); + print ''; + if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); + if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { + if (! empty($arrayfields["ef.".$key]['checked'])) + { $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.date_creation","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['status']['checked'])) - { - print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); - } + if (! empty($arrayfields['lower_planned_end_date']['checked'])) print_liste_field_titre($arrayfields['lower_planned_end_date']['label'],$_SERVER["PHP_SELF"],"lower_planned_end_date","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['status']['checked'])) + { + print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; + print "\n"; - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); + while ($i < min($num,$limit)) + { + $obj = $db->fetch_object($resql); - $contracttmp->ref=$obj->ref; - $contracttmp->id=$obj->rowid; - $contracttmp->ref_customer=$obj->ref_customer; - $contracttmp->ref_supplier=$obj->ref_supplier; + $contracttmp->ref=$obj->ref; + $contracttmp->id=$obj->rowid; + $contracttmp->ref_customer=$obj->ref_customer; + $contracttmp->ref_supplier=$obj->ref_supplier; - print ''; - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; + print ''; + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.email']['checked'])) - { - print ''; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - // Sales representatives - print ''; - } - // Date - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['c.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print ''; - print ''; - print ''; - print ''; - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); + print ''; - print "\n"; - $i++; - } - $db->free($resql); + print ''; + } + if (! empty($arrayfields['c.ref_customer']['checked'])) + { + print ''; + } + if (! empty($arrayfields['c.ref_supplier']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + } + if (! empty($arrayfields['s.email']['checked'])) + { + print ''; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['sale_representative']['checked'])) + { + // Sales representatives + print ''; + } + // Date + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['c.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['c.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date lower end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['status']['checked'])) + { + print ''; + print ''; + print ''; + print ''; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; - print '
      '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - //print ' '.$langs->trans('Year').': '; - $syear = $year; - $formother->select_year($syear,'year',1, 20, 5); - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; - print ''; - print ''; - $searchpicto=$form->showFilterButtons(); - print $searchpicto; - print '
      '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $syear = $year; + $formother->select_year($syear,'year',1, 20, 5); + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; + $arrayofoperators=array('<'=>'<','>'=>'>'); + print $form->selectarray('search_op2df',$arrayofoperators,$search_op2df,0); + print '
      '; + print $formother->select_month($search_dfmonth, 'search_dfmonth', 1); + print ' '; + $formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5); + print '
      '; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '
      '; - print $contracttmp->getNomUrl(1); - if ($obj->nb_late) print img_warning($langs->trans("Late")); - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' '; - print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - print ''; - } + if ($obj->socid > 0) + { + $result=$socstatic->fetch($obj->socid); + } - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); - print '
      '; + print $contracttmp->getNomUrl(1); + if ($obj->nb_late) print img_warning($langs->trans("Late")); + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' '; + print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + print ''; + } - print ''.$obj->ref_customer.''.$obj->ref_supplier.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.$obj->email.''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; - if ($obj->socid > 0) - { - $result=$socstatic->fetch($obj->socid); - $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); - $nbofsalesrepresentative=count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { - print ''; - print $nbofsalesrepresentative; - print ''; - } - else if ($nbofsalesrepresentative > 0) - { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) - { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - print '
      '.$userstatic->getNomUrl(1); - $j++; - if ($j < $nbofsalesrepresentative) print ', '; - print '
      '; - } - } - //else print $langs->trans("NoSalesRepresentativeAffected"); - } - else - { - print ' '; - } - print '
      '.dol_print_date($db->jdate($obj->date_contrat), 'day').''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.($obj->nb_initial>0?$obj->nb_initial:'').''.($obj->nb_running>0?$obj->nb_running:'').''.($obj->nb_expired>0?$obj->nb_expired:'').''.($obj->nb_closed>0 ?$obj->nb_closed:'').''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; - } - print '
      '.$obj->ref_customer.''.$obj->ref_supplier.''; + //print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; + if ($obj->socid > 0) + { + print $socstatic->getNomUrl(1, ''); + } + print ''.$obj->email.''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; + if ($obj->socid > 0) + { + $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); + if ($listsalesrepresentatives < 0) dol_print_error($db); + $nbofsalesrepresentative=count($listsalesrepresentatives); + if ($nbofsalesrepresentative > 3) // We print only number + { + print ''; + print $nbofsalesrepresentative; + print ''; + } + else if ($nbofsalesrepresentative > 0) + { + $userstatic=new User($db); + $j=0; + foreach($listsalesrepresentatives as $val) + { + $userstatic->id=$val['id']; + $userstatic->lastname=$val['lastname']; + $userstatic->firstname=$val['firstname']; + print '
      '.$userstatic->getNomUrl(1); + $j++; + if ($j < $nbofsalesrepresentative) print ', '; + print '
      '; + } + } + //else print $langs->trans("NoSalesRepresentativeAffected"); + } + else + { + print ' '; + } + print '
      '.dol_print_date($db->jdate($obj->date_contrat), 'day').''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day'); + print ''.($obj->nb_initial>0?$obj->nb_initial:'').''.($obj->nb_running>0?$obj->nb_running:'').''.($obj->nb_expired>0?$obj->nb_expired:'').''.($obj->nb_closed>0 ?$obj->nb_closed:'').''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
      '; - print '
      '; + print "
      '; + print '
      '; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - /* + print ''; + + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->contrat->lire; - $delallowed=$user->rights->contrat->lire; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->contrat->lire; + $delallowed=$user->rights->contrat->lire; - print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
      '.$langs->trans("ShowTempMassFilesArea").''; - } + print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
      '.$langs->trans("ShowTempMassFilesArea").''; + } } else { - dol_print_error($db); + dol_print_error($db); } diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index 7d4927d19b8..ff0df34de67 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -74,7 +74,7 @@ if ($id > 0 || ! empty($ref)) // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; @@ -139,7 +139,7 @@ if ($id > 0 || ! empty($ref)) print ''; - + // Ligne info remises tiers print ''; print "
      '.$langs->trans('Discount').''; if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); @@ -161,9 +161,9 @@ if ($id > 0 || ! empty($ref)) print '
      "; - + print '
      '; - + //print '
      '; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/contrat/services.php b/htdocs/contrat/services.php index 9d1db86ded6..84a7fd17cc2 100644 --- a/htdocs/contrat/services.php +++ b/htdocs/contrat/services.php @@ -92,20 +92,20 @@ $result = restrictedArea($user, 'contrat',$contratid); if ($search_status != '') { - $tmp=explode('&', $search_status); - $mode=$tmp[0]; - if (empty($tmp[1])) $filter=''; - else - { - if ($tmp[1] == 'filter=notexpired') $filter='notexpired'; - if ($tmp[1] == 'filter=expired') $filter='expired'; - } + $tmp=explode('&', $search_status); + $mode=$tmp[0]; + if (empty($tmp[1])) $filter=''; + else + { + if ($tmp[1] == 'filter=notexpired') $filter='notexpired'; + if ($tmp[1] == 'filter=expired') $filter='expired'; + } } else { - $search_status = $mode; - if ($filter == 'expired') $search_status.='&filter=expired'; - if ($filter == 'notexpired') $search_status.='&filter=notexpired'; + $search_status = $mode; + if ($filter == 'expired') $search_status.='&filter=expired'; + if ($filter == 'notexpired') $search_status.='&filter=notexpired'; } $staticcontrat=new Contrat($db); @@ -113,24 +113,29 @@ $staticcontratligne=new ContratLigne($db); $companystatic=new Societe($db); $arrayfields=array( - 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), - 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), - 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), - 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), - 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), - 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), - 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), - //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) + 'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80), + 'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80), + 'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100), + 'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>100), + 'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>100), + 'cd.tva_tx'=>array('label'=>$langs->trans("VAT"), 'checked'=>0, 'position'=>100), + 'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>100), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100), + 'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")), + 'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)), + 'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)), + 'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)), + 'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1), + //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -149,37 +154,37 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // 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'; - 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 - { + 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_product_category=0; - $search_name=""; - $search_contract=""; - $search_service=""; - $search_status=-1; - $opouvertureprevuemonth=""; - $opouvertureprevueday=""; - $opouvertureprevueyear=""; - $filter_opouvertureprevue=""; - $op1month=""; - $op1day=""; - $op1year=""; - $filter_op1=""; - $op2month=""; - $op2day=""; - $op2year=""; - $filter_op2=""; - $opcloturemonth=""; - $opclotureday=""; - $opclotureyear=""; - $filter_opcloture=""; - $mode=''; - $filter=''; - $toselect=''; - $search_array_options=array(); - } + $search_name=""; + $search_contract=""; + $search_service=""; + $search_status=-1; + $opouvertureprevuemonth=""; + $opouvertureprevueday=""; + $opouvertureprevueyear=""; + $filter_opouvertureprevue=""; + $op1month=""; + $op1day=""; + $op1year=""; + $filter_op1=""; + $op2month=""; + $op2day=""; + $op2year=""; + $filter_op2=""; + $opcloturemonth=""; + $opclotureday=""; + $opclotureyear=""; + $filter_opcloture=""; + $mode=''; + $filter=''; + $toselect=''; + $search_array_options=array(); + } } @@ -199,7 +204,11 @@ if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk $sql.= " cd.date_ouverture_prevue,"; $sql.= " cd.date_ouverture,"; $sql.= " cd.date_fin_validite,"; -$sql.= " cd.date_cloture,"; +$sql.= " cd.qty,"; +$sql.= " cd.total_ht,"; +$sql.= " cd.total_tva,"; +$sql.= " cd.tva_tx,"; +$sql.= " cd.subprice,"; //$sql.= " cd.date_c as date_creation,"; $sql.= " cd.tms as date_update"; // Add fields from extrafields @@ -240,24 +249,24 @@ if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode_search=0; - if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode_search=0; + if (in_array($typ, array('int','double','real'))) $mode_search=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode_search=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode_search); + } } $sql .= $db->order($sortfield,$sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql .= $db->plimit($limit + 1, $offset); @@ -267,8 +276,8 @@ dol_syslog("contrat/services.php", LOG_DEBUG); $resql=$db->query($sql); if (! $resql) { - dol_print_error($db); - exit; + dol_print_error($db); + exit; } $num = $db->num_rows($resql); @@ -304,15 +313,15 @@ if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->contrat->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); //if ($massaction == 'presend') $arrayofmassactions=array(); @@ -337,8 +346,8 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } $morefilter = ''; @@ -346,12 +355,12 @@ $morefilter = ''; // If the user can view categories of products if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='
      '; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
      '; + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='
      '; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter.='
      '; } $parameters=array(); @@ -362,9 +371,9 @@ else $moreforfilter = $hookmanager->resPrint; if (! empty($moreforfilter)) { - print '
      '; - print $moreforfilter; - print '
      '; + print '
      '; + print $moreforfilter; + print '
      '; } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; @@ -377,6 +386,11 @@ print ''; if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'],$_SERVER["PHP_SELF"],"c.ref","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'],$_SERVER["PHP_SELF"],"p.description","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['cd.qty']['checked'])) print_liste_field_titre($arrayfields['cd.qty']['label'],$_SERVER["PHP_SELF"],"cd.qty","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['cd.total_ht']['checked'])) print_liste_field_titre($arrayfields['cd.total_ht']['label'],$_SERVER["PHP_SELF"],"cd.total_ht","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['cd.total_tva']['checked'])) print_liste_field_titre($arrayfields['cd.total_tva']['label'],$_SERVER["PHP_SELF"],"cd.total_tva","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['cd.tva_tx']['checked'])) print_liste_field_titre($arrayfields['cd.tva_tx']['label'],$_SERVER["PHP_SELF"],"cd.tva_tx","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['cd.subprice']['checked'])) print_liste_field_titre($arrayfields['cd.subprice']['label'],$_SERVER["PHP_SELF"],"cd.subprice","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture_prevue","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture","",$param,'align="center"',$sortfield,$sortorder); @@ -385,16 +399,16 @@ if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); $sortonfield = "ef.".$key; if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -418,21 +432,49 @@ if (! empty($arrayfields['c.ref']['checked'])) // Service label if (! empty($arrayfields['p.description']['checked'])) { - print ''; } +// detail lines +if (! empty($arrayfields['cd.qty']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['cd.total_ht']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['cd.total_tva']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['cd.tva_tx']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['cd.subprice']['checked'])) +{ + print ''; +} // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print ''; } + + if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -503,26 +545,26 @@ $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // N print $hookmanager->resPrint; if (! empty($arrayfields['cd.datec']['checked'])) { - // Date creation - print ''; + // Date creation + print ''; } if (! empty($arrayfields['cd.tms']['checked'])) { - // Date modification - print ''; + // Date modification + print ''; } if (! empty($arrayfields['status']['checked'])) { - // Status - print ''; @@ -549,16 +591,16 @@ while ($i < min($num,$limit)) print ''; // Ref - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; - } + } // Service - if (! empty($arrayfields['p.description']['checked'])) - { - print ''; - } + } + + if (! empty($arrayfields['cd.qty']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.total_ht']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.total_tva']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.tva_tx']['checked'])) + { + print ''; + } + if (! empty($arrayfields['cd.subprice']['checked'])) + { + print ''; + } + // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } + } // Start date - if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) - { + if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) + { print ''; } - if (! empty($arrayfields['cd.date_ouverture']['checked'])) - { - print ''; + if (! empty($arrayfields['cd.date_ouverture']['checked'])) + { + print ''; } // End date - if (! empty($arrayfields['cd.date_fin_validite']['checked'])) - { - print ''; - } - if (! empty($arrayfields['cd.date_cloture']['checked'])) - { - print ''; - } + print ''; + } + if (! empty($arrayfields['cd.date_cloture']['checked'])) + { + print ''; + } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -645,18 +719,18 @@ while ($i < min($num,$limit)) // Date creation if (! empty($arrayfields['cd.datec']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['cd.tms']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['status']['checked'])) @@ -664,11 +738,11 @@ while ($i < min($num,$limit)) print ''; } @@ -676,9 +750,9 @@ while ($i < min($num,$limit)) print ''; if (! $i) $totalarray['nbfield']++; diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index a1ff6417f92..bd86c5cb80c 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -91,10 +91,13 @@ if ($action == 'builddoc' && $permissioncreate) } else { - setEventMessages($langs->trans("FileGenerated"), null); + if (empty($donotredirect)) // This is se when include is done by bulk action "Bill Orders" + { + setEventMessages($langs->trans("FileGenerated"), null); - header('Location: '.$_SERVER['REQUEST_URI'].'#builddoc'); - exit; + header('Location: '.$_SERVER['REQUEST_URI'].'#builddoc'); + exit; + } } } } diff --git a/htdocs/core/actions_comments.inc.php b/htdocs/core/actions_comments.inc.php new file mode 100644 index 00000000000..ee45a035043 --- /dev/null +++ b/htdocs/core/actions_comments.inc.php @@ -0,0 +1,76 @@ + + * + * 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 . + * or see http://www.gnu.org/ + * + * $elementype must be defined. + */ + +/** + * \file htdocs/core/actions_comments.inc.php + * \brief Code for actions on comments pages + */ + + +require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php'; + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$comment = new Comment($db); + +/* + * Actions + */ + +if ($action == 'addcomment') +{ + $description = GETPOST('comment_description', 'none'); + if (!empty($description)) + { + $comment->description = $description; + $comment->datec = time(); + $comment->fk_element = GETPOST('id','int'); + $comment->element_type = GETPOST('comment_element_type','alpha'); + $comment->fk_user_author = $user->id; + $comment->entity = $conf->entity; + if ($comment->create($user) > 0) + { + setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); + header('Location: '.$varpage.'?id='.$id.($withproject?'&withproject=1':'')); + exit; + } + else + { + setEventMessages($comment->error, $comment->errors,'errors'); + $action=''; + } + } +} +if ($action == 'deletecomment') +{ + if ($comment->fetch($idcomment) >= 0) + { + if ($comment->delete($user) > 0) + { + setEventMessages($langs->trans("CommentDeleted"), null, 'mesgs'); + header('Location: '.$varpage.'?id='.$id.($withproject?'&withproject=1':'')); + exit; + } + else + { + setEventMessages($comment->error, $comment->errors,'errors'); + $action=''; + } + } +} \ No newline at end of file diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index 433288606ec..b6e70059da3 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -159,6 +159,7 @@ if ($action == 'add') $params['options'][$key] = $value; } } + $result=$extrafields->addExtraField( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), @@ -172,7 +173,7 @@ if ($action == 'add') $params, (GETPOST('alwayseditable', 'alpha')?1:0), (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), - (GETPOST('list', 'alpha')?1:0), + GETPOST('list', 'alpha'), // Same as visible -1=not visible by default in list, 1=visible, 0=not visible in list (GETPOST('ishidden', 'alpha')?1:0), GETPOST('computed_value','alpha'), (GETPOST('entitycurrentorall', 'alpha')?0:''), @@ -334,7 +335,7 @@ if ($action == 'update') $params, (GETPOST('alwayseditable', 'alpha')?1:0), (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), - (GETPOST('list', 'alpha')?1:0), + GETPOST('list', 'alpha'), // Same as visible -1=not visible by default in list, 1=visible, 0=not visible in list (GETPOST('ishidden', 'alpha')?1:0), GETPOST('default_value','alpha'), GETPOST('computed_value','alpha'), diff --git a/htdocs/core/actions_linkedfiles.inc.php b/htdocs/core/actions_linkedfiles.inc.php index 981de037c13..1f47a94f6d2 100644 --- a/htdocs/core/actions_linkedfiles.inc.php +++ b/htdocs/core/actions_linkedfiles.inc.php @@ -30,9 +30,9 @@ if (GETPOST('sendit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) if ($object->id) { if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) - $result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask')); + $result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha')); else - $result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask')); + $result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha')); } } elseif (GETPOST('linkit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) @@ -57,7 +57,7 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') if ($object->id) { $urlfile = GETPOST('urlfile', 'alpha'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). - if (GETPOST('section')) $file = $upload_dir . "/" . $urlfile; // For a delete of GED module urlfile contains full path from upload_dir + if (GETPOST('section', 'alpha')) $file = $upload_dir . "/" . $urlfile; // For a delete of GED module urlfile contains full path from upload_dir else // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. { $urlfile=basename($urlfile); @@ -116,7 +116,7 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') exit; } } -elseif ($action == 'confirm_updateline' && GETPOST('save') && GETPOST('link', 'alpha')) +elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha')) { require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; $langs->load('link'); @@ -150,8 +150,8 @@ elseif ($action == 'renamefile' && GETPOST('renamefilesave')) //var_dump($upload_dir);exit; if (! empty($upload_dir)) { - $filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom')); - $filenameto=dol_sanitizeFileName(GETPOST('renamefileto')); + $filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha')); + $filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha')); // Security: // Disallow file with some extensions. We rename them. diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index e0acad65ab8..4aec6179365 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -34,8 +34,8 @@ // Protection if (empty($objectclass) || empty($uploaddir)) { - dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined'); - exit; + dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined'); + exit; } @@ -43,433 +43,442 @@ if (empty($objectclass) || empty($uploaddir)) $maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS); if (! empty($massaction) && count($toselect) < 1) { - $error++; - setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); + $error++; + setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); } if (! $error && count($toselect) > $maxformassaction) { - setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); - $error++; + setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); + $error++; } if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail')) // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form { - $massaction='presend'; + $massaction='presend'; } if (! $error && $massaction == 'confirm_presend') { - $resaction = ''; - $nbsent = 0; - $nbignored = 0; - $langs->load("mails"); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $resaction = ''; + $nbsent = 0; + $nbignored = 0; + $langs->load("mails"); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $listofobjectid=array(); - $listofobjectthirdparties=array(); - $listofobjectref=array(); + $listofobjectid=array(); + $listofobjectthirdparties=array(); + $listofobjectref=array(); - if (! $error) - { - $thirdparty=new Societe($db); - if ($objecttmp->element == 'expensereport') $thirdparty=new User($db); + if (! $error) + { + $thirdparty=new Societe($db); + if ($objecttmp->element == 'expensereport') $thirdparty=new User($db); - $objecttmp=new $objectclass($db); - foreach($toselect as $toselectid) - { - $objecttmp=new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofobjectid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - if ($objecttmp->element == 'societe') $thirdpartyid=$objecttmp->id; - if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author; - $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; - $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; - } - } - } + $objecttmp=new $objectclass($db); + foreach($toselect as $toselectid) + { + $objecttmp=new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $listofobjectid[$toselectid]=$toselectid; + $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; + if ($objecttmp->element == 'societe') $thirdpartyid=$objecttmp->id; + if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author; + $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; + $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp; + } + } + } - // Check mandatory parameters - if (empty($user->email)) - { - $error++; - setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); - $massaction='presend'; - } + // Check mandatory parameters + if (empty($user->email)) + { + $error++; + setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); + $massaction='presend'; + } - $receiver=$_POST['receiver']; - if (! is_array($receiver)) - { - if (empty($receiver) || $receiver == '-1') $receiver=array(); - else $receiver=array($receiver); - } - if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); - $massaction='presend'; - } + $receiver=$_POST['receiver']; + if (! is_array($receiver)) + { + if (empty($receiver) || $receiver == '-1') $receiver=array(); + else $receiver=array($receiver); + } + if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); + $massaction='presend'; + } - if (! GETPOST('subject','none')) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); - $massaction='presend'; - } + if (! GETPOST('subject','none')) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); + $massaction='presend'; + } - // Loop on each recipient/thirdparty - if (! $error) - { - foreach ($listofobjectthirdparties as $thirdpartyid) - { - $result = $thirdparty->fetch($thirdpartyid); - if ($result < 0) - { - dol_print_error($db); - exit; - } + // Loop on each recipient/thirdparty + if (! $error) + { + foreach ($listofobjectthirdparties as $thirdpartyid) + { + $result = $thirdparty->fetch($thirdpartyid); + if ($result < 0) + { + dol_print_error($db); + exit; + } - $sendto=''; - $sendtocc=''; - $sendtobcc=''; - $sendtoid = array(); + $sendto=''; + $sendtocc=''; + $sendtobcc=''; + $sendtoid = array(); - // Define $sendto - $tmparray=array(); - if (trim($_POST['sendto'])) - { - // Recipients are provided into free text - $tmparray[] = trim($_POST['sendto']); - } - if (count($receiver)>0) - { - foreach($receiver as $key=>$val) - { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party or user - { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } - elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact - { - $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); - $sendtoid[] = $val; - } - } - } - $sendto=implode(',',$tmparray); + // Define $sendto + $tmparray=array(); + if (trim($_POST['sendto'])) + { + // Recipients are provided into free text + $tmparray[] = trim($_POST['sendto']); + } + if (count($receiver)>0) + { + foreach($receiver as $key=>$val) + { + // Recipient was provided from combo list + if ($val == 'thirdparty') // Id of third party or user + { + $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + } + elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact + { + $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); + $sendtoid[] = $val; + } + } + } + $sendto=implode(',',$tmparray); - // Define $sendtocc - $receivercc=$_POST['receivercc']; - if (! is_array($receivercc)) - { - if ($receivercc == '-1') $receivercc=array(); - else $receivercc=array($receivercc); - } - $tmparray=array(); - if (trim($_POST['sendtocc'])) - { - $tmparray[] = trim($_POST['sendtocc']); - } - if (count($receivercc) > 0) - { - foreach($receivercc as $key=>$val) - { - // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party - { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } - elseif ($val) // Id du contact - { - $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); - //$sendtoid[] = $val; TODO Add also id of contact in CC ? - } - } - } - $sendtocc=implode(',',$tmparray); + // Define $sendtocc + $receivercc=$_POST['receivercc']; + if (! is_array($receivercc)) + { + if ($receivercc == '-1') $receivercc=array(); + else $receivercc=array($receivercc); + } + $tmparray=array(); + if (trim($_POST['sendtocc'])) + { + $tmparray[] = trim($_POST['sendtocc']); + } + if (count($receivercc) > 0) + { + foreach($receivercc as $key=>$val) + { + // Recipient was provided from combo list + if ($val == 'thirdparty') // Id of third party + { + $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + } + elseif ($val) // Id du contact + { + $tmparray[] = $thirdparty->contact_get_property((int) $val,'email'); + //$sendtoid[] = $val; TODO Add also id of contact in CC ? + } + } + } + $sendtocc=implode(',',$tmparray); - //var_dump($listofobjectref);exit; - $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); - $listofqualifiedid=array(); - $listofqualifiedref=array(); - $thirdpartywithoutemail=array(); + //var_dump($listofobjectref);exit; + $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); + $listofqualifiedid=array(); + $listofqualifiedref=array(); + $thirdpartywithoutemail=array(); - foreach($listofobjectref[$thirdpartyid] as $objectid => $object) - { - //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); - if ($objectclass == 'Propal' && $object->statut == Propal::STATUS_DRAFT) - { - $langs->load("errors"); - $nbignored++; - $resaction.='
      '.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$object->ref).'

      '; - continue; // Payment done or started or canceled - } - if ($objectclass == 'Commande' && $object->statut == Commande::STATUS_DRAFT) - { - $langs->load("errors"); - $nbignored++; - $resaction.='
      '.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$object->ref).'

      '; - continue; - } - if ($objectclass == 'Facture' && $object->statut != Facture::STATUS_VALIDATED) - { - $langs->load("errors"); - $nbignored++; - $resaction.='
      '.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$object->ref).'

      '; - continue; // Payment done or started or canceled - } + foreach($listofobjectref[$thirdpartyid] as $objectid => $object) + { + //var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut); + if ($objectclass == 'Propal' && $object->statut == Propal::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
      '.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$object->ref).'

      '; + continue; // Payment done or started or canceled + } + if ($objectclass == 'Commande' && $object->statut == Commande::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
      '.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$object->ref).'

      '; + continue; + } + if ($objectclass == 'Facture' && $object->statut != Facture::STATUS_VALIDATED) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
      '.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$object->ref).'

      '; + continue; // Payment done or started or canceled + } - // Test recipient - if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) - { - if ($object->element == 'expensereport') - { + // Test recipient + if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) + { + if ($object->element == 'expensereport') + { $fuser = new User($db); $fuser->fetch($object->fk_user_author); $sendto = $fuser->email; - } - else - { - $object->fetch_thirdparty(); - $sendto = $object->thirdparty->email; - } - } + } + else + { + $object->fetch_thirdparty(); + $sendto = $object->thirdparty->email; + } + } - if (empty($sendto)) - { - //print "No recipient for thirdparty ".$object->thirdparty->name; - $nbignored++; - if (empty($thirdpartywithoutemail[$object->thirdparty->id])) - { - $resaction.='
      '.$langs->trans('NoRecipientEmail',$object->thirdparty->name).'

      '; - } - dol_syslog('No recipient for thirdparty: '.$object->thirdparty->name, LOG_WARNING); - $thirdpartywithoutemail[$object->thirdparty->id]=1; - continue; - } + if (empty($sendto)) + { + //print "No recipient for thirdparty ".$object->thirdparty->name; + $nbignored++; + if (empty($thirdpartywithoutemail[$object->thirdparty->id])) + { + $resaction.='
      '.$langs->trans('NoRecipientEmail',$object->thirdparty->name).'

      '; + } + dol_syslog('No recipient for thirdparty: '.$object->thirdparty->name, LOG_WARNING); + $thirdpartywithoutemail[$object->thirdparty->id]=1; + continue; + } - if ($_POST['addmaindocfile']) - { - // TODO Use future field $object->fullpathdoc to know where is stored default file - // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. - $filename=dol_sanitizeFileName($object->ref).'.pdf'; - $filedir=$uploaddir . '/' . dol_sanitizeFileName($object->ref); - $file = $filedir . '/' . $filename; - $mime = dol_mimetype($file); + if ($_POST['addmaindocfile']) + { + // TODO Use future field $object->fullpathdoc to know where is stored default file + // TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. + $filename=dol_sanitizeFileName($object->ref).'.pdf'; + $filedir=$uploaddir . '/' . dol_sanitizeFileName($object->ref); + $file = $filedir . '/' . $filename; + $mime = dol_mimetype($file); - if (dol_is_file($file)) - { - // Create form object - $attachedfiles=array( - 'paths'=>array_merge($attachedfiles['paths'],array($file)), - 'names'=>array_merge($attachedfiles['names'],array($filename)), - 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) - ); - } - else - { - $nbignored++; - $langs->load("errors"); - $resaction.='
      '.$langs->trans('ErrorCantReadFile',$file).'

      '; - dol_syslog('Failed to read file: '.$file, LOG_WARNING); - continue; - } - } + if (dol_is_file($file)) + { + // Create form object + $attachedfiles=array( + 'paths'=>array_merge($attachedfiles['paths'],array($file)), + 'names'=>array_merge($attachedfiles['names'],array($filename)), + 'mimes'=>array_merge($attachedfiles['mimes'],array($mime)) + ); + } + else + { + $nbignored++; + $langs->load("errors"); + $resaction.='
      '.$langs->trans('ErrorCantReadFile',$file).'

      '; + dol_syslog('Failed to read file: '.$file, LOG_WARNING); + continue; + } + } - // Object of thirdparty qualified - $listofqualifiedid[$objectid]=$object; - $listofqualifiedref[$objectid]=$object->ref; + // Object of thirdparty qualified + $listofqualifiedid[$objectid]=$object; + $listofqualifiedref[$objectid]=$object->ref; - //var_dump($listofqualifiedref); - } + //var_dump($listofqualifiedref); + } - // Send email if there is at least one qualified record - if (count($listofqualifiedid) > 0) - { - $langs->load("commercial"); + // Send email if there is at least one qualified record + if (count($listofqualifiedid) > 0) + { + $langs->load("commercial"); - $fromtype = GETPOST('fromtype'); - if ($fromtype === 'user') { - $from = $user->getFullName($langs) .' <'.$user->email.'>'; - } - elseif ($fromtype === 'company') { - $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; - } - elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { - $tmp=explode(',', $user->email_aliases); - $from = trim($tmp[($reg[1] - 1)]); - } - elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { - $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); - $from = trim($tmp[($reg[1] - 1)]); - } - else { - $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; - } + $fromtype = GETPOST('fromtype'); + if ($fromtype === 'user') { + $from = $user->getFullName($langs) .' <'.$user->email.'>'; + } + elseif ($fromtype === 'company') { + $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + } + elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $user->email_aliases); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; + $resql = $db->query($sql); + $obj = $db->fetch_object($resql); + if ($obj) + { + $from = $obj->label.' <'.$obj->email.'>'; + } + } + else { + $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; + } - $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); + $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); - // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty - $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); - $looparray=array(); - if (! $oneemailperrecipient) - { - $looparray = $listofqualifiedid; - } - else - { - $objectforloop=new $objectclass($db); - $objectforloop->thirdparty = $thirdparty; - $looparray[0]=$objectforloop; - } - //var_dump($looparray);exit; + // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty + $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); + $looparray=array(); + if (! $oneemailperrecipient) + { + $looparray = $listofqualifiedid; + } + else + { + $objectforloop=new $objectclass($db); + $objectforloop->thirdparty = $thirdparty; + $looparray[0]=$objectforloop; + } + //var_dump($looparray);exit; foreach ($looparray as $objecttmp) // $objecttmp is a real object or an empty if we choose to send one email per thirdparty instead of per record { - // Make substitution in email content - $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp); - $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedid)) : $objecttmp->id); - $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref); - $substitutionarray['__EMAIL__'] = $thirdparty->email; - $substitutionarray['__CHECK_READ__'] = ''; + // Make substitution in email content + $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp); + $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedid)) : $objecttmp->id); + $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref); + $substitutionarray['__EMAIL__'] = $thirdparty->email; + $substitutionarray['__CHECK_READ__'] = ''; - $parameters=array('mode'=>'formemail'); - complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters); + $parameters=array('mode'=>'formemail'); + complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters); - $subject=make_substitutions($subject, $substitutionarray); - $message=make_substitutions($message, $substitutionarray); + $subject=make_substitutions($subject, $substitutionarray); + $message=make_substitutions($message, $substitutionarray); - $filepath = $attachedfiles['paths']; - $filename = $attachedfiles['names']; - $mimetype = $attachedfiles['mimes']; + $filepath = $attachedfiles['paths']; + $filename = $attachedfiles['names']; + $mimetype = $attachedfiles['mimes']; - //var_dump($filepath); + //var_dump($filepath); - // Send mail (substitutionarray must be done just before this) - require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); - if ($mailfile->error) - { - $resaction.='
      '.$mailfile->error.'
      '; - } - else - { - $result=$mailfile->sendfile(); - if ($result) - { - $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'
      '; // Must not contain " + // Send mail (substitutionarray must be done just before this) + require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); + if ($mailfile->error) + { + $resaction.='
      '.$mailfile->error.'
      '; + } + else + { + $result=$mailfile->sendfile(); + if ($result) + { + $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'
      '; // Must not contain " - $error=0; + $error=0; - // Insert logs into agenda - foreach($listofqualifiedid as $objid => $object) - { - /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; + // Insert logs into agenda + foreach($listofqualifiedid as $objid => $object) + { + /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; if ($objectclass == 'Commande') $actiontypecode='AC_COM'; if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ - $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); - $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); - $actionmsg = dol_concatdesc($actionmsg, $message); - } - $actionmsg2=''; + $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + if ($message) + { + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); + } + $actionmsg2=''; - // Initialisation donnees - $object->sendtoid = 0; - $object->actionmsg = $actionmsg; // Long text - $object->actionmsg2 = $actionmsg2; // Short text - $object->fk_element = $objid; - $object->elementtype = $object->element; + // Initialisation donnees + $object->sendtoid = 0; + $object->actionmsg = $actionmsg; // Long text + $object->actionmsg2 = $actionmsg2; // Short text + $object->fk_element = $objid; + $object->elementtype = $object->element; - $triggername = strtoupper(get_class($object)) .'_SENTBYMAIL'; - if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYEMAIL'; - if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYEMAIL'; - if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYEMAIL'; - if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYEMAIL'; - if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL'; - if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; - if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL'; - if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL'; + $triggername = strtoupper(get_class($object)) .'_SENTBYMAIL'; + if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYEMAIL'; + if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYEMAIL'; + if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYEMAIL'; + if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYEMAIL'; + if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL'; + if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; + if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL'; + if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL'; - if (! empty($trigger_name)) - { - // Appel des triggers - include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - $interface=new Interfaces($db); - $result=$interface->run_triggers($trigger_name, $object, $user, $langs, $conf); - if ($result < 0) { $error++; $errors=$interface->errors; } - // Fin appel triggers + if (! empty($trigger_name)) + { + // Appel des triggers + include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); + $interface=new Interfaces($db); + $result=$interface->run_triggers($trigger_name, $object, $user, $langs, $conf); + if ($result < 0) { $error++; $errors=$interface->errors; } + // Fin appel triggers - if ($error) - { - setEventMessages($db->lasterror(), $errors, 'errors'); - dol_syslog("Error in trigger ".$trigger_name.' '.$db->lasterror(), LOG_ERR); - } - } + if ($error) + { + setEventMessages($db->lasterror(), $errors, 'errors'); + dol_syslog("Error in trigger ".$trigger_name.' '.$db->lasterror(), LOG_ERR); + } + } - $nbsent++; - } - } - else - { - $langs->load("other"); - if ($mailfile->error) - { - $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); - $resaction.='
      '.$mailfile->error.'
      '; - } - else - { - $resaction.='
      No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS
      '; - } - } - } + $nbsent++; + } + } + else + { + $langs->load("other"); + if ($mailfile->error) + { + $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); + $resaction.='
      '.$mailfile->error.'
      '; + } + else + { + $resaction.='
      No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS
      '; + } + } + } } - } - } + } + } - $resaction.=($resaction?'
      ':$resaction); - $resaction.=''.$langs->trans("ResultOfMailSending").':
      '."\n"; - $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n
      "; - $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n
      "; - $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n
      "; + $resaction.=($resaction?'
      ':$resaction); + $resaction.=''.$langs->trans("ResultOfMailSending").':
      '."\n"; + $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n
      "; + $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n
      "; + $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n
      "; - if ($nbsent) - { - $action=''; // Do not show form post if there was at least one successfull sent - //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); - setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); - setEventMessages($resaction, null, 'mesgs'); - } - else - { - //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file - setEventMessages($resaction, null, 'warnings'); - } + if ($nbsent) + { + $action=''; // Do not show form post if there was at least one successfull sent + //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); + setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); + setEventMessages($resaction, null, 'mesgs'); + } + else + { + //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file + setEventMessages($resaction, null, 'warnings'); + } - $action='list'; - $massaction=''; - } + $action='list'; + $massaction=''; + } } if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search')) @@ -480,59 +489,59 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se exit; } - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $objecttmp=new $objectclass($db); - $listofobjectid=array(); - $listofobjectthirdparties=array(); - $listofobjectref=array(); - foreach($toselect as $toselectid) - { - $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - $listofobjectid[$toselectid]=$toselectid; - $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; - $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; - $listofobjectref[$toselectid]=$objecttmp->ref; - } - } + $objecttmp=new $objectclass($db); + $listofobjectid=array(); + $listofobjectthirdparties=array(); + $listofobjectref=array(); + foreach($toselect as $toselectid) + { + $objecttmp=new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + $listofobjectid[$toselectid]=$toselectid; + $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid; + $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid; + $listofobjectref[$toselectid]=$objecttmp->ref; + } + } - $arrayofinclusion=array(); - foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote($tmppdf.'.pdf','/').'$'; - $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true); + $arrayofinclusion=array(); + foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote($tmppdf.'.pdf','/').'$'; + $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true); - // build list of files with full path - $files = array(); - foreach($listofobjectref as $basename) - { - foreach($listoffiles as $filefound) - { - if (strstr($filefound["name"],$basename)) - { - $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; - break; - } - } - } + // build list of files with full path + $files = array(); + foreach($listofobjectref as $basename) + { + foreach($listoffiles as $filefound) + { + if (strstr($filefound["name"],$basename)) + { + $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; + break; + } + } + } - // Define output language (Here it is not used because we do only merging existing PDF) - $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); - } + // Define output language (Here it is not used because we do only merging existing PDF) + $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->USE_PDFTK_FOR_PDF_CONCAT)) - { - // Create output dir if not exists + if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) + { + // Create output dir if not exists dol_mkdir($diroutputmassaction); // Defined name of merged file @@ -540,7 +549,7 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se $filename=preg_replace('/\s/','_',$filename); // Save merged file - if ($filter=='paye:0') + if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); @@ -548,112 +557,118 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se if ($year) $filename.='_'.$year; if ($month) $filename.='_'.$month; - if (count($files)>0) - { - $now=dol_now(); - $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; + if (count($files)>0) + { + $now=dol_now(); + $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; - $input_files = ''; - foreach($files as $f) { - $input_files.=' '.escapeshellarg($f); - } + $input_files = ''; + foreach($files as $f) { + $input_files.=' '.escapeshellarg($f); + } - $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file); - exec($cmd); + $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file); + exec($cmd); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); - $langs->load("exports"); - setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); - } - else - { - setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); - } - } - else { - // Create empty PDF - $formatarray=pdf_getFormat(); - $page_largeur = $formatarray['width']; - $page_hauteur = $formatarray['height']; - $format = array($page_largeur,$page_hauteur); + $langs->load("exports"); + setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); + } + } + else { + // Create empty PDF + $formatarray=pdf_getFormat(); + $page_largeur = $formatarray['width']; + $page_hauteur = $formatarray['height']; + $format = array($page_largeur,$page_hauteur); - $pdf=pdf_getInstance($format); + $pdf=pdf_getInstance($format); - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) + { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); - } - $pdf->SetFont(pdf_getPDFFont($outputlangs)); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - // Add all others - foreach($files as $file) - { + // Add all others + foreach($files as $file) + { // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); for ($i = 1; $i <= $pagecount; $i++) { - $tplidx = $pdf->importPage($i); - $s = $pdf->getTemplatesize($tplidx); - $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); - $pdf->useTemplate($tplidx); + $tplidx = $pdf->importPage($i); + $s = $pdf->getTemplatesize($tplidx); + $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); + $pdf->useTemplate($tplidx); } - } + } - // Create output dir if not exists - dol_mkdir($diroutputmassaction); + // Create output dir if not exists + dol_mkdir($diroutputmassaction); - // Defined name of merged file - $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel))); - $filename=preg_replace('/\s/','_',$filename); + // Defined name of merged file + $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel))); + $filename=preg_replace('/\s/','_',$filename); - // Save merged file - if ($filter=='paye:0') - { + // Save merged file + if (in_array($object->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) + { if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); - } - if ($year) $filename.='_'.$year; - if ($month) $filename.='_'.$month; - if ($pagecount) - { + } + if ($year) $filename.='_'.$year; + if ($month) $filename.='_'.$month; + if ($pagecount) + { $now=dol_now(); $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf'; $pdf->Output($file,'F'); if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + @chmod($file, octdec($conf->global->MAIN_UMASK)); - $langs->load("exports"); - setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); - } - else - { + $langs->load("exports"); + setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs'); + } + else + { setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors'); - } - } + } + } } // Remove a file from massaction area if ($action == 'remove_file') { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $langs->load("other"); - $upload_dir = $diroutputmassaction; - $file = $upload_dir . '/' . GETPOST('file'); - $ret=dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); - $action=''; + $langs->load("other"); + $upload_dir = $diroutputmassaction; + $file = $upload_dir . '/' . GETPOST('file'); + $ret=dol_delete_file($file); + if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + $action=''; } // Validate records if (! $error && $massaction == 'validate' && $permtocreate) { + if ($object->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) + { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); + $error++; + } if ($object->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { $langs->load("errors"); @@ -714,17 +729,17 @@ if (! $error && $massaction == 'validate' && $permtocreate) // Delete records if (! $error && $massaction == 'delete' && $permtodelete) { - $db->begin(); + $db->begin(); - $objecttmp=new $objectclass($db); - $nbok = 0; - foreach($toselect as $toselectid) - { - $result=$objecttmp->fetch($toselectid); - if ($result > 0) - { - // Refuse deletion for some status ? - /* + $objecttmp=new $objectclass($db); + $nbok = 0; + foreach($toselect as $toselectid) + { + $result=$objecttmp->fetch($toselectid); + if ($result > 0) + { + // Refuse deletion for some status ? + /* if ($objectclass == 'Facture' && $objecttmp->status == Facture::STATUS_DRAFT) { $langs->load("errors"); @@ -733,36 +748,36 @@ if (! $error && $massaction == 'delete' && $permtodelete) continue; }*/ - if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); - else $result = $objecttmp->delete($user); + if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); + else $result = $objecttmp->delete($user); - if ($result <= 0) - { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; - } - else $nbok++; - } - else - { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; - } - } + if ($result <= 0) + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + else $nbok++; + } + else + { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } - if (! $error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); - $db->commit(); - } - else - { - $db->rollback(); - } - //var_dump($listofobjectthirdparties);exit; + if (! $error) + { + if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + $db->commit(); + } + else + { + $db->rollback(); + } + //var_dump($listofobjectthirdparties);exit; } $parameters['toselect']=$toselect; diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 4439f0034ce..57b6ae80b6c 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -113,14 +113,14 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $result=$object->fetch($id); $sendtosocid=0; // Thirdparty on object - if (method_exists($object,"fetch_thirdparty") && ! in_array($object->element, array('societe','member'))) + if (method_exists($object,"fetch_thirdparty") && ! in_array($object->element, array('societe','member','user'))) { $result=$object->fetch_thirdparty(); if ($object->element == 'user' && $result == 0) $result=1; // Even if not found, we consider ok $thirdparty=$object->thirdparty; $sendtosocid=$thirdparty->id; } - else if ($object->element == 'member') + else if ($object->element == 'member' || $object->element == 'user') { $thirdparty=$object; if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id; @@ -258,6 +258,15 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); $from = trim($tmp[($reg[1] - 1)]); } + elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; + $resql = $db->query($sql); + $obj = $db->fetch_object($resql); + if ($obj) + { + $from = $obj->label.' <'.$obj->email.'>'; + } + } else { $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; } diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index 2d92bc8f938..f04e2e95b18 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -56,85 +56,85 @@ $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('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, '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('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, '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)); } 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('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, '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('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, '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) { - $arrayresult['searchintotasks']=array('img'=>'object_task', 'label'=>$langs->trans("SearchIntoTasks", $search_boxvalue), 'text'=>img_picto('','object_task').' '.$langs->trans("SearchIntoTasks", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/tasks/list.php?search_all='.urlencode($search_boxvalue)); -} - -if (! empty($conf->adherent->enabled) && empty($conf->global->MAIN_SEARCHFORM_ADHERENT_DISABLED) && $user->rights->adherent->lire) -{ - $arrayresult['searchintomember']=array('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->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) -{ - $arrayresult['searchintouser']=array('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['searchintotasks']=array('position'=>45, 'img'=>'object_task', 'label'=>$langs->trans("SearchIntoTasks", $search_boxvalue), 'text'=>img_picto('','object_task').' '.$langs->trans("SearchIntoTasks", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/tasks/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->propal->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_PROPAL_DISABLED) && $user->rights->propal->lire) { - $arrayresult['searchintopropal']=array('img'=>'object_propal', 'label'=>$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/comm/propal/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintopropal']=array('position'=>60, 'img'=>'object_propal', 'label'=>$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/comm/propal/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->commande->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_ORDER_DISABLED) && $user->rights->commande->lire) { - $arrayresult['searchintoorder']=array('img'=>'object_order', 'label'=>$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/commande/list.php?sall='.urlencode($search_boxvalue)); -} -if (! empty($conf->facture->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_INVOICE_DISABLED) && $user->rights->facture->lire) -{ - $arrayresult['searchintoinvoice']=array('img'=>'object_bill', 'label'=>$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/compta/facture/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoorder']=array('position'=>70, 'img'=>'object_order', 'label'=>$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/commande/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->expedition->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_SHIPMENT_DISABLED) && $user->rights->expedition->lire) { - $arrayresult['searchintoshipment']=array('img'=>'object_sending', 'label'=>$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'text'=>img_picto('','object_sending').' '.$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expedition/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoshipment']=array('position'=>80, 'img'=>'object_sending', 'label'=>$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'text'=>img_picto('','object_sending').' '.$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expedition/list.php?sall='.urlencode($search_boxvalue)); +} +if (! empty($conf->facture->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_INVOICE_DISABLED) && $user->rights->facture->lire) +{ + $arrayresult['searchintoinvoice']=array('position'=>90, 'img'=>'object_bill', 'label'=>$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/compta/facture/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->supplier_proposal->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_PROPAL_DISABLED) && $user->rights->supplier_proposal->lire) { - $arrayresult['searchintosupplierpropal']=array('img'=>'object_propal', 'label'=>$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/supplier_proposal/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierpropal']=array('position'=>100, 'img'=>'object_propal', 'label'=>$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/supplier_proposal/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_ORDER_DISABLED) && $user->rights->fournisseur->commande->lire) { - $arrayresult['searchintosupplierorder']=array('img'=>'object_order', 'label'=>$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/commande/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierorder']=array('position'=>110, 'img'=>'object_order', 'label'=>$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/commande/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_INVOICE_DISABLED) && $user->rights->fournisseur->facture->lire) { - $arrayresult['searchintosupplierinvoice']=array('img'=>'object_bill', 'label'=>$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierinvoice']=array('position'=>120, 'img'=>'object_bill', 'label'=>$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->contrat->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTRACT_DISABLED) && $user->rights->contrat->lire) { - $arrayresult['searchintocontract']=array('img'=>'object_contract', 'label'=>$langs->trans("SearchIntoContracts", $search_boxvalue), 'text'=>img_picto('','object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontract']=array('position'=>130, 'img'=>'object_contract', 'label'=>$langs->trans("SearchIntoContracts", $search_boxvalue), 'text'=>img_picto('','object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->ficheinter->enabled) && empty($conf->global->MAIN_SEARCHFORM_FICHINTER_DISABLED) && $user->rights->ficheinter->lire) { - $arrayresult['searchintointervention']=array('img'=>'object_intervention', 'label'=>$langs->trans("SearchIntoInterventions", $search_boxvalue), 'text'=>img_picto('','object_intervention').' '.$langs->trans("SearchIntoInterventions", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fichinter/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintointervention']=array('position'=>140, 'img'=>'object_intervention', 'label'=>$langs->trans("SearchIntoInterventions", $search_boxvalue), 'text'=>img_picto('','object_intervention').' '.$langs->trans("SearchIntoInterventions", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fichinter/list.php?sall='.urlencode($search_boxvalue)); } + // 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)); +} if (! empty($conf->expensereport->enabled) && empty($conf->global->MAIN_SEARCHFORM_EXPENSEREPORT_DISABLED) && $user->rights->expensereport->lire) { - $arrayresult['searchintoexpensereport']=array('img'=>'object_trip', 'label'=>$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'text'=>img_picto('','object_trip').' '.$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoexpensereport']=array('position'=>210, 'img'=>'object_trip', 'label'=>$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'text'=>img_picto('','object_trip').' '.$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); } if (! empty($conf->holiday->enabled) && empty($conf->global->MAIN_SEARCHFORM_HOLIDAY_DISABLED) && $user->rights->holiday->read) { - $arrayresult['searchintoleaves']=array('img'=>'object_holiday', 'label'=>$langs->trans("SearchIntoLeaves", $search_boxvalue), 'text'=>img_picto('','object_holiday').' '.$langs->trans("SearchIntoLeaves", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/holiday/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoleaves']=array('position'=>220, 'img'=>'object_holiday', 'label'=>$langs->trans("SearchIntoLeaves", $search_boxvalue), 'text'=>img_picto('','object_holiday').' '.$langs->trans("SearchIntoLeaves", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/holiday/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); } @@ -147,7 +147,7 @@ if (! empty($conf->hrm->enabled) && ! empty($conf->global->MAIN_SEARCHFORM_EMPLO */ // Execute hook addSearchEntry -$parameters=array('search_boxvalue'=>$search_boxvalue); +$parameters=array('search_boxvalue'=>$search_boxvalue, 'arrayresult'=>$arrayresult); $reshook=$hookmanager->executeHooks('addSearchEntry',$parameters); if (empty($reshook)) { @@ -155,6 +155,8 @@ if (empty($reshook)) } else $arrayresult=$hookmanager->resArray; +// Sort on position +$arrayresult = dol_sort_array($arrayresult, 'position'); // Print output if called by ajax or do nothing (var $arrayresult will be used) if called by an include if (! isset($usedbyinclude) || empty($usedbyinclude)) 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/antivir.class.php b/htdocs/core/class/antivir.class.php index 357f184eea8..b5f4f0e5539 100644 --- a/htdocs/core/class/antivir.class.php +++ b/htdocs/core/class/antivir.class.php @@ -63,9 +63,9 @@ class AntiVir if (preg_match('/\.virus$/i', $file)) { $this->errors='File has an extension saying file is a virus'; - return -97; + return -97; } - + $fullcommand=$this->getCliCommand($file); //$fullcommand='"c:\Program Files (x86)\ClamWin\bin\clamscan.exe" --database="C:\Program Files (x86)\ClamWin\lib" "c:\temp\aaa.txt"'; $fullcommand.=' 2>&1'; // This is to get error output diff --git a/htdocs/core/class/comment.class.php b/htdocs/core/class/comment.class.php new file mode 100644 index 00000000000..a21057662f2 --- /dev/null +++ b/htdocs/core/class/comment.class.php @@ -0,0 +1,324 @@ +db = $db; + } + + + /** + * Create into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + function create($user, $notrigger=0) + { + global $conf, $langs; + + $error=0; + + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."comment ("; + $sql.= "description"; + $sql.= ", datec"; + $sql.= ", fk_element"; + $sql.= ", element_type"; + $sql.= ", fk_user_author"; + $sql.= ", entity"; + $sql.= ", import_key"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($this->description)."'"; + $sql.= ", ".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null'); + $sql.= ", '".(isset($this->fk_element)?$this->fk_element:"null")."'"; + $sql.= ", '".$this->db->escape($this->element_type)."'"; + $sql.= ", '".(isset($this->fk_user_author)?$this->fk_user_author:"null")."'"; + $sql.= ", ".(!empty($this->entity)?$this->entity:'1'); + $sql.= ", ".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); + $sql.= ")"; + + //var_dump($this->db); + //echo $sql; + + $this->db->begin(); + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_comment"); + + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_COMMENT_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param int $ref ref object + * @return int <0 if KO, 0 if not found, >0 if OK + */ + function fetch($id, $ref='') + { + global $langs; + + $sql = "SELECT"; + $sql.= " c.rowid,"; + $sql.= " c.description,"; + $sql.= " c.datec,"; + $sql.= " c.tms,"; + $sql.= " c.fk_element,"; + $sql.= " c.element_type,"; + $sql.= " c.fk_user_author,"; + $sql.= " c.entity,"; + $sql.= " c.import_key"; + $sql.= " FROM ".MAIN_DB_PREFIX."comment as c"; + $sql.= " WHERE c.rowid = ".$id; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num_rows = $this->db->num_rows($resql); + + if ($num_rows) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->description = $obj->description; + $this->element_type = $obj->element_type; + $this->datec = $this->db->jdate($obj->datec); + $this->tms = $obj->tms; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_element = $obj->fk_element; + $this->entity = $obj->entity; + $this->import_key = $obj->import_key; + } + + $this->db->free($resql); + + if ($num_rows) return 1; + else return 0; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <=0 if KO, >0 if OK + */ + function update(User $user, $notrigger=0) + { + global $conf, $langs; + $error=0; + + // Clean parameters + if (isset($this->fk_element)) $this->fk_project=(int) trim($this->fk_element); + if (isset($this->fk_user_author)) $this->fk_user_author=(int) trim($this->fk_user_author); + if (isset($this->description)) $this->description=trim($this->description); + + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_comment SET"; + $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").","; + $sql.= " datec=".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null').","; + $sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").","; + $sql.= " element_type='".$this->db->escape($this->element_type)."',"; + $sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").","; + $sql.= " entity=".(!empty($this->entity)?$this->entity:'1').","; + $sql.= " import_key=".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); + $sql.= " WHERE rowid=".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_COMMENT_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // 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; + } + } + + + /** + * Delete task from database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger=0) + { + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + $error=0; + + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."comment"; + $sql.= " WHERE rowid=".$this->id; + + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('TASK_COMMENT_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + }else{ + $this->db->commit(); + return 1; + } + } + + + /** + * Load comments linked with current task + * + * @param string $element_type Element type + * @param int $fk_element Id of element + * @return array Comment array + */ + public static function fetchAllFor($element_type, $fk_element) + { + global $db,$conf; + $TComments = array(); + if(!empty($element_type) && !empty($fk_element)) { + $sql = "SELECT"; + $sql.= " c.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."comment as c"; + $sql.= " WHERE c.fk_element = ".$fk_element; + $sql.= " AND c.element_type = '".$db->escape($element_type)."'"; + $sql.= " AND c.entity = ".$conf->entity; + $sql.= " ORDER BY c.tms DESC"; + + dol_syslog("Comment::fetchAllFor", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num_rows = $db->num_rows($resql); + if ($num_rows > 0) + { + while($obj = $db->fetch_object($resql)) + { + $comment = new self($db); + $comment->fetch($obj->rowid); + $TComments[] = $comment; + } + } + $db->free($resql); + } + } + return $TComments; + } +} \ No newline at end of file diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 535200ab95a..937634de5d4 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -418,6 +418,21 @@ abstract class CommonDocGenerator $resarray[$array_key.'_total_discount_ht'] = ''; } + // Fetch project information if there is a project assigned to this object + if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0) + { + if (! is_object($object->project)) + { + $object->fetch_projet(); + } + + $resarray[$array_key.'_project_ref'] = $object->project->ref; + $resarray[$array_key.'_project_title'] = $object->project->title; + $resarray[$array_key.'_project_description'] = $object->project->description; + $resarray[$array_key.'_project_date_start'] = dol_print_date($object->project->date_start, 'day'); + $resarray[$array_key.'_project_date_end'] = dol_print_date($object->project->date_end, 'day'); + } + // Add vat by rates if (is_array($object->lines) && count($object->lines)>0) { diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 6bbde52cb58..2f6d72fb64e 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -450,8 +450,9 @@ abstract class CommonInvoice extends CommonObject $sqltemp = 'SELECT c.type_cdr,c.nbjour,c.decalage'; $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; - if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; - else $sqltemp.= " WHERE c.code='".$this->db->escape($cond_reglement)."'"; + $sqltemp.= " WHERE c.entity IN (" . getEntity('c_payment_term').")"; + if (is_numeric($cond_reglement)) $sqltemp.= " AND c.rowid=".$cond_reglement; + else $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG); $resqltemp=$this->db->query($sqltemp); diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index bd6f658185d..c410bc4b361 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -12,6 +12,7 @@ * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2016 Bahfir abbes * Copyright (C) 2017 ATM Consulting + * Copyright (C) 2017 Nicolas ZABOURI * * 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 @@ -39,24 +40,24 @@ */ abstract class CommonObject { - /** - * @var DoliDb Database handler (result of a new DoliDB) - */ + /** + * @var DoliDb Database handler (result of a new DoliDB) + */ public $db; /** * @var int The object identifier */ public $id; - /** - * @var string Error string - * @deprecated Use instead the array of error strings - * @see errors - */ - public $error; /** - * @var string[] Array of error strings - */ - public $errors=array(); + * @var string Error string + * @deprecated Use instead the array of error strings + * @see errors + */ + public $error; + /** + * @var string[] Array of error strings + */ + public $errors=array(); /** * @var string */ @@ -69,45 +70,45 @@ abstract class CommonObject * @var */ public $table_element_line; - /** - * @var string Key value used to track if data is coming from import wizard - */ - public $import_key; - /** - * @var mixed Contains data to manage extrafields - */ - public $array_options=array(); - /** - * @var int[] Array of linked objects ids. Loaded by ->fetchObjectLinked - */ - public $linkedObjectsIds; - /** - * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked - */ - public $linkedObjects; - /** - * @var Object To store a cloned copy of object before to edit it and keep track of old properties - */ - public $oldcopy; + /** + * @var string Key value used to track if data is coming from import wizard + */ + public $import_key; + /** + * @var mixed Contains data to manage extrafields + */ + public $array_options=array(); + /** + * @var int[] Array of linked objects ids. Loaded by ->fetchObjectLinked + */ + public $linkedObjectsIds; + /** + * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked + */ + public $linkedObjects; + /** + * @var Object To store a cloned copy of object before to edit it and keep track of old properties + */ + public $oldcopy; - /** - * @var string Column name of the ref field. - */ - protected $table_ref_field = ''; + /** + * @var string Column name of the ref field. + */ + protected $table_ref_field = ''; - // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them. + // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them. - /** - * @var string[] Can be used to pass information when only object is provided to method - */ - public $context=array(); + /** + * @var string[] Can be used to pass information when only object is provided to method + */ + public $context=array(); - /** - * @var string Contains canvas name if record is an alternative canvas record - */ - public $canvas; + /** + * @var string Contains canvas name if record is an alternative canvas record + */ + public $canvas; /** * @var Project The related project @@ -309,6 +310,12 @@ abstract class CommonObject */ public $lines; + /** + * @var mixed Contains comments + * @see fetchComments() + */ + public $comments=array(); + /** * @var int * @see setIncoterms() @@ -325,13 +332,13 @@ abstract class CommonObject */ public $location_incoterms; - public $name; - public $lastname; - public $firstname; - public $civility_id; + public $name; + public $lastname; + public $firstname; + public $civility_id; - // No constructor as it is an abstract class + // No constructor as it is an abstract class /** @@ -383,84 +390,84 @@ abstract class CommonObject return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):''); } - /** - * Return full name (civility+' '+name+' '+lastname) - * - * @param Translate $langs Language object for translation of civility - * @param int $option 0=No option, 1=Add civility - * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname - * @param int $maxlen Maximum length - * @return string String with full name - */ - function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0) - { - //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
      \n"; - $lastname=$this->lastname; - $firstname=$this->firstname; - if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:''))))); + /** + * Return full name (civility+' '+name+' '+lastname) + * + * @param Translate $langs Language object for translation of civility + * @param int $option 0=No option, 1=Add civility + * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname + * @param int $maxlen Maximum length + * @return string String with full name + */ + function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0) + { + //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."
      \n"; + $lastname=$this->lastname; + $firstname=$this->firstname; + if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:''))))); - $ret=''; - if ($option && $this->civility_id) - { - if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; - else $ret.=$this->civility_id.' '; - } + $ret=''; + if ($option && $this->civility_id) + { + if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' '; + else $ret.=$this->civility_id.' '; + } - $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder); + $ret.=dolGetFirstLastname($firstname, $lastname, $nameorder); - return dol_trunc($ret,$maxlen); - } + return dol_trunc($ret,$maxlen); + } - /** - * Return full address of contact - * - * @param int $withcountry 1=Add country into address string - * @param string $sep Separator to use to build string - * @return string Full address string - */ - function getFullAddress($withcountry=0,$sep="\n") - { - if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) - { - require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; - $tmparray=getCountry($this->country_id,'all'); - $this->country_code=$tmparray['code']; - $this->country =$tmparray['label']; - } + /** + * Return full address of contact + * + * @param int $withcountry 1=Add country into address string + * @param string $sep Separator to use to build string + * @return string Full address string + */ + function getFullAddress($withcountry=0,$sep="\n") + { + if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) + { + require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; + $tmparray=getCountry($this->country_id,'all'); + $this->country_code=$tmparray['code']; + $this->country =$tmparray['label']; + } - return dol_format_address($this, $withcountry, $sep); - } + return dol_format_address($this, $withcountry, $sep); + } - /** - * Return full address for banner - * - * @param string $htmlkey HTML id to make banner content unique - * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) - * @return string Full address string - */ - function getBannerAddress($htmlkey, $object) - { - global $conf, $langs; + /** + * Return full address for banner + * + * @param string $htmlkey HTML id to make banner content unique + * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) + * @return string Full address string + */ + function getBannerAddress($htmlkey, $object) + { + global $conf, $langs; - $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS + $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS - $contactid=0; - $thirdpartyid=0; - if ($this->element == 'societe') - { - $thirdpartyid=$this->id; - } - if ($this->element == 'contact') - { - $contactid=$this->id; + $contactid=0; + $thirdpartyid=0; + if ($this->element == 'societe') + { + $thirdpartyid=$this->id; + } + if ($this->element == 'contact') + { + $contactid=$this->id; $thirdpartyid=$object->fk_soc; - } - if ($this->element == 'user') - { - $contactid=$this->contact_id; + } + if ($this->element == 'user') + { + $contactid=$this->contact_id; $thirdpartyid=$object->fk_soc; - } + } $out=''; @@ -488,7 +495,7 @@ abstract class CommonObject } if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'
      ':''); - if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone + if (! empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone $out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; } if (! empty($this->phone_pro)) { @@ -503,7 +510,7 @@ abstract class CommonObject if (! empty($this->fax)) { $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX',' ','fax',$langs->trans("Fax")); $outdone++; } - if (! empty($this->office_phone)) { + if (! empty($this->office_phone)) { $out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL',' ','phone',$langs->trans("PhonePro")); $outdone++; } if (! empty($this->user_mobile)) { @@ -520,7 +527,7 @@ abstract class CommonObject $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1); $outdone++; } - if (! empty($this->url)) + if (! empty($this->url)) { $out.=dol_print_url($this->url,'_goout',0,1); $outdone++; @@ -535,1022 +542,1022 @@ abstract class CommonObject $out.=''; return $out; - } + } - /** - * Add a link between element $this->element and a contact - * - * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link - * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL - * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) - * @param int $notrigger Disable all triggers - * @return int <0 if KO, >0 if OK - */ - function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0) - { - global $user,$langs; + /** + * Add a link between element $this->element and a contact + * + * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link + * @param int $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL + * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) + * @param int $notrigger Disable all triggers + * @return int <0 if KO, >0 if OK + */ + function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0) + { + global $user,$langs; - dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger"); + dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger"); - // Check parameters - if ($fk_socpeople <= 0) - { - $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX","1"); - dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); - return -1; - } - if (! $type_contact) - { - $langs->load("errors"); - $this->error=$langs->trans("ErrorWrongValueForParameterX","2"); - dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); - return -2; - } - - $id_type_contact=0; - if (is_numeric($type_contact)) - { - $id_type_contact=$type_contact; - } - else - { - // On recherche id type_contact - $sql = "SELECT tc.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - $sql.= " AND tc.source='".$this->db->escape($source)."'"; - $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1"; - //print $sql; - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) $id_type_contact=$obj->rowid; - } - } - - if ($id_type_contact == 0) - { - $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; - dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT"); - return -3; - } - - $datecreate = dol_now(); - - // Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error - $TListeContacts=$this->liste_contact(-1, $source); - $already_added=false; - if(!empty($TListeContacts)) { - foreach($TListeContacts as $array_contact) { - if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) { - $already_added=true; - break; - } - } - } - - if(!$already_added) { - - $this->db->begin(); - - // Insertion dans la base - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; - $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; - $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; - $sql.= "'".$this->db->idate($datecreate)."'"; - $sql.= ", 4, ". $id_type_contact; - $sql.= ")"; - - $resql=$this->db->query($sql); - if ($resql) - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - } - - $this->db->commit(); - return 1; - } - else - { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $this->error=$this->db->errno(); - $this->db->rollback(); - echo 'err rollback'; - return -2; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } - } else return 0; - } - - /** - * Copy contact from one element to current - * - * @param CommonObject $objFrom Source element - * @param string $source Nature of contact ('internal' or 'external') - * @return int >0 if OK, <0 if KO - */ - function copy_linked_contact($objFrom, $source='internal') - { - $contacts = $objFrom->liste_contact(-1, $source); - foreach($contacts as $contact) - { - if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) - { - $this->error=$this->db->lasterror(); - return -1; - } - } - return 1; - } - - /** - * Update a link to contact line - * - * @param int $rowid Id of line contact-element - * @param int $statut New status of link - * @param int $type_contact_id Id of contact type (not modified if 0) - * @param int $fk_socpeople Id of soc_people to update (not modified if 0) - * @return int <0 if KO, >= 0 if OK - */ - function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0) - { - // Insertion dans la base - $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; - $sql.= " statut = ".$statut; - if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; - if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'"; - $sql.= " where rowid = ".$rowid; - $resql=$this->db->query($sql); - if ($resql) - { - return 0; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Delete a link to contact line - * - * @param int $rowid Id of contact link line to delete - * @param int $notrigger Disable all triggers - * @return int >0 if OK, <0 if KO - */ - function delete_contact($rowid, $notrigger=0) - { - global $user; - - - $this->db->begin(); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE rowid =".$rowid; - - dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Delete all links between an object $this and all its contacts - * - * @param string $source '' or 'internal' or 'external' - * @param string $code Type of contact (code or id) - * @return int >0 if OK, <0 if KO - */ - function delete_linked_contact($source='',$code='') - { - $temp = array(); - $typeContact = $this->liste_type_contact($source,'',0,0,$code); - - foreach($typeContact as $key => $value) - { - array_push($temp,$key); - } - $listId = implode(",", $temp); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE element_id = ".$this->id; - if ($listId) - $sql.= " AND fk_c_type_contact IN (".$listId.")"; - - dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else + // Check parameters + if ($fk_socpeople <= 0) { - $this->error=$this->db->lasterror(); - return -1; - } - } - - /** - * Get array of all contacts for an object - * - * @param int $statut Status of links to get (-1=all) - * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) - * @param int $list 0:Return array contains all properties, 1:Return array contains just id - * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) - * @return array Array of contacts - */ - function liste_contact($statut=-1,$source='external',$list=0,$code='') - { - global $langs; - - $tab=array(); - - $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user - if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; - if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact"; - $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; - $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; - $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; - if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; - if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; - $sql.= " WHERE ec.element_id =".$this->id; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element='".$this->db->escape($this->element)."'"; - if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'"; - if ($source == 'internal') $sql.= " AND tc.source = 'internal'"; - if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'"; - $sql.= " AND tc.active=1"; - if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'"; - $sql.=" ORDER BY t.lastname ASC"; - - dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); - $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 (! $list) - { - $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id, - 'nom'=>$obj->lastname, // For backward compatibility - 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, - 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); - } - else - { - $tab[$i]=$obj->id; - } - - $i++; - } - - return $tab; - } - else - { - $this->error=$this->db->lasterror(); - dol_print_error($this->db); - return -1; - } - } - - - /** - * Update status of a contact linked to object - * - * @param int $rowid Id of link between object and contact - * @return int <0 if KO, >=0 if OK - */ - function swapContactStatus($rowid) - { - $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; - $sql.= " tc.code, tc.libelle"; - //$sql.= ", s.fk_soc"; - $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; - //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe - $sql.= " WHERE ec.rowid =".$rowid; - $sql.= " AND ec.fk_c_type_contact=tc.rowid"; - $sql.= " AND tc.element = '".$this->db->escape($this->element)."'"; - - dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $newstatut = ($obj->statut == 4) ? 5 : 4; - $result = $this->update_contact($rowid, $newstatut); - $this->db->free($resql); - return $result; - } - else - { - $this->error=$this->db->error(); - dol_print_error($this->db); - return -1; - } - - } - - /** - * Return array with list of possible values for type of contacts - * - * @param string $source 'internal', 'external' or 'all' - * @param string $order Sort order by : 'position', 'code', 'rowid'... - * @param int $option 0=Return array id->label, 1=Return array code->label - * @param int $activeonly 0=all status of contact, 1=only the active - * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') - * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) - */ - function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='') - { - global $langs; - - if (empty($order)) $order='position'; - if ($order == 'position') $order.=',code'; - - $tab = array(); - $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; - if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types - if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'"; - if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'"; - $sql.= $this->db->order($order,'ASC'); - - //print "sql=".$sql; - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - $transkey="TypeContact_".$this->element."_".$source."_".$obj->code; - $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); - if (empty($option)) $tab[$obj->rowid]=$libelle_type; - else $tab[$obj->code]=$libelle_type; - $i++; - } - return $tab; - } - else - { - $this->error=$this->db->lasterror(); - //dol_print_error($this->db); - return null; - } - } - - /** - * Return id of contacts for a source and a contact code. - * Example: contact client de facturation ('external', 'BILLING') - * Example: contact client de livraison ('external', 'SHIPPING') - * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL') - * - * @param string $source 'external' or 'internal' - * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ... - * @param int $status limited to a certain status - * @return array List of id for such contacts - */ - function getIdContact($source,$code,$status=0) - { - global $conf; - - $result=array(); - $i=0; - //cas particulier pour les expeditions - if($this->element=='shipping' && $this->origin_id != 0) { - $id=$this->origin_id; - $element='commande'; - } else { - $id=$this->id; - $element=$this->element; - } - - $sql = "SELECT ec.fk_socpeople"; - $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; - if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,"; - if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE ec.element_id = ".$id; - $sql.= " AND ec.fk_socpeople = c.rowid"; - if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")"; - if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; - $sql.= " AND ec.fk_c_type_contact = tc.rowid"; - $sql.= " AND tc.element = '".$element."'"; - $sql.= " AND tc.source = '".$source."'"; - $sql.= " AND tc.code = '".$code."'"; - $sql.= " AND tc.active = 1"; - if ($status) $sql.= " AND ec.statut = ".$status; - - dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - $result[$i]=$obj->fk_socpeople; - $i++; - } - } - else - { - $this->error=$this->db->error(); - return null; - } - - return $result; - } - - /** - * Load object contact with id=$this->contactid into $this->contact - * - * @param int $contactid Id du contact. Use this->contactid if empty. - * @return int <0 if KO, >0 if OK - */ - function fetch_contact($contactid=null) - { - if (empty($contactid)) $contactid=$this->contactid; - - if (empty($contactid)) return 0; - - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - $contact = new Contact($this->db); - $result=$contact->fetch($contactid); - $this->contact = $contact; - return $result; - } - - /** - * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty - * - * @param int $force_thirdparty_id Force thirdparty id - * @return int <0 if KO, >0 if OK - */ - function fetch_thirdparty($force_thirdparty_id=0) - { - global $conf; - - if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) - return 0; - - require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; - - $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); - if ($force_thirdparty_id) - $idtofetch = $force_thirdparty_id; - - if ($idtofetch) { - $thirdparty = new Societe($this->db); - $result = $thirdparty->fetch($idtofetch); - $this->thirdparty = $thirdparty; - - // Use first price level if level not defined for third party - if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) { - $this->thirdparty->price_level = 1; - } - - return $result; - } else - return -1; - } - - - /** - * Looks for an object with ref matching the wildcard provided - * It does only work when $this->table_ref_field is set - * - * @param string $ref Wildcard - * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO - */ - public function fetchOneLike($ref) - { - if (!$this->table_ref_field) { - return 0; - } - - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1'; - - $query = $this->db->query($sql); - - if (!$this->db->num_rows($query)) { - return 0; - } - - $result = $this->db->fetch_object($query); - - return $this->fetch($result->rowid); - } - - /** - * Load data for barcode into properties ->barcode_type* - * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but - * if it is not defined, ->element must be defined to know default barcode type. - * - * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) - */ - function fetch_barcode() - { - global $conf; - - dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); - - $idtype=$this->barcode_type; - if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined - { - if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; - else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; - else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); - } - - if ($idtype > 0) - { - if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded - { - $sql = "SELECT rowid, code, libelle as label, coder"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; - $sql.= " WHERE rowid = ".$idtype; - dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $this->barcode_type = $obj->rowid; - $this->barcode_type_code = $obj->code; - $this->barcode_type_label = $obj->label; - $this->barcode_type_coder = $obj->coder; - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - } - return 0; - } - - /** - * Charge le projet d'id $this->fk_project dans this->projet - * - * @return int <0 if KO, >=0 if OK - */ - function fetch_projet() - { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - - if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility - if (empty($this->fk_project)) return 0; - - $project = new Project($this->db); - $result = $project->fetch($this->fk_project); - - $this->projet = $project; // deprecated - $this->project = $project; - return $result; - } - - /** - * Charge le user d'id userid dans this->user - * - * @param int $userid Id du contact - * @return int <0 if KO, >0 if OK - */ - function fetch_user($userid) - { - $user = new User($this->db); - $result=$user->fetch($userid); - $this->user = $user; - return $result; - } - - /** - * Read linked origin object - * - * @return void - */ - function fetch_origin() - { - if ($this->origin == 'shipping') $this->origin = 'expedition'; - if ($this->origin == 'delivery') $this->origin = 'livraison'; - - $origin = $this->origin; - - $classname = ucfirst($origin); - $this->$origin = new $classname($this->db); - $this->$origin->fetch($this->origin_id); - } - - /** - * Load object from specific field - * - * @param string $table Table element or element line - * @param string $field Field selected - * @param string $key Import key - * @return int <0 if KO, >0 if OK - */ - function fetchObjectFrom($table,$field,$key) - { - global $conf; - - $result=false; - - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$field." = '".$key."'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $result = $this->fetch($row[0]); - } - - return $result; - } - - /** - * Getter generic. Load value from a specific field - * - * @param string $table Table of element or element line - * @param int $id Element id - * @param string $field Field selected - * @return int <0 if KO, >0 if OK - */ - function getValueFrom($table, $id, $field) - { - $result=false; - if (!empty($id) && !empty($field) && !empty($table)) { - $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE rowid = ".$id; - - dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - $result = $row[0]; - } + $langs->load("errors"); + $this->error=$langs->trans("ErrorWrongValueForParameterX","1"); + dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); + return -1; + } + if (! $type_contact) + { + $langs->load("errors"); + $this->error=$langs->trans("ErrorWrongValueForParameterX","2"); + dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR); + return -2; } - return $result; - } - /** - * Setter generic. Update a specific field into database. - * Warning: Trigger is run only if param trigkey is provided. - * - * @param string $field Field to update - * @param mixed $value New value - * @param string $table To force other table element or element line (should not be used) - * @param int $id To force other object id (should not be used) - * @param string $format Data format ('text', 'date'). 'text' is used if not defined - * @param string $id_field To force rowid field name. 'rowid' is used if not defined - * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' - * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') - * @return int <0 if KO, >0 if OK - */ - function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='') - { - global $user,$langs,$conf; + $id_type_contact=0; + if (is_numeric($type_contact)) + { + $id_type_contact=$type_contact; + } + else + { + // On recherche id type_contact + $sql = "SELECT tc.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; + $sql.= " AND tc.source='".$this->db->escape($source)."'"; + $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1"; + //print $sql; + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $id_type_contact=$obj->rowid; + } + } - if (empty($table)) $table=$this->table_element; - if (empty($id)) $id=$this->id; + if ($id_type_contact == 0) + { + $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; + dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT"); + return -3; + } + + $datecreate = dol_now(); + + // Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error + $TListeContacts=$this->liste_contact(-1, $source); + $already_added=false; + if(!empty($TListeContacts)) { + foreach($TListeContacts as $array_contact) { + if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) { + $already_added=true; + break; + } + } + } + + if(!$already_added) { + + $this->db->begin(); + + // Insertion dans la base + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; + $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; + $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; + $sql.= "'".$this->db->idate($datecreate)."'"; + $sql.= ", 4, ". $id_type_contact; + $sql.= ")"; + + $resql=$this->db->query($sql); + if ($resql) + { + if (! $notrigger) + { + $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + } + + $this->db->commit(); + return 1; + } + else + { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $this->error=$this->db->errno(); + $this->db->rollback(); + echo 'err rollback'; + return -2; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } + } else return 0; + } + + /** + * Copy contact from one element to current + * + * @param CommonObject $objFrom Source element + * @param string $source Nature of contact ('internal' or 'external') + * @return int >0 if OK, <0 if KO + */ + function copy_linked_contact($objFrom, $source='internal') + { + $contacts = $objFrom->liste_contact(-1, $source); + foreach($contacts as $contact) + { + if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) + { + $this->error=$this->db->lasterror(); + return -1; + } + } + return 1; + } + + /** + * Update a link to contact line + * + * @param int $rowid Id of line contact-element + * @param int $statut New status of link + * @param int $type_contact_id Id of contact type (not modified if 0) + * @param int $fk_socpeople Id of soc_people to update (not modified if 0) + * @return int <0 if KO, >= 0 if OK + */ + function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0) + { + // Insertion dans la base + $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; + $sql.= " statut = ".$statut; + if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; + if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'"; + $sql.= " where rowid = ".$rowid; + $resql=$this->db->query($sql); + if ($resql) + { + return 0; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Delete a link to contact line + * + * @param int $rowid Id of contact link line to delete + * @param int $notrigger Disable all triggers + * @return int >0 if OK, <0 if KO + */ + function delete_contact($rowid, $notrigger=0) + { + global $user; + + + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; + $sql.= " WHERE rowid =".$rowid; + + dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); + if ($this->db->query($sql)) + { + if (! $notrigger) + { + $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); + if ($result < 0) { $this->db->rollback(); return -1; } + } + + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + /** + * Delete all links between an object $this and all its contacts + * + * @param string $source '' or 'internal' or 'external' + * @param string $code Type of contact (code or id) + * @return int >0 if OK, <0 if KO + */ + function delete_linked_contact($source='',$code='') + { + $temp = array(); + $typeContact = $this->liste_type_contact($source,'',0,0,$code); + + foreach($typeContact as $key => $value) + { + array_push($temp,$key); + } + $listId = implode(",", $temp); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; + $sql.= " WHERE element_id = ".$this->id; + if ($listId) + $sql.= " AND fk_c_type_contact IN (".$listId.")"; + + dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); + if ($this->db->query($sql)) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Get array of all contacts for an object + * + * @param int $statut Status of links to get (-1=all) + * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) + * @param int $list 0:Return array contains all properties, 1:Return array contains just id + * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) + * @return array Array of contacts + */ + function liste_contact($statut=-1,$source='external',$list=0,$code='') + { + global $langs; + + $tab=array(); + + $sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user + if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo"; + if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact"; + $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; + $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; + $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; + if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid"; + if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid"; + $sql.= " WHERE ec.element_id =".$this->id; + $sql.= " AND ec.fk_c_type_contact=tc.rowid"; + $sql.= " AND tc.element='".$this->db->escape($this->element)."'"; + if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'"; + if ($source == 'internal') $sql.= " AND tc.source = 'internal'"; + if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'"; + $sql.= " AND tc.active=1"; + if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'"; + $sql.=" ORDER BY t.lastname ASC"; + + dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); + $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 (! $list) + { + $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code; + $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); + $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id, + 'nom'=>$obj->lastname, // For backward compatibility + 'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact, + 'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact); + } + else + { + $tab[$i]=$obj->id; + } + + $i++; + } + + return $tab; + } + else + { + $this->error=$this->db->lasterror(); + dol_print_error($this->db); + return -1; + } + } + + + /** + * Update status of a contact linked to object + * + * @param int $rowid Id of link between object and contact + * @return int <0 if KO, >=0 if OK + */ + function swapContactStatus($rowid) + { + $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,"; + $sql.= " tc.code, tc.libelle"; + //$sql.= ", s.fk_soc"; + $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)"; + //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid"; // Si contact de type external, alors il est lie a une societe + $sql.= " WHERE ec.rowid =".$rowid; + $sql.= " AND ec.fk_c_type_contact=tc.rowid"; + $sql.= " AND tc.element = '".$this->db->escape($this->element)."'"; + + dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $newstatut = ($obj->statut == 4) ? 5 : 4; + $result = $this->update_contact($rowid, $newstatut); + $this->db->free($resql); + return $result; + } + else + { + $this->error=$this->db->error(); + dol_print_error($this->db); + return -1; + } + + } + + /** + * Return array with list of possible values for type of contacts + * + * @param string $source 'internal', 'external' or 'all' + * @param string $order Sort order by : 'position', 'code', 'rowid'... + * @param int $option 0=Return array id->label, 1=Return array code->label + * @param int $activeonly 0=all status of contact, 1=only the active + * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') + * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) + */ + function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='') + { + global $langs; + + if (empty($order)) $order='position'; + if ($order == 'position') $order.=',code'; + + $tab = array(); + $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; + if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types + if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'"; + if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'"; + $sql.= $this->db->order($order,'ASC'); + + //print "sql=".$sql; + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + $transkey="TypeContact_".$this->element."_".$source."_".$obj->code; + $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle); + if (empty($option)) $tab[$obj->rowid]=$libelle_type; + else $tab[$obj->code]=$libelle_type; + $i++; + } + return $tab; + } + else + { + $this->error=$this->db->lasterror(); + //dol_print_error($this->db); + return null; + } + } + + /** + * Return id of contacts for a source and a contact code. + * Example: contact client de facturation ('external', 'BILLING') + * Example: contact client de livraison ('external', 'SHIPPING') + * Example: contact interne suivi paiement ('internal', 'SALESREPFOLL') + * + * @param string $source 'external' or 'internal' + * @param string $code 'BILLING', 'SHIPPING', 'SALESREPFOLL', ... + * @param int $status limited to a certain status + * @return array List of id for such contacts + */ + function getIdContact($source,$code,$status=0) + { + global $conf; + + $result=array(); + $i=0; + //cas particulier pour les expeditions + if($this->element=='shipping' && $this->origin_id != 0) { + $id=$this->origin_id; + $element='commande'; + } else { + $id=$this->id; + $element=$this->element; + } + + $sql = "SELECT ec.fk_socpeople"; + $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,"; + if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,"; + if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; + $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.= " WHERE ec.element_id = ".$id; + $sql.= " AND ec.fk_socpeople = c.rowid"; + if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")"; + if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; + $sql.= " AND ec.fk_c_type_contact = tc.rowid"; + $sql.= " AND tc.element = '".$element."'"; + $sql.= " AND tc.source = '".$source."'"; + $sql.= " AND tc.code = '".$code."'"; + $sql.= " AND tc.active = 1"; + if ($status) $sql.= " AND ec.statut = ".$status; + + dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { + $result[$i]=$obj->fk_socpeople; + $i++; + } + } + else + { + $this->error=$this->db->error(); + return null; + } + + return $result; + } + + /** + * Load object contact with id=$this->contactid into $this->contact + * + * @param int $contactid Id du contact. Use this->contactid if empty. + * @return int <0 if KO, >0 if OK + */ + function fetch_contact($contactid=null) + { + if (empty($contactid)) $contactid=$this->contactid; + + if (empty($contactid)) return 0; + + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + $contact = new Contact($this->db); + $result=$contact->fetch($contactid); + $this->contact = $contact; + return $result; + } + + /** + * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty + * + * @param int $force_thirdparty_id Force thirdparty id + * @return int <0 if KO, >0 if OK + */ + function fetch_thirdparty($force_thirdparty_id=0) + { + global $conf; + + if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) + return 0; + + require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; + + $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty); + if ($force_thirdparty_id) + $idtofetch = $force_thirdparty_id; + + if ($idtofetch) { + $thirdparty = new Societe($this->db); + $result = $thirdparty->fetch($idtofetch); + $this->thirdparty = $thirdparty; + + // Use first price level if level not defined for third party + if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) { + $this->thirdparty->price_level = 1; + } + + return $result; + } else + return -1; + } + + + /** + * Looks for an object with ref matching the wildcard provided + * It does only work when $this->table_ref_field is set + * + * @param string $ref Wildcard + * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO + */ + public function fetchOneLike($ref) + { + if (!$this->table_ref_field) { + return 0; + } + + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1'; + + $query = $this->db->query($sql); + + if (!$this->db->num_rows($query)) { + return 0; + } + + $result = $this->db->fetch_object($query); + + return $this->fetch($result->rowid); + } + + /** + * Load data for barcode into properties ->barcode_type* + * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but + * if it is not defined, ->element must be defined to know default barcode type. + * + * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) + */ + function fetch_barcode() + { + global $conf; + + dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type); + + $idtype=$this->barcode_type; + if (empty($idtype) && $idtype != '0') // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined + { + if ($this->element == 'product') $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE; + else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY; + else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING); + } + + if ($idtype > 0) + { + if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) // If data not already loaded + { + $sql = "SELECT rowid, code, libelle as label, coder"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; + $sql.= " WHERE rowid = ".$idtype; + dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $this->barcode_type = $obj->rowid; + $this->barcode_type_code = $obj->code; + $this->barcode_type_label = $obj->label; + $this->barcode_type_coder = $obj->coder; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + } + return 0; + } + + /** + * Charge le projet d'id $this->fk_project dans this->projet + * + * @return int <0 if KO, >=0 if OK + */ + function fetch_projet() + { + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + + if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility + if (empty($this->fk_project)) return 0; + + $project = new Project($this->db); + $result = $project->fetch($this->fk_project); + + $this->projet = $project; // deprecated + $this->project = $project; + return $result; + } + + /** + * Charge le user d'id userid dans this->user + * + * @param int $userid Id du contact + * @return int <0 if KO, >0 if OK + */ + function fetch_user($userid) + { + $user = new User($this->db); + $result=$user->fetch($userid); + $this->user = $user; + return $result; + } + + /** + * Read linked origin object + * + * @return void + */ + function fetch_origin() + { + if ($this->origin == 'shipping') $this->origin = 'expedition'; + if ($this->origin == 'delivery') $this->origin = 'livraison'; + + $origin = $this->origin; + + $classname = ucfirst($origin); + $this->$origin = new $classname($this->db); + $this->$origin->fetch($this->origin_id); + } + + /** + * Load object from specific field + * + * @param string $table Table element or element line + * @param string $field Field selected + * @param string $key Import key + * @return int <0 if KO, >0 if OK + */ + function fetchObjectFrom($table,$field,$key) + { + global $conf; + + $result=false; + + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table; + $sql.= " WHERE ".$field." = '".$key."'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + $result = $this->fetch($row[0]); + } + + return $result; + } + + /** + * Getter generic. Load value from a specific field + * + * @param string $table Table of element or element line + * @param int $id Element id + * @param string $field Field selected + * @return int <0 if KO, >0 if OK + */ + function getValueFrom($table, $id, $field) + { + $result=false; + if (!empty($id) && !empty($field) && !empty($table)) { + $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; + $sql.= " WHERE rowid = ".$id; + + dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + $result = $row[0]; + } + } + return $result; + } + + /** + * Setter generic. Update a specific field into database. + * Warning: Trigger is run only if param trigkey is provided. + * + * @param string $field Field to update + * @param mixed $value New value + * @param string $table To force other table element or element line (should not be used) + * @param int $id To force other object id (should not be used) + * @param string $format Data format ('text', 'date'). 'text' is used if not defined + * @param string $id_field To force rowid field name. 'rowid' is used if not defined + * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' + * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') + * @return int <0 if KO, >0 if OK + */ + function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='') + { + global $user,$langs,$conf; + + if (empty($table)) $table=$this->table_element; + if (empty($id)) $id=$this->id; if (empty($format)) $format='text'; if (empty($id_field)) $id_field='rowid'; $error=0; - $this->db->begin(); + $this->db->begin(); - // Special case - if ($table == 'product' && $field == 'note_private') $field='note'; + // Special case + if ($table == 'product' && $field == 'note_private') $field='note'; - $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; - if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; - else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); - else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); - if (! empty($fuser) && is_object($fuser)) $sql.=", fk_user_modif = ".$fuser->id; - elseif (empty($fuser) || $fuser != 'none') $sql.=", fk_user_modif = ".$user->id; - $sql.= " WHERE ".$id_field." = ".$id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; + if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; + else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); + else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); + if (! empty($fuser) && is_object($fuser)) $sql.=", fk_user_modif = ".$fuser->id; + elseif (empty($fuser) || $fuser != 'none') $sql.=", fk_user_modif = ".$user->id; + $sql.= " WHERE ".$id_field." = ".$id; - dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($trigkey) - { - $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors - if ($result < 0) $error++; - } + dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($trigkey) + { + $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors + if ($result < 0) $error++; + } - if (! $error) - { - if (property_exists($this, $field)) $this->$field = $value; - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } - - /** - * Load properties id_previous and id_next - * - * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" - * @param string $fieldid Name of field to use for the select MAX and MIN - * @param int $nodbprefix Do not include DB prefix to forge table name - * @return int <0 if KO, >0 if OK - */ - function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) - { - global $user; - - if (! $this->table_element) - { - dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); - return -1; - } - if ($fieldid == 'none') return 1; - - // this->ismultientitymanaged contains - // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - $alias = 's'; - if ($this->element == 'societe') $alias = 'te'; - - $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"; - $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 (! 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 == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; - - //print $filter.' '.$sql."
      "; - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->lasterror(); - return -1; - } - $row = $this->db->fetch_row($result); - $this->ref_previous = $row[0]; - - - $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"; - $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 (! 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 == 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 - - //print $sql."
      "; - $result = $this->db->query($sql); - if (! $result) - { - $this->error=$this->db->lasterror(); - return -2; - } - $row = $this->db->fetch_row($result); - $this->ref_next = $row[0]; - - return 1; - } - - - /** - * Return list of id of contacts of project - * - * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe) - * @return array Array of id of contacts (if source=external or internal) - * Array of id of third parties with at least one contact on project (if source=thirdparty) - */ - function getListContactId($source='external') - { - $contactAlreadySelected = array(); - $tab = $this->liste_contact(-1,$source); - $num=count($tab); - $i = 0; - while ($i < $num) - { - if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; - else $contactAlreadySelected[$i] = $tab[$i]['id']; - $i++; - } - return $contactAlreadySelected; - } - - - /** - * Link element with a project - * - * @param int $projectid Project id to link element to - * @return int <0 if KO, >0 if OK - */ - function setProject($projectid) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - if ($this->table_element == 'actioncomm') - { - if ($projectid) $sql.= ' SET fk_project = '.$projectid; - else $sql.= ' SET fk_project = NULL'; - $sql.= ' WHERE id = '.$this->id; - } - else - { - if ($projectid) $sql.= ' SET fk_projet = '.$projectid; - else $sql.= ' SET fk_projet = NULL'; - $sql.= ' WHERE rowid = '.$this->id; - } - - dol_syslog(get_class($this)."::setProject", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->fk_project = $projectid; - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Change the payments methods - * - * @param int $id Id of new payment method - * @return int >0 if OK, <0 if KO - */ - function setPaymentMethods($id) - { - dol_syslog(get_class($this).'::setPaymentMethods('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - // TODO uniformize field name - $fieldname = 'fk_mode_reglement'; - if ($this->element == 'societe') $fieldname = 'mode_reglement'; - if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier'; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; - - if ($this->db->query($sql)) - { - $this->mode_reglement_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; - return 1; - } - else - { - dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + if (! $error) + { + if (property_exists($this, $field)) $this->$field = $value; + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } /** - * Change the multicurrency code - * - * @param string $code multicurrency code - * @return int >0 if OK, <0 if KO - */ - function setMulticurrencyCode($code) - { - dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'multicurrency_code'; + * Load properties id_previous and id_next + * + * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" + * @param string $fieldid Name of field to use for the select MAX and MIN + * @param int $nodbprefix Do not include DB prefix to forge table name + * @return int <0 if KO, >0 if OK + */ + function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) + { + global $user; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; - $sql .= ' WHERE rowid='.$this->id; + if (! $this->table_element) + { + dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined"); + return -1; + } + if ($fieldid == 'none') return 1; - if ($this->db->query($sql)) - { - $this->multicurrency_code = $code; + // this->ismultientitymanaged contains + // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + $alias = 's'; + if ($this->element == 'societe') $alias = 'te'; + + $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"; + $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 (! 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 == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; + + //print $filter.' '.$sql."
      "; + $result = $this->db->query($sql); + if (! $result) + { + $this->error=$this->db->lasterror(); + return -1; + } + $row = $this->db->fetch_row($result); + $this->ref_previous = $row[0]; + + + $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"; + $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 (! 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 == 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 + + //print $sql."
      "; + $result = $this->db->query($sql); + if (! $result) + { + $this->error=$this->db->lasterror(); + return -2; + } + $row = $this->db->fetch_row($result); + $this->ref_next = $row[0]; + + return 1; + } + + + /** + * Return list of id of contacts of project + * + * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe) + * @return array Array of id of contacts (if source=external or internal) + * Array of id of third parties with at least one contact on project (if source=thirdparty) + */ + function getListContactId($source='external') + { + $contactAlreadySelected = array(); + $tab = $this->liste_contact(-1,$source); + $num=count($tab); + $i = 0; + while ($i < $num) + { + if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid']; + else $contactAlreadySelected[$i] = $tab[$i]['id']; + $i++; + } + return $contactAlreadySelected; + } + + + /** + * Link element with a project + * + * @param int $projectid Project id to link element to + * @return int <0 if KO, >0 if OK + */ + function setProject($projectid) + { + if (! $this->table_element) + { + dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + if ($this->table_element == 'actioncomm') + { + if ($projectid) $sql.= ' SET fk_project = '.$projectid; + else $sql.= ' SET fk_project = NULL'; + $sql.= ' WHERE id = '.$this->id; + } + else + { + if ($projectid) $sql.= ' SET fk_projet = '.$projectid; + else $sql.= ' SET fk_projet = NULL'; + $sql.= ' WHERE rowid = '.$this->id; + } + + dol_syslog(get_class($this)."::setProject", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->fk_project = $projectid; + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Change the payments methods + * + * @param int $id Id of new payment method + * @return int >0 if OK, <0 if KO + */ + function setPaymentMethods($id) + { + dol_syslog(get_class($this).'::setPaymentMethods('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + // TODO uniformize field name + $fieldname = 'fk_mode_reglement'; + if ($this->element == 'societe') $fieldname = 'mode_reglement'; + if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$id; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->mode_reglement_id = $id; + // for supplier + if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id; + return 1; + } + else + { + dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } + + /** + * Change the multicurrency code + * + * @param string $code multicurrency code + * @return int >0 if OK, <0 if KO + */ + function setMulticurrencyCode($code) + { + dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + $fieldname = 'multicurrency_code'; + + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; + $sql .= ' WHERE rowid='.$this->id; + + if ($this->db->query($sql)) + { + $this->multicurrency_code = $code; list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code); if ($rate) $this->setMulticurrencyRate($rate); - return 1; - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + return 1; + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } /** - * Change the multicurrency rate - * - * @param double $rate multicurrency rate + * Change the multicurrency rate + * + * @param double $rate multicurrency rate * @param int $mode mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency - * @return int >0 if OK, <0 if KO - */ - function setMulticurrencyRate($rate, $mode=1) - { - dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - $fieldname = 'multicurrency_tx'; + * @return int >0 if OK, <0 if KO + */ + function setMulticurrencyRate($rate, $mode=1) + { + dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + $fieldname = 'multicurrency_tx'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$rate; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$rate; + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->multicurrency_tx = $rate; + if ($this->db->query($sql)) + { + $this->multicurrency_tx = $rate; // Update line price if (!empty($this->lines)) @@ -1588,249 +1595,249 @@ abstract class CommonObject } } - return 1; - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + return 1; + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } - /** - * Change the payments terms - * - * @param int $id Id of new payment terms - * @return int >0 if OK, <0 if KO - */ - function setPaymentTerms($id) - { - dol_syslog(get_class($this).'::setPaymentTerms('.$id.')'); - if ($this->statut >= 0 || $this->element == 'societe') - { - // TODO uniformize field name - $fieldname = 'fk_cond_reglement'; - if ($this->element == 'societe') $fieldname = 'cond_reglement'; - if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier'; + /** + * Change the payments terms + * + * @param int $id Id of new payment terms + * @return int >0 if OK, <0 if KO + */ + function setPaymentTerms($id) + { + dol_syslog(get_class($this).'::setPaymentTerms('.$id.')'); + if ($this->statut >= 0 || $this->element == 'societe') + { + // TODO uniformize field name + $fieldname = 'fk_cond_reglement'; + if ($this->element == 'societe') $fieldname = 'cond_reglement'; + if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier'; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql .= ' SET '.$fieldname.' = '.$id; + $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { - $this->cond_reglement_id = $id; - // for supplier - if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; - $this->cond_reglement = $id; // for compatibility - return 1; - } - else - { - dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return -1; - } - } - else - { - dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); - $this->error='Status of the object is incompatible '.$this->statut; - return -2; - } - } + if ($this->db->query($sql)) + { + $this->cond_reglement_id = $id; + // for supplier + if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id; + $this->cond_reglement = $id; // for compatibility + return 1; + } + else + { + dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return -1; + } + } + else + { + dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible'); + $this->error='Status of the object is incompatible '.$this->statut; + return -2; + } + } - /** - * Define delivery address - * @deprecated - * - * @param int $id Address id - * @return int <0 si ko, >0 si ok - */ - function setDeliveryAddress($id) - { - $fieldname = 'fk_delivery_address'; - if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; + /** + * Define delivery address + * @deprecated + * + * @param int $id Address id + * @return int <0 si ko, >0 si ok + */ + function setDeliveryAddress($id) + { + $fieldname = 'fk_delivery_address'; + if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address'; - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - if ($this->db->query($sql)) - { - $this->fk_delivery_address = $id; - return 1; - } - else - { - $this->error=$this->db->error(); - dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); - return -1; - } - } + if ($this->db->query($sql)) + { + $this->fk_delivery_address = $id; + return 1; + } + else + { + $this->error=$this->db->error(); + dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error); + return -1; + } + } - /** - * Change the shipping method - * - * @param int $shipping_method_id Id of shipping method - * @return int 1 if OK, 0 if KO - */ - function setShippingMethod($shipping_method_id) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($shipping_method_id<0) $shipping_method_id='NULL'; - dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); + /** + * Change the shipping method + * + * @param int $shipping_method_id Id of shipping method + * @return int 1 if OK, 0 if KO + */ + function setShippingMethod($shipping_method_id) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($shipping_method_id<0) $shipping_method_id='NULL'; + dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_shipping_method = ".$shipping_method_id; - $sql.= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_shipping_method = ".$shipping_method_id; + $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; - return 1; - } else { - dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); - $this->error=$this->db->error(); - return 0; - } - } + if ($this->db->query($sql)) { + $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; + return 1; + } else { + dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); + $this->error=$this->db->error(); + return 0; + } + } - /** - * Change the warehouse - * - * @param int $warehouse_id Id of warehouse - * @return int 1 if OK, 0 if KO - */ - function setWarehouse($warehouse_id) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($warehouse_id<0) $warehouse_id='NULL'; - dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')'); + /** + * Change the warehouse + * + * @param int $warehouse_id Id of warehouse + * @return int 1 if OK, 0 if KO + */ + function setWarehouse($warehouse_id) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($warehouse_id<0) $warehouse_id='NULL'; + dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')'); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_warehouse = ".$warehouse_id; - $sql.= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_warehouse = ".$warehouse_id; + $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id; - return 1; - } else { - dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG); - $this->error=$this->db->error(); - return 0; - } - } + if ($this->db->query($sql)) { + $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id; + return 1; + } else { + dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG); + $this->error=$this->db->error(); + return 0; + } + } - /** - * Set last model used by doc generator - * - * @param User $user User object that make change - * @param string $modelpdf Modele name - * @return int <0 if KO, >0 if OK - */ - function setDocModel($user, $modelpdf) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR); - return -1; - } + /** + * Set last model used by doc generator + * + * @param User $user User object that make change + * @param string $modelpdf Modele name + * @return int <0 if KO, >0 if OK + */ + function setDocModel($user, $modelpdf) + { + if (! $this->table_element) + { + dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR); + return -1; + } - $newmodelpdf=dol_trunc($modelpdf,255); + $newmodelpdf=dol_trunc($modelpdf,255); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; - $sql.= " WHERE rowid = ".$this->id; - // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; - // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'"; + $sql.= " WHERE rowid = ".$this->id; + // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; + // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; - dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->modelpdf=$modelpdf; - return 1; - } - else - { - dol_print_error($this->db); - return 0; - } - } + dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->modelpdf=$modelpdf; + return 1; + } + else + { + dol_print_error($this->db); + return 0; + } + } - /** - * Change the bank account - * - * @param int $fk_account Id of bank account - * @return int 1 if OK, 0 if KO - */ - function setBankAccount($fk_account) - { - if (! $this->table_element) { - dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); - return -1; - } - if ($fk_account<0) $fk_account='NULL'; - dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); + /** + * Change the bank account + * + * @param int $fk_account Id of bank account + * @return int 1 if OK, 0 if KO + */ + function setBankAccount($fk_account) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($fk_account<0) $fk_account='NULL'; + dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_account = ".$fk_account; - $sql.= " WHERE rowid=".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_account = ".$fk_account; + $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->fk_account = ($fk_account=='NULL')?null:$fk_account; - return 1; - } else { - dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return 0; - } - } + if ($this->db->query($sql)) { + $this->fk_account = ($fk_account=='NULL')?null:$fk_account; + return 1; + } else { + dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return 0; + } + } // TODO: Move line related operations to CommonObjectLine? - /** - * Save a new position (field rang) for details lines. - * You can choose to set position for lines with already a position or lines without any position defined. - * - * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines. - * @param string $rowidorder ASC or DESC - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return int <0 if KO, >0 if OK - */ - function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true) - { - if (! $this->table_element_line) - { - dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR); - return -1; - } - if (! $this->fk_element) - { - dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR); - return -1; - } + /** + * Save a new position (field rang) for details lines. + * You can choose to set position for lines with already a position or lines without any position defined. + * + * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines. + * @param string $rowidorder ASC or DESC + * @param boolean $fk_parent_line Table with fk_parent_line field or not + * @return int <0 if KO, >0 if OK + */ + function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true) + { + if (! $this->table_element_line) + { + dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR); + return -1; + } + if (! $this->fk_element) + { + dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR); + return -1; + } - // Count number of lines to reorder (according to choice $renum) - $nl=0; - $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + // Count number of lines to reorder (according to choice $renum) + $nl=0; + $sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line; $sql.= ' WHERE '.$this->fk_element.'='.$this->id; if (! $renum) $sql.= ' AND rang = 0'; if ($renum) $sql.= ' AND rang <> 0'; @@ -1925,44 +1932,44 @@ abstract class CommonObject return $rows; } - /** - * Update a line to have a lower rank - * - * @param int $rowid Id of line - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return void - */ - function line_up($rowid, $fk_parent_line=true) - { - $this->line_order(false, 'ASC', $fk_parent_line); + /** + * Update a line to have a lower rank + * + * @param int $rowid Id of line + * @param boolean $fk_parent_line Table with fk_parent_line field or not + * @return void + */ + function line_up($rowid, $fk_parent_line=true) + { + $this->line_order(false, 'ASC', $fk_parent_line); - // Get rang of line - $rang = $this->getRangOfLine($rowid); + // Get rang of line + $rang = $this->getRangOfLine($rowid); - // Update position of line - $this->updateLineUp($rowid, $rang); - } + // Update position of line + $this->updateLineUp($rowid, $rang); + } - /** - * Update a line to have a higher rank - * - * @param int $rowid Id of line - * @param boolean $fk_parent_line Table with fk_parent_line field or not - * @return void - */ - function line_down($rowid, $fk_parent_line=true) - { - $this->line_order(false, 'ASC', $fk_parent_line); + /** + * Update a line to have a higher rank + * + * @param int $rowid Id of line + * @param boolean $fk_parent_line Table with fk_parent_line field or not + * @return void + */ + function line_down($rowid, $fk_parent_line=true) + { + $this->line_order(false, 'ASC', $fk_parent_line); - // Get rang of line - $rang = $this->getRangOfLine($rowid); + // Get rang of line + $rang = $this->getRangOfLine($rowid); - // Get max value for rang - $max = $this->line_max(); + // Get max value for rang + $max = $this->line_max(); - // Update position of line - $this->updateLineDown($rowid, $rang, $max); - } + // Update position of line + $this->updateLineDown($rowid, $rang, $max); + } /** * Update position of line (rang) @@ -1973,8 +1980,8 @@ abstract class CommonObject */ function updateRangOfLine($rowid,$rang) { - $fieldposition = 'rang'; - if ($this->table_element_line == 'ecm_files') $fieldposition = 'position'; + $fieldposition = 'rang'; + if ($this->table_element_line == 'ecm_files') $fieldposition = 'position'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang; $sql.= ' WHERE rowid = '.$rowid; @@ -1986,400 +1993,426 @@ abstract class CommonObject } } - /** - * Update position of line with ajax (rang) - * - * @param array $rows Array of rows - * @return void - */ - function line_ajaxorder($rows) - { - $num = count($rows); - for ($i = 0 ; $i < $num ; $i++) - { - $this->updateRangOfLine($rows[$i], ($i+1)); - } - } + /** + * Update position of line with ajax (rang) + * + * @param array $rows Array of rows + * @return void + */ + function line_ajaxorder($rows) + { + $num = count($rows); + for ($i = 0 ; $i < $num ; $i++) + { + $this->updateRangOfLine($rows[$i], ($i+1)); + } + } - /** - * Update position of line up (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @return void - */ - function updateLineUp($rowid,$rang) - { - if ($rang > 1 ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang - 1); - if ($this->db->query($sql) ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) - { - dol_print_error($this->db); - } - } - else - { - dol_print_error($this->db); - } - } - } + /** + * Update position of line up (rang) + * + * @param int $rowid Id of line + * @param int $rang Position + * @return void + */ + function updateLineUp($rowid,$rang) + { + if ($rang > 1 ) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang ; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND rang = '.($rang - 1); + if ($this->db->query($sql) ) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang - 1); + $sql.= ' WHERE rowid = '.$rowid; + if (! $this->db->query($sql) ) + { + dol_print_error($this->db); + } + } + else + { + dol_print_error($this->db); + } + } + } - /** - * Update position of line down (rang) - * - * @param int $rowid Id of line - * @param int $rang Position - * @param int $max Max - * @return void - */ - function updateLineDown($rowid,$rang,$max) - { - if ($rang < $max) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.($rang+1); - if ($this->db->query($sql) ) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1); - $sql.= ' WHERE rowid = '.$rowid; - if (! $this->db->query($sql) ) - { - dol_print_error($this->db); - } - } - else - { - dol_print_error($this->db); - } - } - } + /** + * Update position of line down (rang) + * + * @param int $rowid Id of line + * @param int $rang Position + * @param int $max Max + * @return void + */ + function updateLineDown($rowid,$rang,$max) + { + if ($rang < $max) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND rang = '.($rang+1); + if ($this->db->query($sql) ) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.($rang+1); + $sql.= ' WHERE rowid = '.$rowid; + if (! $this->db->query($sql) ) + { + dol_print_error($this->db); + } + } + else + { + dol_print_error($this->db); + } + } + } - /** - * Get position of line (rang) - * - * @param int $rowid Id of line - * @return int Value of rang in table of lines - */ - function getRangOfLine($rowid) - { - $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid ='.$rowid; + /** + * Get position of line (rang) + * + * @param int $rowid Id of line + * @return int Value of rang in table of lines + */ + function getRangOfLine($rowid) + { + $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE rowid ='.$rowid; - dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } + dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } - /** - * Get rowid of the line relative to its position - * - * @param int $rang Rang value - * @return int Rowid of the line - */ - function getIdOfLine($rang) - { - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND rang = '.$rang; - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } + /** + * Get rowid of the line relative to its position + * + * @param int $rang Rang value + * @return int Rowid of the line + */ + function getIdOfLine($rang) + { + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND rang = '.$rang; + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } - /** - * Get max value used for position of line (rang) - * - * @param int $fk_parent_line Parent line id - * @return int Max value of rang in table of lines - */ - function line_max($fk_parent_line=0) - { - // Search the last rang with fk_parent_line - if ($fk_parent_line) - { - $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - $sql.= ' AND fk_parent_line = '.$fk_parent_line; + /** + * Get max value used for position of line (rang) + * + * @param int $fk_parent_line Parent line id + * @return int Max value of rang in table of lines + */ + function line_max($fk_parent_line=0) + { + // Search the last rang with fk_parent_line + if ($fk_parent_line) + { + $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + $sql.= ' AND fk_parent_line = '.$fk_parent_line; - dol_syslog(get_class($this)."::line_max", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - if (! empty($row[0])) - { - return $row[0]; - } - else - { - return $this->getRangOfLine($fk_parent_line); - } - } - } - // If not, search the last rang of element - else - { - $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + dol_syslog(get_class($this)."::line_max", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + if (! empty($row[0])) + { + return $row[0]; + } + else + { + return $this->getRangOfLine($fk_parent_line); + } + } + } + // If not, search the last rang of element + else + { + $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - dol_syslog(get_class($this)."::line_max", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } - } + dol_syslog(get_class($this)."::line_max", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } + } - /** - * Update external ref of element - * - * @param string $ref_ext Update field ref_ext - * @return int <0 if KO, >0 if OK - */ - function update_ref_ext($ref_ext) - { - if (! $this->table_element) - { - dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + /** + * Update external ref of element + * + * @param string $ref_ext Update field ref_ext + * @return int <0 if KO, >0 if OK + */ + function update_ref_ext($ref_ext) + { + if (! $this->table_element) + { + dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR); + return -1; + } - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; - $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; + $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; - dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); - if ($this->db->query($sql)) - { - $this->ref_ext = $ref_ext; - return 1; - } - else - { - $this->error=$this->db->error(); - return -1; - } - } + dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); + if ($this->db->query($sql)) + { + $this->ref_ext = $ref_ext; + return 1; + } + else + { + $this->error=$this->db->error(); + return -1; + } + } - /** - * Update note of element - * - * @param string $note New value for note - * @param string $suffix '', '_public' or '_private' - * @return int <0 if KO, >0 if OK - */ - function update_note($note,$suffix='') - { - global $user; + /** + * Update note of element + * + * @param string $note New value for note + * @param string $suffix '', '_public' or '_private' + * @return int <0 if KO, >0 if OK + */ + function update_note($note,$suffix='') + { + global $user; - if (! $this->table_element) - { - dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR); - return -1; - } + if (! $this->table_element) + { + dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR); + return -1; + } if (! in_array($suffix,array('','_public','_private'))) { - dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); + dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR); return -2; } - // Special cas - //var_dump($this->table_element);exit; + // Special cas + //var_dump($this->table_element);exit; if ($this->table_element == 'product') $suffix=''; - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); - $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id; - $sql.= " WHERE rowid =". $this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); + $sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id; + $sql.= " WHERE rowid =". $this->id; - dol_syslog(get_class($this)."::update_note", LOG_DEBUG); - if ($this->db->query($sql)) - { - if ($suffix == '_public') $this->note_public = $note; - else if ($suffix == '_private') $this->note_private = $note; - else - { - $this->note = $note; // deprecated - $this->note_private = $note; - } - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::update_note", LOG_DEBUG); + if ($this->db->query($sql)) + { + if ($suffix == '_public') $this->note_public = $note; + else if ($suffix == '_private') $this->note_private = $note; + else + { + $this->note = $note; // deprecated + $this->note_private = $note; + } + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } - /** - * Update public note (kept for backward compatibility) - * - * @param string $note New value for note - * @return int <0 if KO, >0 if OK - * @deprecated - * @see update_note() - */ - function update_note_public($note) - { - return $this->update_note($note,'_public'); - } + /** + * Update public note (kept for backward compatibility) + * + * @param string $note New value for note + * @return int <0 if KO, >0 if OK + * @deprecated + * @see update_note() + */ + function update_note_public($note) + { + return $this->update_note($note,'_public'); + } - /** - * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). - * Must be called at end of methods addline or updateline. - * - * @param int $exclspec >0 = Exclude special product (product_type=9) - * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total - * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object. - * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object. - * @return int <0 if KO, >0 if OK - */ - function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null) - { - global $conf; + /** + * Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines). + * Must be called at end of methods addline or updateline. + * + * @param int $exclspec >0 = Exclude special product (product_type=9) + * @param string $roundingadjust 'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total + * @param int $nodatabaseupdate 1=Do not update database. Update only properties of object. + * @param Societe $seller If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object. + * @return int <0 if KO, >0 if OK + */ + function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null) + { + global $conf; - include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; + // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield) + $MODULE = ""; + if ($this->element == 'propal') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL"; + elseif ($this->element == 'order') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER"; + elseif ($this->element == 'facture') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE"; + elseif ($this->element == 'facture_fourn') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE"; + elseif ($this->element == 'order_supplier') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER"; + elseif ($this->element == 'supplier_proposal') + $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL"; - if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility + if (! empty($MODULE)) { + if (! empty($conf->global->$MODULE)) { + $modsactivated = explode(',', $conf->global->$MODULE); + foreach ($modsactivated as $mod) { + if ($conf->$mod->enabled) + return 1; // update was disabled by specific setup + } + } + } - $forcedroundingmode=$roundingadjust; - if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; - elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - $error=0; + if ($roundingadjust == '-1') $roundingadjust='auto'; // For backward compatibility - $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1; + $forcedroundingmode=$roundingadjust; + if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND; + elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0'; - // Define constants to find lines to sum - $fieldtva='total_tva'; - $fieldlocaltax1='total_localtax1'; - $fieldlocaltax2='total_localtax2'; - $fieldup='subprice'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') - { - $fieldtva='tva'; - $fieldup='pu_ht'; - } - if ($this->element == 'expensereport') - { - $fieldup='value_unit'; - } + $error=0; - $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; - $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; - if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent'; - $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; - $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - if ($exclspec) - { - $product_field='product_type'; - if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field - if ($product_field) $sql.= ' AND '.$product_field.' <> 9'; - } - $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used + $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1; - dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->total_ht = 0; - $this->total_tva = 0; - $this->total_localtax1 = 0; - $this->total_localtax2 = 0; - $this->total_ttc = 0; - $total_ht_by_vats = array(); - $total_tva_by_vats = array(); - $total_ttc_by_vats = array(); + // Define constants to find lines to sum + $fieldtva='total_tva'; + $fieldlocaltax1='total_localtax1'; + $fieldlocaltax2='total_localtax2'; + $fieldup='subprice'; + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') + { + $fieldtva='tva'; + $fieldup='pu_ht'; + } + if ($this->element == 'expensereport') + { + $fieldup='value_unit'; + } + + $sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,'; + $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type'; + if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent'; + $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; + if ($exclspec) + { + $product_field='product_type'; + if ($this->table_element_line == 'contratdet') $product_field=''; // contratdet table has no product_type field + if ($product_field) $sql.= ' AND '.$product_field.' <> 9'; + } + $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used + + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->total_ht = 0; + $this->total_tva = 0; + $this->total_localtax1 = 0; + $this->total_localtax2 = 0; + $this->total_ttc = 0; + $total_ht_by_vats = array(); + $total_tva_by_vats = array(); + $total_ttc_by_vats = array(); $this->multicurrency_total_ht = 0; - $this->multicurrency_total_tva = 0; - $this->multicurrency_total_ttc = 0; + $this->multicurrency_total_tva = 0; + $this->multicurrency_total_ttc = 0; - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none' - if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' - { - $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx); - $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); - $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); - if ($diff) - { - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; - dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); - $obj->total_tva = $tmpcal[1]; - $obj->total_ttc = $tmpcal[2]; - // - } - } + // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none' + if ($forcedroundingmode == '0') // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto' + { + $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx); + $tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx); + $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); + if ($diff) + { + $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid; + dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); + $resqlfix=$this->db->query($sqlfix); + if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); + $obj->total_tva = $tmpcal[1]; + $obj->total_ttc = $tmpcal[2]; + // + } + } - $this->total_ht += $obj->total_ht; // The field visible at end of line detail - $this->total_tva += $obj->total_tva; - $this->total_localtax1 += $obj->total_localtax1; - $this->total_localtax2 += $obj->total_localtax2; - $this->total_ttc += $obj->total_ttc; - $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail - $this->multicurrency_total_tva += $obj->multicurrency_total_tva; - $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc; + $this->total_ht += $obj->total_ht; // The field visible at end of line detail + $this->total_tva += $obj->total_tva; + $this->total_localtax1 += $obj->total_localtax1; + $this->total_localtax2 += $obj->total_localtax2; + $this->total_ttc += $obj->total_ttc; + $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail + $this->multicurrency_total_tva += $obj->multicurrency_total_tva; + $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc; - if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0; - if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0; - if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0; - $total_ht_by_vats[$obj->vatrate] += $obj->total_ht; - $total_tva_by_vats[$obj->vatrate] += $obj->total_tva; - $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc; + if (! isset($total_ht_by_vats[$obj->vatrate])) $total_ht_by_vats[$obj->vatrate]=0; + if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0; + if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0; + $total_ht_by_vats[$obj->vatrate] += $obj->total_ht; + $total_tva_by_vats[$obj->vatrate] += $obj->total_tva; + $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc; - if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency - { - $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); - $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1); - //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."
      \n"; - if ($diff) - { - if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; } - $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; - dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); - $resqlfix=$this->db->query($sqlfix); - if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); - $this->total_tva -= $diff; - $this->total_ttc -= $diff; - $total_tva_by_vats[$obj->vatrate] -= $diff; - $total_ttc_by_vats[$obj->vatrate] -= $diff; + if ($forcedroundingmode == '1') // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency + { + $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1); + $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1); + //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."
      \n"; + if ($diff) + { + if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; } + $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid; + dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix); + $resqlfix=$this->db->query($sqlfix); + if (! $resqlfix) dol_print_error($this->db,'Failed to update line'); + $this->total_tva -= $diff; + $this->total_ttc -= $diff; + $total_tva_by_vats[$obj->vatrate] -= $diff; + $total_ttc_by_vats[$obj->vatrate] -= $diff; - } - } + } + } - $i++; - } + $i++; + } - // Add revenue stamp to total - $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0; - $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; + // Add revenue stamp to total + $this->total_ttc += isset($this->revenuestamp)?$this->revenuestamp:0; + $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; // Situations totals - if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) { + if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) + { $prev_sits = $this->get_prev_sits(); foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch. @@ -2394,93 +2427,93 @@ abstract class CommonObject } } - $this->db->free($resql); + $this->db->free($resql); - // Now update global field total_ht, total_ttc and tva - $fieldht='total_ht'; - $fieldtva='tva'; - $fieldlocaltax1='localtax1'; - $fieldlocaltax2='localtax2'; - $fieldttc='total_ttc'; - // Specific code for backward compatibility with old field names - if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total'; - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva'; - if ($this->element == 'propal') $fieldttc='total'; - if ($this->element == 'expensereport') $fieldtva='total_tva'; - if ($this->element == 'supplier_proposal') $fieldttc='total'; + // Now update global field total_ht, total_ttc and tva + $fieldht='total_ht'; + $fieldtva='tva'; + $fieldlocaltax1='localtax1'; + $fieldlocaltax2='localtax2'; + $fieldttc='total_ttc'; + // Specific code for backward compatibility with old field names + if ($this->element == 'facture' || $this->element == 'facturerec') $fieldht='total'; + if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva'; + if ($this->element == 'propal') $fieldttc='total'; + if ($this->element == 'expensereport') $fieldtva='total_tva'; + if ($this->element == 'supplier_proposal') $fieldttc='total'; - if (empty($nodatabaseupdate)) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; - $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; - $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; - $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',"; - $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',"; - $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'"; - $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'"; - $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'"; - $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; - $sql .= ' WHERE rowid = '.$this->id; + if (empty($nodatabaseupdate)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; + $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; + $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; + $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',"; + $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',"; + $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'"; + $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'"; + $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'"; + $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; + $sql .= ' WHERE rowid = '.$this->id; - //print "xx".$sql; - dol_syslog(get_class($this)."::update_price", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); - } - } + //print "xx".$sql; + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + $error++; + $this->error=$this->db->lasterror(); + $this->errors[]=$this->db->lasterror(); + } + } - if (! $error) - { - return 1; - } - else - { - return -1; - } - } - else - { - dol_print_error($this->db,'Bad request in update_price'); - return -1; - } - } + if (! $error) + { + return 1; + } + else + { + return -1; + } + } + else + { + dol_print_error($this->db,'Bad request in update_price'); + return -1; + } + } - /** - * Add objects linked in llx_element_element. - * - * @param string $origin Linked element type - * @param int $origin_id Linked element id - * @return int <=0 if KO, >0 if OK - * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked - */ - function add_object_linked($origin=null, $origin_id=null) - { - $origin = (! empty($origin) ? $origin : $this->origin); - $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id); + /** + * Add objects linked in llx_element_element. + * + * @param string $origin Linked element type + * @param int $origin_id Linked element id + * @return int <=0 if KO, >0 if OK + * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked + */ + function add_object_linked($origin=null, $origin_id=null) + { + $origin = (! empty($origin) ? $origin : $this->origin); + $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id); - // Special case - if ($origin == 'order') $origin='commande'; - if ($origin == 'invoice') $origin='facture'; + // Special case + if ($origin == 'order') $origin='commande'; + if ($origin == 'invoice') $origin='facture'; - $this->db->begin(); + $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $origin_id; - $sql.= ", '".$this->db->escape($origin)."'"; - $sql.= ", ".$this->id; - $sql.= ", '".$this->db->escape($this->element)."'"; - $sql.= ")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $origin_id; + $sql.= ", '".$this->db->escape($origin)."'"; + $sql.= ", ".$this->id; + $sql.= ", '".$this->db->escape($this->element)."'"; + $sql.= ")"; - dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); + dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); if ($this->db->query($sql)) { $this->db->commit(); @@ -2494,263 +2527,263 @@ abstract class CommonObject } } - /** - * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds - * Possible usage for parameters: - * - all parameters empty -> we look all link to current object (current object can be source or target) - * - source id+type -> will get target list linked to source - * - target id+type -> will get source list linked to target - * - source id+type + target type -> will get target list of the type - * - target id+type + target source -> will get source list of the type - * - * @param int $sourceid Object source id (if not defined, id of object) - * @param string $sourcetype Object source type (if not defined, element name of object) - * @param int $targetid Object target id (if not defined, id of object) - * @param string $targettype Object target type (if not defined, elemennt name of object) - * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided - * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. - * @return void - * @see add_object_linked, updateObjectLinked, deleteObjectLinked - */ + /** + * Fetch array of objects linked to current object. Links are loaded into this->linkedObjects array and this->linkedObjectsIds + * Possible usage for parameters: + * - all parameters empty -> we look all link to current object (current object can be source or target) + * - source id+type -> will get target list linked to source + * - target id+type -> will get source list linked to target + * - source id+type + target type -> will get target list of the type + * - target id+type + target source -> will get source list of the type + * + * @param int $sourceid Object source id (if not defined, id of object) + * @param string $sourcetype Object source type (if not defined, element name of object) + * @param int $targetid Object target id (if not defined, id of object) + * @param string $targettype Object target type (if not defined, elemennt name of object) + * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided + * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. + * @return void + * @see add_object_linked, updateObjectLinked, deleteObjectLinked + */ function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1) - { - global $conf; + { + global $conf; - $this->linkedObjectsIds=array(); - $this->linkedObjects=array(); + $this->linkedObjectsIds=array(); + $this->linkedObjects=array(); - $justsource=false; - $justtarget=false; - $withtargettype=false; - $withsourcetype=false; + $justsource=false; + $justtarget=false; + $withtargettype=false; + $withsourcetype=false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid)) - { - $justsource=true; // the source (id and type) is a search criteria - if (! empty($targettype)) $withtargettype=true; - } - if (! empty($targetid) && ! empty($targettype) && empty($sourceid)) - { - $justtarget=true; // the target (id and type) is a search criteria - if (! empty($sourcetype)) $withsourcetype=true; - } + if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid)) + { + $justsource=true; // the source (id and type) is a search criteria + if (! empty($targettype)) $withtargettype=true; + } + if (! empty($targetid) && ! empty($targettype) && empty($sourceid)) + { + $justtarget=true; // the target (id and type) is a search criteria + if (! empty($sourcetype)) $withsourcetype=true; + } - $sourceid = (! empty($sourceid) ? $sourceid : $this->id); - $targetid = (! empty($targetid) ? $targetid : $this->id); - $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); - $targettype = (! empty($targettype) ? $targettype : $this->element); + $sourceid = (! empty($sourceid) ? $sourceid : $this->id); + $targetid = (! empty($targetid) ? $targetid : $this->id); + $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); + $targettype = (! empty($targettype) ? $targettype : $this->element); - /*if (empty($sourceid) && empty($targetid)) + /*if (empty($sourceid) && empty($targetid)) { dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR); return -1; }*/ - // Links between objects are stored in table element_element - $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; - $sql.= " WHERE "; - if ($justsource || $justtarget) - { - if ($justsource) - { - $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; - if ($withtargettype) $sql.= " AND targettype = '".$targettype."'"; - } - else if ($justtarget) - { - $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; - if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'"; - } - } - else + // Links between objects are stored in table element_element + $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; + $sql.= " WHERE "; + if ($justsource || $justtarget) { - $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; - $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; - } - $sql .= ' ORDER BY sourcetype'; - //print $sql; + if ($justsource) + { + $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'"; + if ($withtargettype) $sql.= " AND targettype = '".$targettype."'"; + } + else if ($justtarget) + { + $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'"; + if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'"; + } + } + else + { + $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; + $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; + } + $sql .= ' ORDER BY sourcetype'; + //print $sql; - dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); - $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 ($justsource || $justtarget) - { - if ($justsource) - { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; - } - else if ($justtarget) - { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; - } - } - else - { - if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) - { - $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; - } - if ($obj->fk_target == $targetid && $obj->targettype == $targettype) - { - $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; - } - } - $i++; - } + dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); + $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 ($justsource || $justtarget) + { + if ($justsource) + { + $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; + } + else if ($justtarget) + { + $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; + } + } + else + { + if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) + { + $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target; + } + if ($obj->fk_target == $targetid && $obj->targettype == $targettype) + { + $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source; + } + } + $i++; + } - if (! empty($this->linkedObjectsIds)) - { - foreach($this->linkedObjectsIds as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) - { - // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) - $module = $element = $subelement = $objecttype; - if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' - && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs)) - { - $module = $element = $regs[1]; - $subelement = $regs[2]; - } + if (! empty($this->linkedObjectsIds)) + { + foreach($this->linkedObjectsIds as $objecttype => $objectids) // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...) + { + // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...) + $module = $element = $subelement = $objecttype; + if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' + && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs)) + { + $module = $element = $regs[1]; + $subelement = $regs[2]; + } - $classpath = $element.'/class'; - // To work with non standard classpath or module name - if ($objecttype == 'facture') { - $classpath = 'compta/facture/class'; - } - else if ($objecttype == 'facturerec') { - $classpath = 'compta/facture/class'; $module = 'facture'; - } - else if ($objecttype == 'propal') { - $classpath = 'comm/propal/class'; - } - else if ($objecttype == 'supplier_proposal') { - $classpath = 'supplier_proposal/class'; - } - else if ($objecttype == 'shipping') { - $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; - } - else if ($objecttype == 'delivery') { - $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; - } - else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { - $classpath = 'fourn/class'; $module = 'fournisseur'; - } - else if ($objecttype == 'fichinter') { - $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; - } - else if ($objecttype == 'subscription') { - $classpath = 'adherents/class'; $module = 'adherent'; - } + $classpath = $element.'/class'; + // To work with non standard classpath or module name + if ($objecttype == 'facture') { + $classpath = 'compta/facture/class'; + } + else if ($objecttype == 'facturerec') { + $classpath = 'compta/facture/class'; $module = 'facture'; + } + else if ($objecttype == 'propal') { + $classpath = 'comm/propal/class'; + } + else if ($objecttype == 'supplier_proposal') { + $classpath = 'supplier_proposal/class'; + } + else if ($objecttype == 'shipping') { + $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; + } + else if ($objecttype == 'delivery') { + $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon'; + } + else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { + $classpath = 'fourn/class'; $module = 'fournisseur'; + } + else if ($objecttype == 'fichinter') { + $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; + } + else if ($objecttype == 'subscription') { + $classpath = 'adherents/class'; $module = 'adherent'; + } - // Set classfile - $classfile = strtolower($subelement); $classname = ucfirst($subelement); + // Set classfile + $classfile = strtolower($subelement); $classname = ucfirst($subelement); - if ($objecttype == 'order') { - $classfile = 'commande'; $classname = 'Commande'; - } - else if ($objecttype == 'invoice_supplier') { - $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; - } - else if ($objecttype == 'order_supplier') { - $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; - } - else if ($objecttype == 'supplier_proposal') { - $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; - } - else if ($objecttype == 'facturerec') { - $classfile = 'facture-rec'; $classname = 'FactureRec'; - } - else if ($objecttype == 'subscription') { - $classfile = 'subscription'; $classname = 'Subscription'; - } + if ($objecttype == 'order') { + $classfile = 'commande'; $classname = 'Commande'; + } + else if ($objecttype == 'invoice_supplier') { + $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; + } + else if ($objecttype == 'order_supplier') { + $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; + } + else if ($objecttype == 'supplier_proposal') { + $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; + } + else if ($objecttype == 'facturerec') { + $classfile = 'facture-rec'; $classname = 'FactureRec'; + } + else if ($objecttype == 'subscription') { + $classfile = 'subscription'; $classname = 'Subscription'; + } - // Here $module, $classfile and $classname are set - if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) - { - dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); - //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname); - if (class_exists($classname)) - { - foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element - { - $object = new $classname($this->db); - $ret = $object->fetch($objectid); - if ($ret >= 0) - { - $this->linkedObjects[$objecttype][$i] = $object; - } - } - } - } - } - } - } - else - { - dol_print_error($this->db); - } - } + // Here $module, $classfile and $classname are set + if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) + { + dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); + //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname); + if (class_exists($classname)) + { + foreach($objectids as $i => $objectid) // $i is rowid into llx_element_element + { + $object = new $classname($this->db); + $ret = $object->fetch($objectid); + if ($ret >= 0) + { + $this->linkedObjects[$objecttype][$i] = $object; + } + } + } + } + } + } + } + else + { + dol_print_error($this->db); + } + } - /** - * Update object linked of a current object - * - * @param int $sourceid Object source id - * @param string $sourcetype Object source type - * @param int $targetid Object target id - * @param string $targettype Object target type - * @return int >0 if OK, <0 if KO - * @see add_object_linked, fetObjectLinked, deleteObjectLinked - */ - function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='') - { - $updatesource=false; - $updatetarget=false; + /** + * Update object linked of a current object + * + * @param int $sourceid Object source id + * @param string $sourcetype Object source type + * @param int $targetid Object target id + * @param string $targettype Object target type + * @return int >0 if OK, <0 if KO + * @see add_object_linked, fetObjectLinked, deleteObjectLinked + */ + function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='') + { + $updatesource=false; + $updatetarget=false; - if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true; - else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true; + if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true; + else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true; - $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; - if ($updatesource) - { - $sql.= "fk_source = ".$sourceid; - $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql.= " WHERE fk_target = ".$this->id; - $sql.= " AND targettype = '".$this->db->escape($this->element)."'"; - } - else if ($updatetarget) - { - $sql.= "fk_target = ".$targetid; - $sql.= ", targettype = '".$this->db->escape($targettype)."'"; - $sql.= " WHERE fk_source = ".$this->id; - $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'"; - } + $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; + if ($updatesource) + { + $sql.= "fk_source = ".$sourceid; + $sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'"; + $sql.= " WHERE fk_target = ".$this->id; + $sql.= " AND targettype = '".$this->db->escape($this->element)."'"; + } + else if ($updatetarget) + { + $sql.= "fk_target = ".$targetid; + $sql.= ", targettype = '".$this->db->escape($targettype)."'"; + $sql.= " WHERE fk_source = ".$this->id; + $sql.= " AND sourcetype = '".$this->db->escape($this->element)."'"; + } - dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); + if ($this->db->query($sql)) + { + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } /** * Delete all links between an object $this * * @param int $sourceid Object source id - * @param string $sourcetype Object source type - * @param int $targetid Object target id - * @param string $targettype Object target type - * @param int $rowid Row id of line to delete. If defined, other parameters are not used. + * @param string $sourcetype Object source type + * @param int $targetid Object target id + * @param string $targettype Object target type + * @param int $rowid Row id of line to delete. If defined, other parameters are not used. * @return int >0 if OK, <0 if KO * @see add_object_linked, updateObjectLinked, fetchObjectLinked */ @@ -2806,73 +2839,73 @@ abstract class CommonObject } } - /** - * Set status of an object - * - * @param int $status Status to set - * @param int $elementId Id of element to force (use this->id by default) - * @param string $elementType Type of element to force (use this->table_element by default) - * @return int <0 if KO, >0 if OK - */ - function setStatut($status,$elementId=null,$elementType='') - { - global $user,$langs,$conf; + /** + * Set status of an object + * + * @param int $status Status to set + * @param int $elementId Id of element to force (use this->id by default) + * @param string $elementType Type of element to force (use this->table_element by default) + * @return int <0 if KO, >0 if OK + */ + function setStatut($status,$elementId=null,$elementType='') + { + global $user,$langs,$conf; - $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not. + $savElementId=$elementId; // To be used later to know if we were using the method using the id of this or not. - $elementId = (!empty($elementId)?$elementId:$this->id); - $elementTable = (!empty($elementType)?$elementType:$this->table_element); + $elementId = (!empty($elementId)?$elementId:$this->id); + $elementTable = (!empty($elementType)?$elementType:$this->table_element); - $this->db->begin(); + $this->db->begin(); - $fieldstatus="fk_statut"; - if ($elementTable == 'mailing') $fieldstatus="statut"; - if ($elementTable == 'user') $fieldstatus="statut"; - if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; + $fieldstatus="fk_statut"; + if ($elementTable == 'mailing') $fieldstatus="statut"; + if ($elementTable == 'user') $fieldstatus="statut"; + if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status"; - $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; - $sql.= " SET ".$fieldstatus." = ".$status; - // If status = 1 = validated, update also fk_user_valid - if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id; - $sql.= " WHERE rowid=".$elementId; + $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable; + $sql.= " SET ".$fieldstatus." = ".$status; + // If status = 1 = validated, update also fk_user_valid + if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id; + $sql.= " WHERE rowid=".$elementId; - dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); - if ($this->db->query($sql)) - { - $error = 0; + dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); + if ($this->db->query($sql)) + { + $error = 0; - $trigkey=''; - if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class - if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; - if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; - if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; + $trigkey=''; + if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class + if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; + if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; + if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; - if ($trigkey) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } + if ($trigkey) + { + // Appel des triggers + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf); + if ($result < 0) { + $error++; $this->errors=$interface->errors; + } + // Fin appel triggers + } if (! $error) { $this->db->commit(); - if (empty($savElementId)) // If the element we update was $this (so $elementId is null) - { - $this->statut = $status; - $this->status = $status; - } + if (empty($savElementId)) // If the element we update was $this (so $elementId is null) + { + $this->statut = $status; + $this->status = $status; + } - return 1; + return 1; } else { @@ -2880,260 +2913,260 @@ abstract class CommonObject dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR); return -1; } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } - /** - * Load type of canvas of an object if it exists - * - * @param int $id Record id - * @param string $ref Record ref - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - function getCanvas($id=0,$ref='') - { - global $conf; + /** + * Load type of canvas of an object if it exists + * + * @param int $id Record id + * @param string $ref Record ref + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + function getCanvas($id=0,$ref='') + { + global $conf; - if (empty($id) && empty($ref)) return 0; - if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. + if (empty($id) && empty($ref)) return 0; + if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default. - // Clean parameters - $ref = trim($ref); + // Clean parameters + $ref = trim($ref); - $sql = "SELECT rowid, canvas"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; - if (! empty($id)) $sql.= " AND rowid = ".$id; - if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'"; + $sql = "SELECT rowid, canvas"; + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " WHERE entity IN (".getEntity($this->element, 1).")"; + if (! empty($id)) $sql.= " AND rowid = ".$id; + if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'"; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $this->canvas = $obj->canvas; - return 1; - } - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $this->canvas = $obj->canvas; + return 1; + } + else return 0; + } + else + { + dol_print_error($this->db); + return -1; + } + } - /** - * Get special code of a line - * - * @param int $lineid Id of line - * @return int Special code - */ - function getSpecialCode($lineid) - { - $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; - $sql.= ' WHERE rowid = '.$lineid; - $resql = $this->db->query($sql); - if ($resql) - { - $row = $this->db->fetch_row($resql); - return $row[0]; - } - } + /** + * Get special code of a line + * + * @param int $lineid Id of line + * @return int Special code + */ + function getSpecialCode($lineid) + { + $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line; + $sql.= ' WHERE rowid = '.$lineid; + $resql = $this->db->query($sql); + if ($resql) + { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + } - /** - * Function to check if an object is used by others. - * Check is done into this->childtables. There is no check into llx_element_element. - * - * @param int $id Force id of object - * @return int <0 if KO, 0 if not used, >0 if already used - */ - function isObjectUsed($id=0) - { - global $langs; + /** + * Function to check if an object is used by others. + * Check is done into this->childtables. There is no check into llx_element_element. + * + * @param int $id Force id of object + * @return int <0 if KO, 0 if not used, >0 if already used + */ + function isObjectUsed($id=0) + { + global $langs; - if (empty($id)) $id=$this->id; + if (empty($id)) $id=$this->id; - // Check parameters - if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0) - { - dol_print_error('Called isObjectUsed on a class with property this->childtables not defined'); - return -1; - } + // Check parameters + if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0) + { + dol_print_error('Called isObjectUsed on a class with property this->childtables not defined'); + return -1; + } - $arraytoscan = $this->childtables; - // For backward compatibility, we check if array is old format array('table1', 'table2', ...) - $tmparray=array_keys($this->childtables); - if (is_numeric($tmparray[0])) - { - $arraytoscan = array_flip($this->childtables); - } + $arraytoscan = $this->childtables; + // For backward compatibility, we check if array is old format array('table1', 'table2', ...) + $tmparray=array_keys($this->childtables); + if (is_numeric($tmparray[0])) + { + $arraytoscan = array_flip($this->childtables); + } - // Test if child exists - $haschild=0; - foreach($arraytoscan as $table => $elementname) - { - //print $id.'-'.$table.'-'.$elementname.'
      '; - // Check if third party can be deleted - $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; - $sql.= " WHERE ".$this->fk_element." = ".$id; - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - if ($obj->nb > 0) - { - $langs->load("errors"); - //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild; - $haschild += $obj->nb; - $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); - break; // We found at least one, we stop here - } - } - else - { - $this->errors[]=$this->db->lasterror(); - return -1; - } - } - if ($haschild > 0) - { - $this->errors[]="ErrorRecordHasChildren"; - return $haschild; - } - else return 0; - } + // Test if child exists + $haschild=0; + foreach($arraytoscan as $table => $elementname) + { + //print $id.'-'.$table.'-'.$elementname.'
      '; + // Check if third party can be deleted + $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table; + $sql.= " WHERE ".$this->fk_element." = ".$id; + $resql=$this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $langs->load("errors"); + //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild; + $haschild += $obj->nb; + $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); + break; // We found at least one, we stop here + } + } + else + { + $this->errors[]=$this->db->lasterror(); + return -1; + } + } + if ($haschild > 0) + { + $this->errors[]="ErrorRecordHasChildren"; + return $haschild; + } + else return 0; + } - /** - * Function to say how many lines object contains - * - * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service - * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found - */ - function hasProductsOrServices($predefined=-1) - { - $nb=0; + /** + * Function to say how many lines object contains + * + * @param int $predefined -1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service + * @return int <0 if KO, 0 if no predefined products, nb of lines with predefined products if found + */ + function hasProductsOrServices($predefined=-1) + { + $nb=0; - foreach($this->lines as $key => $val) - { - $qualified=0; - if ($predefined == -1) $qualified=1; - if ($predefined == 1 && $val->fk_product > 0) $qualified=1; - if ($predefined == 0 && $val->fk_product <= 0) $qualified=1; - if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1; - if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1; - if ($qualified) $nb++; - } - dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies'); - return $nb; - } + foreach($this->lines as $key => $val) + { + $qualified=0; + if ($predefined == -1) $qualified=1; + if ($predefined == 1 && $val->fk_product > 0) $qualified=1; + if ($predefined == 0 && $val->fk_product <= 0) $qualified=1; + if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1; + if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1; + if ($qualified) $nb++; + } + dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies'); + return $nb; + } - /** - * Function that returns the total amount HT of discounts applied for all lines. - * - * @return float - */ - function getTotalDiscount() - { - $total_discount=0.00; + /** + * Function that returns the total amount HT of discounts applied for all lines. + * + * @return float + */ + function getTotalDiscount() + { + $total_discount=0.00; - $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; - $sql.= " WHERE ".$this->fk_element." = ".$this->id; + $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht"; + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; + $sql.= " WHERE ".$this->fk_element." = ".$this->id; - dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $pu_ht = $obj->pu_ht; - $qty= $obj->qty; - $total_ht = $obj->total_ht; + $pu_ht = $obj->pu_ht; + $qty= $obj->qty; + $total_ht = $obj->total_ht; - $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); - $total_discount += $total_discount_line; + $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); + $total_discount += $total_discount_line; - $i++; - } - } + $i++; + } + } - //print $total_discount; exit; - return price2num($total_discount); - } + //print $total_discount; exit; + return price2num($total_discount); + } - /** - * Return into unit=0, the calculated total of weight and volume of all lines * qty - * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line. - * - * @return array array('weight'=>...,'volume'=>...) - */ - function getTotalWeightVolume() - { - $totalWeight = 0; - $totalVolume = 0; - // defined for shipment only - $totalOrdered = ''; - // defined for shipment only - $totalToShip = ''; + /** + * Return into unit=0, the calculated total of weight and volume of all lines * qty + * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line. + * + * @return array array('weight'=>...,'volume'=>...) + */ + function getTotalWeightVolume() + { + $totalWeight = 0; + $totalVolume = 0; + // defined for shipment only + $totalOrdered = ''; + // defined for shipment only + $totalToShip = ''; - foreach ($this->lines as $line) - { - if (isset($line->qty_asked)) - { - if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is '' - $totalOrdered+=$line->qty_asked; // defined for shipment only - } - if (isset($line->qty_shipped)) - { - if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is '' - $totalToShip+=$line->qty_shipped; // defined for shipment only - } + foreach ($this->lines as $line) + { + if (isset($line->qty_asked)) + { + if (empty($totalOrdered)) $totalOrdered=0; // Avoid warning because $totalOrdered is '' + $totalOrdered+=$line->qty_asked; // defined for shipment only + } + if (isset($line->qty_shipped)) + { + if (empty($totalToShip)) $totalToShip=0; // Avoid warning because $totalToShip is '' + $totalToShip+=$line->qty_shipped; // defined for shipment only + } - // Define qty, weight, volume, weight_units, volume_units - if ($this->element == 'shipping') { - // for shipments - $qty = $line->qty_shipped ? $line->qty_shipped : 0; - } - else { - $qty = $line->qty ? $line->qty : 0; - } + // Define qty, weight, volume, weight_units, volume_units + if ($this->element == 'shipping') { + // for shipments + $qty = $line->qty_shipped ? $line->qty_shipped : 0; + } + else { + $qty = $line->qty ? $line->qty : 0; + } - $weight = $line->weight ? $line->weight : 0; - $volume = $line->volume ? $line->volume : 0; + $weight = $line->weight ? $line->weight : 0; + $volume = $line->volume ? $line->volume : 0; - $weight_units=$line->weight_units; - $volume_units=$line->volume_units; + $weight_units=$line->weight_units; + $volume_units=$line->volume_units; - $weightUnit=0; - $volumeUnit=0; - if (! empty($weight_units)) $weightUnit = $weight_units; - if (! empty($volume_units)) $volumeUnit = $volume_units; + $weightUnit=0; + $volumeUnit=0; + if (! empty($weight_units)) $weightUnit = $weight_units; + if (! empty($volume_units)) $volumeUnit = $volume_units; - if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is '' - if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is '' + if (empty($totalWeight)) $totalWeight=0; // Avoid warning because $totalWeight is '' + if (empty($totalVolume)) $totalVolume=0; // Avoid warning because $totalVolume is '' - //var_dump($line->volume_units); - if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) - { - $trueWeightUnit=pow(10, $weightUnit); - $totalWeight += $weight * $qty * $trueWeightUnit; - } - else { + //var_dump($line->volume_units); + if ($weight_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + { + $trueWeightUnit=pow(10, $weightUnit); + $totalWeight += $weight * $qty * $trueWeightUnit; + } + else { if ($weight_units == 99) { // conversion 1 Pound = 0.45359237 KG $trueWeightUnit = 0.45359237; @@ -3144,65 +3177,65 @@ abstract class CommonObject $totalWeight += $weight * $qty * $trueWeightUnit; } else - $totalWeight += $weight * $qty; // This may be wrong if we mix different units - } - if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) - { - //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit; - $trueVolumeUnit=pow(10, $volumeUnit); - //print $line->volume; - $totalVolume += $volume * $qty * $trueVolumeUnit; - } - else - { - $totalVolume += $volume * $qty; // This may be wrong if we mix different units - } - } + $totalWeight += $weight * $qty; // This may be wrong if we mix different units + } + if ($volume_units < 50) // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch) + { + //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit; + $trueVolumeUnit=pow(10, $volumeUnit); + //print $line->volume; + $totalVolume += $volume * $qty * $trueVolumeUnit; + } + else + { + $totalVolume += $volume * $qty; // This may be wrong if we mix different units + } + } - return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip); - } - - - /** - * Set extra parameters - * - * @return int <0 if KO, >0 if OK - */ - function setExtraParameters() - { - $this->db->begin(); - - $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null); - - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); - $sql.= " WHERE rowid = ".$this->id; - - dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } + return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip); + } /** - * Return incoterms informations - * TODO Use a cache for label get - * - * @return string incoterms info - */ - function display_incoterms() - { - $out = ''; + * Set extra parameters + * + * @return int <0 if KO, >0 if OK + */ + function setExtraParameters() + { + $this->db->begin(); + + $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null); + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); + $sql.= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + + + /** + * Return incoterms informations + * TODO Use a cache for label get + * + * @return string incoterms info + */ + function display_incoterms() + { + $out = ''; $this->libelle_incoterms = ''; if (!empty($this->fk_incoterms)) { @@ -3218,13 +3251,13 @@ abstract class CommonObject $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms; return $out; - } + } /** - * Return incoterms informations for pdf display - * - * @return string incoterms info - */ + * Return incoterms informations for pdf display + * + * @return string incoterms info + */ function getIncotermsForPDF() { $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; @@ -3244,31 +3277,31 @@ abstract class CommonObject } else { - $this->errors[] = $this->db->lasterror(); + $this->errors[] = $this->db->lasterror(); return false; } } /** - * Define incoterms values of current object - * - * @param int $id_incoterm Id of incoterm to set or '' to remove + * Define incoterms values of current object + * + * @param int $id_incoterm Id of incoterm to set or '' to remove * @param string $location location of incoterm - * @return int <0 if KO, >0 if OK - */ - function setIncoterms($id_incoterm, $location) - { - if ($this->id && $this->table_element) - { - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); + * @return int <0 if KO, >0 if OK + */ + function setIncoterms($id_incoterm, $location) + { + if ($this->id && $this->table_element) + { + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null"); $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null"); - $sql.= " WHERE rowid = " . $this->id; + $sql.= " WHERE rowid = " . $this->id; dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->fk_incoterms = $id_incoterm; + $resql=$this->db->query($sql); + if ($resql) + { + $this->fk_incoterms = $id_incoterm; $this->location_incoterms = $location; $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms; @@ -3278,45 +3311,45 @@ abstract class CommonObject $obj = $this->db->fetch_object($res); $this->libelle_incoterms = $obj->libelle; } - return 1; - } - else + return 1; + } + else { - $this->errors[] = $this->db->lasterror(); - return -1; - } - } - else return -1; - } + $this->errors[] = $this->db->lasterror(); + return -1; + } + } + else return -1; + } - /** - * Return if a country is inside the EEC (European Economic Community) - * @deprecated - * - * @return boolean true = country inside EEC, false = country outside EEC - */ - function isInEEC() - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - return isInEEC($this); - } + /** + * Return if a country is inside the EEC (European Economic Community) + * @deprecated + * + * @return boolean true = country inside EEC, false = country outside EEC + */ + function isInEEC() + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + return isInEEC($this); + } - // -------------------- - // TODO: All functions here must be redesigned and moved as they are not business functions but output functions - // -------------------- + // -------------------- + // TODO: All functions here must be redesigned and moved as they are not business functions but output functions + // -------------------- - /* This is to show add lines */ + /* This is to show add lines */ - /** - * Show add free and predefined products/services form - * - * @param int $dateSelector 1=Show also date range input fields - * @param Societe $seller Object thirdparty who sell - * @param Societe $buyer Object thirdparty who buy - * @return void - */ + /** + * Show add free and predefined products/services form + * + * @param int $dateSelector 1=Show also date range input fields + * @param Societe $seller Object thirdparty who sell + * @param Societe $buyer Object thirdparty who buy + * @return void + */ function formAddObjectLine($dateSelector,$seller,$buyer) { global $conf,$user,$langs,$object,$hookmanager; @@ -3328,7 +3361,7 @@ abstract class CommonObject $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line); // Output template part (modules that overwrite templates must declare this into descriptor) - // Use global variables + $dateSelector + $seller and $buyer + // Use global variables + $dateSelector + $seller and $buyer $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); foreach($dirtpls as $reldir) { @@ -3338,13 +3371,13 @@ abstract class CommonObject } else { $res=include $tpl; // for debug } - if ($res) break; + if ($res) break; } - } + } - /* This is to show array of line of details */ + /* This is to show array of line of details */ /** @@ -3381,75 +3414,75 @@ abstract class CommonObject $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { - print '
      '; + print ''; - if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ''; + if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ''; - // Description - print ''; + // Description + print ''; - if ($this->element == 'supplier_proposal') - { - print ''; - } + if ($this->element == 'supplier_proposal') + { + print ''; + } - // VAT - print ''; + // VAT + print ''; - // Price HT - print ''; + // Price HT + print ''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''; + // Multicurrency + if (!empty($conf->multicurrency->enabled)) print ''; - if ($inputalsopricewithtax) print ''; + if ($inputalsopricewithtax) print ''; - // Qty - print ''; + // Qty + print ''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''; - } + if($conf->global->PRODUCT_USE_UNITS) + { + print ''; + } - // Reduction short - print ''; + // Reduction short + print ''; - if ($this->situation_cycle_ref) { - print ''; - } + if ($this->situation_cycle_ref) { + print ''; + } - if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) - { - if (!empty($user->rights->margins->creer)) - { - if ($conf->global->MARGIN_TYPE == "1") - print ''; - else - print ''; - } + if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) + { + if (!empty($user->rights->margins->creer)) + { + if ($conf->global->MARGIN_TYPE == "1") + print ''; + else + print ''; + } - if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) - print ''; - if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) - print ''; - } + if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) + print ''; + if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) + print ''; + } - // Total HT - print ''; + // Total HT + print ''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''; + // Multicurrency + if (!empty($conf->multicurrency->enabled)) print ''; - if ($outputalsopricetotalwithtax) print ''; + if ($outputalsopricetotalwithtax) print ''; - print ''; // No width to allow autodim + print ''; // No width to allow autodim - print ''; + print ''; - print ''; + print ''; - print "\n"; + print "\n"; } $var = true; @@ -3463,20 +3496,20 @@ abstract class CommonObject //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) - if (is_object($hookmanager)) // Old code is commented on preceding line. + if (is_object($hookmanager)) // Old code is commented on preceding line. { if (empty($line->fk_parent_line)) { $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline); - $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } else { $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline, 'fk_parent_line'=>$line->fk_parent_line); - $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } } - if (empty($reshook)) + if (empty($reshook)) { $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline); } @@ -3528,8 +3561,8 @@ abstract class CommonObject $product_static = new Product($this->db); $product_static->fetch($line->fk_product); - $product_static->ref = $line->ref; //can change ref in hook - $product_static->label = $line->label; //can change label in hook + $product_static->ref = $line->ref; //can change ref in hook + $product_static->label = $line->label; //can change label in hook $text=$product_static->getNomUrl(1); // Define output language and label @@ -3608,74 +3641,74 @@ abstract class CommonObject } - /* This is to show array of line of details of source object */ + /* This is to show array of line of details of source object */ - /** - * 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. - * - * @return void - */ - function printOriginLinesList() - { - global $langs, $hookmanager, $conf; + /** + * 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, so we keep the method available on overloaded objects. + * + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only + * @return void + */ + function printOriginLinesList($restrictlist='') + { + global $langs, $hookmanager, $conf; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; if (!empty($conf->multicurrency->enabled)) print ''; - print ''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''; - } - print ''; + print ''; + if($conf->global->PRODUCT_USE_UNITS) + { + print ''; + } + print ''; - $var = true; - $i = 0; + $var = true; + $i = 0; - foreach ($this->lines as $line) - { + 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)) + { + $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); + $action=''; + $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + } + } + else + { + $this->printOriginLine($line, $var, $restrictlist); + } + $i++; + } + } - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) - { - if (empty($line->fk_parent_line)) - { - $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); - $action=''; - $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - } - } - else - { - $this->printOriginLine($line,$var); - } + /** + * Return HTML with a line of table array 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. + * + * @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, $restrictlist='') + { + global $langs, $conf; - $i++; - } - } - - /** - * Return HTML with a line of table array 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. - * - * @param CommonObjectLine $line Line - * @param string $var Var - * @return void - */ - function printOriginLine($line,$var) - { - global $langs, $conf; - - //var_dump($line); + //var_dump($line); if (!empty($line->date_start)) { $date_start=$line->date_start; @@ -3695,98 +3728,102 @@ abstract class CommonObject if ($line->date_fin_reel) $date_end=$line->date_fin_reel; } - $this->tpl['label'] = ''; - if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow'); + $this->tpl['label'] = ''; + if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow'); - if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fk_soc = $this->socid; - $this->tpl['label'].= $discount->getNomUrl(0,'discount'); - } - else if (! empty($line->fk_product)) - { - $productstatic = new Product($this->db); - $productstatic->id = $line->fk_product; - $productstatic->ref = $line->ref; - $productstatic->type = $line->fk_product_type; - $this->tpl['label'].= $productstatic->getNomUrl(1); - $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label); - // Dates - if ($line->product_type == 1 && ($date_start || $date_end)) - { - $this->tpl['label'].= get_date_range($date_start,$date_end); - } - } - else - { - $this->tpl['label'].= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product'))); - if (!empty($line->desc)) { - $this->tpl['label'].=$line->desc; - }else { - $this->tpl['label'].= ($line->label ? ' '.$line->label : ''); - } - // Dates - if ($line->product_type == 1 && ($date_start || $date_end)) - { - $this->tpl['label'].= get_date_range($date_start,$date_end); - } - } + if (($line->info_bits & 2) == 2) // TODO Not sure this is used for source object + { + $discount=new DiscountAbsolute($this->db); + $discount->fk_soc = $this->socid; + $this->tpl['label'].= $discount->getNomUrl(0,'discount'); + } + else if (! empty($line->fk_product)) + { + $productstatic = new Product($this->db); + $productstatic->id = $line->fk_product; + $productstatic->ref = $line->ref; + $productstatic->type = $line->fk_product_type; + $this->tpl['label'].= $productstatic->getNomUrl(1); + $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label); + // Dates + if ($line->product_type == 1 && ($date_start || $date_end)) + { + $this->tpl['label'].= get_date_range($date_start,$date_end); + } + } + else + { + $this->tpl['label'].= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product'))); + if (!empty($line->desc)) { + $this->tpl['label'].=$line->desc; + }else { + $this->tpl['label'].= ($line->label ? ' '.$line->label : ''); + } + // Dates + if ($line->product_type == 1 && ($date_start || $date_end)) + { + $this->tpl['label'].= get_date_range($date_start,$date_end); + } + } - if (! empty($line->desc)) - { - if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); - } - elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); - } - elseif ($line->desc == '(EXCESS RECEIVED)') - { - $discount=new DiscountAbsolute($this->db); - $discount->fetch($line->fk_remise_except); - $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); - } - else - { - $this->tpl['description'] = dol_trunc($line->desc,60); - } - } - else - { - $this->tpl['description'] = ' '; - } + if (! empty($line->desc)) + { + if ($line->desc == '(CREDIT_NOTE)') // TODO Not sure this is used for source object + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0)); + } + elseif ($line->desc == '(DEPOSIT)') // TODO Not sure this is used for source object + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0)); + } + elseif ($line->desc == '(EXCESS RECEIVED)') + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); + } + else + { + $this->tpl['description'] = dol_trunc($line->desc,60); + } + } + else + { + $this->tpl['description'] = ' '; + } - // VAT Rate - $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); - if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')'; + // VAT Rate + $this->tpl['vat_rate'] = vatrate($line->tva_tx, true); + if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')'; - $this->tpl['price'] = price($line->subprice); + $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'); - $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; + $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; + if($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $line->getLabelOfUnit('long'); + $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; - // 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')); - foreach($dirtpls as $reldir) - { - $tpl = dol_buildpath($reldir.'/originproductline.tpl.php'); - if (empty($conf->file->strict_mode)) { - $res=@include $tpl; - } else { - $res=include $tpl; // for debug - } - if ($res) break; - } - } + // 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')); + foreach($dirtpls as $reldir) + { + $tpl = dol_buildpath($reldir.'/originproductline.tpl.php'); + if (empty($conf->file->strict_mode)) { + $res=@include $tpl; + } else { + $res=include $tpl; // for debug + } + if ($res) break; + } + } /** @@ -3843,32 +3880,32 @@ abstract class CommonObject */ function delete_resource($rowid, $element, $notrigger=0) { - global $user; + global $user; - $this->db->begin(); + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; - $sql.= " WHERE rowid=".$rowid; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; + $sql.= " WHERE rowid=".$rowid; - dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); + dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - $this->db->commit(); - return 1; - } + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + if (! $notrigger) + { + $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); + if ($result < 0) { $this->db->rollback(); return -1; } + } + $this->db->commit(); + return 1; + } } @@ -3878,17 +3915,17 @@ abstract class CommonObject * @return void */ function __clone() - { - // Force a copy of this->lines, otherwise it will point to same object. - if (isset($this->lines) && is_array($this->lines)) - { - $nboflines=count($this->lines); - for($i=0; $i < $nboflines; $i++) - { - $this->lines[$i] = clone $this->lines[$i]; - } - } - } + { + // Force a copy of this->lines, otherwise it will point to same object. + if (isset($this->lines) && is_array($this->lines)) + { + $nboflines=count($this->lines); + for($i=0; $i < $nboflines; $i++) + { + $this->lines[$i] = clone $this->lines[$i]; + } + } + } /** * Common function for all objects extending CommonObject for generating documents @@ -3930,7 +3967,7 @@ abstract class CommonObject { foreach(array('doc','pdf') as $prefix) { - if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php else $file = $prefix."_".$modele.".modules.php"; // On verifie l'emplacement du modele @@ -3965,27 +4002,27 @@ abstract class CommonObject $listoffiles=array(); // Now we add first model found in directories scanned - $listofdir=explode(',',$dirtoscan); - foreach($listofdir as $key => $tmpdir) - { - $tmpdir=trim($tmpdir); - $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir); - if (! $tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { - $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0); - if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles); - } - } + $listofdir=explode(',',$dirtoscan); + foreach($listofdir as $key => $tmpdir) + { + $tmpdir=trim($tmpdir); + $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir); + if (! $tmpdir) { unset($listofdir[$key]); continue; } + if (is_dir($tmpdir)) + { + $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0); + if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles); + } + } - if (count($listoffiles)) - { - foreach($listoffiles as $record) - { - $srctemplatepath=$record['fullname']; - break; - } - } + if (count($listoffiles)) + { + foreach($listoffiles as $record) + { + $srctemplatepath=$record['fullname']; + break; + } + } } if (empty($srctemplatepath)) @@ -3995,14 +4032,14 @@ abstract class CommonObject } } - if ($obj->type == 'odt' && ! empty($srctemplatepath)) - { - if (! dol_is_file($srctemplatepath)) - { - $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; - return -1; - } - } + if ($obj->type == 'odt' && ! empty($srctemplatepath)) + { + if (! dol_is_file($srctemplatepath)) + { + $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; + return -1; + } + } // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. @@ -4010,8 +4047,8 @@ abstract class CommonObject if (in_array(get_class($this), array('Adherent'))) { - $arrayofrecords = array(); // The write_file of templates of adherent class need this - $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); + $arrayofrecords = array(); // The write_file of templates of adherent class need this + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); } else { @@ -4115,190 +4152,190 @@ abstract class CommonObject if (file_exists($file_osencoded)) { // Create small thumbs for company (Ratio is near 16/9) - // Used on logon for example - vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality); + // Used on logon for example + vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality); - // Create mini thumbs for company (Ratio is near 16/9) - // Used on menu or for setup page for example - vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality); + // Create mini thumbs for company (Ratio is near 16/9) + // Used on menu or for setup page for example + vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality); } } /* Functions common to commonobject and commonobjectline */ - /* For default values */ + /* For default values */ - /** - * Return the default value to use for a field when showing the create form of object. - * Return values in this order: - * 1) If parameter is available into POST, we return it first. - * 2) If not but an alternate value was provided as parameter of function, we return it. - * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table). - * 4) Return value found into database (TODO No yet implemented) - * - * @param string $fieldname Name of field - * @param string $alternatevalue Alternate value to use - * @return string|string[] Default value (can be an array if the GETPOST return an array) - **/ + /** + * Return the default value to use for a field when showing the create form of object. + * Return values in this order: + * 1) If parameter is available into POST, we return it first. + * 2) If not but an alternate value was provided as parameter of function, we return it. + * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table). + * 4) Return value found into database (TODO No yet implemented) + * + * @param string $fieldname Name of field + * @param string $alternatevalue Alternate value to use + * @return string|string[] Default value (can be an array if the GETPOST return an array) + **/ function getDefaultCreateValueFor($fieldname, $alternatevalue=null) - { - global $conf, $_POST; + { + global $conf, $_POST; - // If param here has been posted, we use this value first. - if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2); + // If param here has been posted, we use this value first. + if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2); - if (isset($alternatevalue)) return $alternatevalue; + if (isset($alternatevalue)) return $alternatevalue; - $newelement=$this->element; - if ($newelement == 'facture') $newelement='invoice'; - if ($newelement == 'commande') $newelement='order'; - if (empty($newelement)) - { - dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING); - return ''; - } + $newelement=$this->element; + if ($newelement == 'facture') $newelement='invoice'; + if ($newelement == 'commande') $newelement='order'; + if (empty($newelement)) + { + dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING); + return ''; + } - $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname); - //var_dump($keyforfieldname); - if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; + $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname); + //var_dump($keyforfieldname); + if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname; - // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname + // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname - } + } /* For triggers */ - /** - * Call trigger based on this instance. - * Some context information may also be provided into array property this->context. - * NB: Error from trigger are stacked in interface->errors - * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. - * - * @param string $trigger_name trigger's name to execute - * @param User $user Object user - * @return int Result of run_triggers - */ - function call_trigger($trigger_name, $user) - { - global $langs,$conf; + /** + * Call trigger based on this instance. + * Some context information may also be provided into array property this->context. + * NB: Error from trigger are stacked in interface->errors + * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. + * + * @param string $trigger_name trigger's name to execute + * @param User $user Object user + * @return int Result of run_triggers + */ + function call_trigger($trigger_name, $user) + { + global $langs,$conf; - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); - if ($result < 0) - { - if (!empty($this->errors)) - { - $this->errors=array_unique(array_merge($this->errors,$interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. - } - else - { - $this->errors=$interface->errors; - } - } - return $result; - } + if ($result < 0) + { + if (!empty($this->errors)) + { + $this->errors=array_unique(array_merge($this->errors,$interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice. + } + else + { + $this->errors=$interface->errors; + } + } + return $result; + } - /* Functions for extrafields */ + /* Functions for extrafields */ - /** - * Function to get extra fields of a member into $this->array_options - * This method is in most cases called by method fetch of objects but you can call it separately. - * - * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters. - * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters. - * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded - */ - function fetch_optionals($rowid=null,$optionsArray=null) - { - if (empty($rowid)) $rowid=$this->id; + /** + * Function to get extra fields of a member into $this->array_options + * This method is in most cases called by method fetch of objects but you can call it separately. + * + * @param int $rowid Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters. + * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters. + * @return int <0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded + */ + function fetch_optionals($rowid=null,$optionsArray=null) + { + if (empty($rowid)) $rowid=$this->id; - // To avoid SQL errors. Probably not the better solution though - if (!$this->table_element) { - return 0; - } + // To avoid SQL errors. Probably not the better solution though + if (!$this->table_element) { + return 0; + } - if (! is_array($optionsArray)) - { - // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. - // TODO Use of existing extrafield is not yet ready (must mutualize code that use extrafields in form first) - // global $extrafields; - //if (! is_object($extrafields)) - //{ - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - //} + if (! is_array($optionsArray)) + { + // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. + // TODO Use of existing extrafield is not yet ready (must mutualize code that use extrafields in form first) + // global $extrafields; + //if (! is_object($extrafields)) + //{ + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + //} - // Load array of extrafields for elementype = $this->table_element - if (empty($extrafields->attributes[$this->table_element]['loaded'])) - { - $extrafields->fetch_name_optionals_label($this->table_element); - } - $optionsArray = $extrafields->attributes[$this->table_element]['label']; - } + // Load array of extrafields for elementype = $this->table_element + if (empty($extrafields->attributes[$this->table_element]['loaded'])) + { + $extrafields->fetch_name_optionals_label($this->table_element); + } + $optionsArray = $extrafields->attributes[$this->table_element]['label']; + } - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility + $table_element = $this->table_element; + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - // Request to get complementary values - if (is_array($optionsArray) && count($optionsArray) > 0) - { - $sql = "SELECT rowid"; - foreach ($optionsArray as $name => $label) - { - if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') - { - $sql.= ", ".$name; - } - } - $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; - $sql.= " WHERE fk_object = ".$rowid; + // Request to get complementary values + if (is_array($optionsArray) && count($optionsArray) > 0) + { + $sql = "SELECT rowid"; + foreach ($optionsArray as $name => $label) + { + if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') + { + $sql.= ", ".$name; + } + } + $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; + $sql.= " WHERE fk_object = ".$rowid; - dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $numrows=$this->db->num_rows($resql); - if ($numrows) - { - $tab = $this->db->fetch_array($resql); + dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $numrows=$this->db->num_rows($resql); + if ($numrows) + { + $tab = $this->db->fetch_array($resql); - foreach ($tab as $key => $value) - { - // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine) - if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) - { - // we can add this attribute to object - $this->array_options["options_".$key]=$value; - } - } - } + foreach ($tab as $key => $value) + { + // Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine) + if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) + { + // we can add this attribute to object + $this->array_options["options_".$key]=$value; + } + } + } - $this->db->free($resql); + $this->db->free($resql); - if ($numrows) return $numrows; - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } - return 0; - } + if ($numrows) return $numrows; + else return 0; + } + else + { + dol_print_error($this->db); + return -1; + } + } + return 0; + } - /** - * Delete all extra fields values for the current object. - * - * @return int <0 if KO, >0 if OK - */ + /** + * Delete all extra fields values for the current object. + * + * @return int <0 if KO, >0 if OK + */ function deleteExtraFields() { $this->db->begin(); @@ -4322,256 +4359,257 @@ abstract class CommonObject } } - /** - * Add/Update all extra fields values for the current object. - * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * This function delete record with all extrafields and insert them again from the array $this->array_options. - * - * @return int -1=error, O=did nothing, 1=OK - */ - function insertExtraFields() - { - global $conf,$langs; + /** + * Add/Update all extra fields values for the current object. + * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) + * This function delete record with all extrafields and insert them again from the array $this->array_options. + * + * @return int -1=error, O=did nothing, 1=OK + */ + function insertExtraFields() + { + global $conf,$langs; $error=0; if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - if (! empty($this->array_options)) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); + if (! empty($this->array_options)) + { + // Check parameters + $langs->load('admin'); + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); - //Eliminate copied source object extra_fields that do not exist in target object - $new_array_options=array(); - foreach ($this->array_options as $key => $value) { - if (in_array(substr($key,8), array_keys($target_extrafields))) - $new_array_options[$key] = $value; - } + //Eliminate copied source object extra_fields that do not exist in target object + $new_array_options=array(); + foreach ($this->array_options as $key => $value) { + if (in_array(substr($key,8), array_keys($target_extrafields))) + $new_array_options[$key] = $value; + } - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - $attributeType = $extrafields->attribute_type[$attributeKey]; - $attributeLabel = $extrafields->attribute_label[$attributeKey]; - $attributeParam = $extrafields->attribute_param[$attributeKey]; - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); - return -1; - } - elseif ($value=='') - { - $new_array_options[$key] = null; - } - break; - /*case 'select': // Not required, we chosed value='0' for undefined values + foreach($new_array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + $attributeType = $extrafields->attribute_type[$attributeKey]; + $attributeLabel = $extrafields->attribute_label[$attributeKey]; + $attributeParam = $extrafields->attribute_param[$attributeKey]; + switch ($attributeType) + { + case 'int': + if (!is_numeric($value) && $value!='') + { + $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); + return -1; + } + elseif ($value=='') + { + $new_array_options[$key] = null; + } + break; + /*case 'select': // Not required, we chosed value='0' for undefined values if ($value=='-1') { $this->array_options[$key] = null; } break;*/ - case 'price': - $new_array_options[$key] = price2num($this->array_options[$key]); - break; - case 'date': - $new_array_options[$key] = $this->db->idate($this->array_options[$key]); - break; - case 'datetime': - $new_array_options[$key] = $this->db->idate($this->array_options[$key]); - break; - case 'link': + case 'price': + $new_array_options[$key] = price2num($this->array_options[$key]); + break; + case 'date': + $new_array_options[$key] = $this->db->idate($this->array_options[$key]); + break; + case 'datetime': + $new_array_options[$key] = $this->db->idate($this->array_options[$key]); + break; + case 'link': $param_list=array_keys($attributeParam ['options']); // 0 : ObjectName // 1 : classPath $InfoFieldList = explode(":", $param_list[0]); dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - $object = new $InfoFieldList[0]($this->db); - if ($value) - { - if (is_numeric($value)) $res=$object->fetch($value); + if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) + { + $object = new $InfoFieldList[0]($this->db); + if ($value) + { + if (is_numeric($value)) $res=$object->fetch($value); else $res=$object->fetch('',$value); - if ($res > 0) $new_array_options[$key]=$object->id; - else - { - $this->error="Ref '".$value."' for object '".$object->element."' not found"; - $this->db->rollback(); - return -1; - } - } - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - } + if ($res > 0) $new_array_options[$key]=$object->id; + else + { + $this->error="Ref '".$value."' for object '".$object->element."' not found"; + $this->db->rollback(); + return -1; + } + } + } + else + { + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + } break; - } - } - $this->db->begin(); + } + } + $this->db->begin(); - $table_element = $this->table_element; - if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility + $table_element = $this->table_element; + if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility - $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; - dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG); - $this->db->query($sql_del); + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id; + dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG); + $this->db->query($sql_del); - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field of attribut - if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate - $sql.=",".$attributeKey; - } - $sql .= ") VALUES (".$this->id; - foreach($new_array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field o fattribut - if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) - { - if ($new_array_options[$key] != '') - { - $sql.=",'".$this->db->escape($new_array_options[$key])."'"; - } - else - { - $sql.=",null"; - } - } - } - $sql.=")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object"; + foreach($new_array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + // Add field of attribut + if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate + $sql.=",".$attributeKey; + } + $sql .= ") VALUES (".$this->id; + foreach($new_array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + // Add field o fattribut + if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) + { + if ($new_array_options[$key] != '') + { + $sql.=",'".$this->db->escape($new_array_options[$key])."'"; + } + else + { + $sql.=",null"; + } + } + } + $sql.=")"; - dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } + dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + else return 0; + } - /** - * Update an exta field value for the current object. - * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * This function delte record with all extrafields and insert them again from the array $this->array_options. - * - * @param string $key Key of the extrafield - * @return int -1=error, O=did nothing, 1=OK - */ - function updateExtraField($key) - { - global $conf,$langs; + /** + * Update an exta field value for the current object. + * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) + * This function delte record with all extrafields and insert them again from the array $this->array_options. + * + * @param string $key Key of the extrafield + * @return int -1=error, O=did nothing, 1=OK + */ + function updateExtraField($key) + { + global $conf,$langs; $error=0; if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - if (! empty($this->array_options) && isset($this->array_options["options_".$key])) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); + if (! empty($this->array_options) && isset($this->array_options["options_".$key])) + { + // Check parameters + $langs->load('admin'); + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); - $value=$this->array_options["options_".$key]; - $attributeType = $extrafields->attribute_type[$key]; - $attributeLabel = $extrafields->attribute_label[$key]; - $attributeParam = $extrafields->attribute_param[$key]; - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); - return -1; - } - elseif ($value=='') - { - $this->array_options["options_".$key] = null; - } - break; - /*case 'select': // Not required, we chosed value='0' for undefined values + $value=$this->array_options["options_".$key]; + $attributeType = $extrafields->attribute_type[$key]; + $attributeLabel = $extrafields->attribute_label[$key]; + $attributeParam = $extrafields->attribute_param[$key]; + switch ($attributeType) + { + case 'int': + if (!is_numeric($value) && $value!='') + { + $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); + return -1; + } + elseif ($value=='') + { + $this->array_options["options_".$key] = null; + } + break; + /*case 'select': // Not required, we chosed value='0' for undefined values if ($value=='-1') { $this->array_options[$key] = null; } break;*/ - case 'price': - $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); - break; - case 'date': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); - break; - case 'datetime': - $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); - break; - case 'link': - $param_list=array_keys($attributeParam ['options']); - // 0 : ObjectName - // 1 : classPath - $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - $object = new $InfoFieldList[0]($this->db); - if ($value) - { - $object->fetch(0,$value); - $this->array_options["options_".$key]=$object->id; - } - break; - } + case 'price': + $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); + break; + case 'date': + $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); + break; + case 'datetime': + $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); + break; + case 'link': + $param_list=array_keys($attributeParam ['options']); + // 0 : ObjectName + // 1 : classPath + $InfoFieldList = explode(":", $param_list[0]); + dol_include_once($InfoFieldList[1]); + $object = new $InfoFieldList[0]($this->db); + if ($value) + { + $object->fetch(0,$value); + $this->array_options["options_".$key]=$object->id; + } + break; + } - $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; - $sql .= " WHERE fk_object = ".$this->id; - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } + $this->db->begin(); + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'"; + $sql .= " WHERE fk_object = ".$this->id; + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + else return 0; + } - /** - * Function to show lines of extrafields with output datas - * + /** + * 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, $keyprefix='') - { - global $_POST, $conf, $langs; + * + * @return string + */ + function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='') + { + global $_POST, $conf, $langs, $action; $out = ''; @@ -4594,23 +4632,29 @@ abstract class CommonObject }else { $colspan='3'; } + switch($mode) { case "view": - $value=$this->array_options["options_".$key]; + $value=$this->array_options["options_".$key.$keysuffix]; break; case "edit": - if (isset($_POST["options_" . $key])) { - if (is_array($_POST["options_" . $key])) { - // $_POST["options"] is an array but following code expects a comma separated string - $value = implode(",", $_POST["options_" . $key]); + $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($keyprefix.'options_'.$key.$keysuffix)) + { + if (is_array($getposttemp)) { + // $getposttemp is an array but following code expects a comma separated string + $value = implode(",", $getposttemp); } else { - $value = $_POST["options_" . $key]; + $value = $getposttemp; } } else { - $value = $this->array_options["options_" . $key]; + $value = $this->array_options["options_" . $key]; // No GET, no POST, no default value, so we take value of object. } break; } + //var_dump($value); + if ($extrafields->attribute_type[$key] == 'separate') { $out .= $extrafields->showSeparator($key); @@ -4633,13 +4677,19 @@ abstract class CommonObject { $out .= ''; } - // Convert date into timestamp format + // 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 = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix,'int',3)):$this->array_options['options_'.$key]; } $labeltoshow = $langs->trans($label); + if($extrafields->attribute_required[$key]) { $labeltoshow = ''.$labeltoshow.''; @@ -4650,12 +4700,12 @@ abstract class CommonObject $out .=''; @@ -4667,8 +4717,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 @@ -4736,9 +4788,9 @@ abstract class CommonObject if (! $db->query($sql)) { - if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. + if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B. //$this->errors = $db->lasterror(); - return false; + return false; } } @@ -4999,40 +5051,40 @@ abstract class CommonObject */ private function setVarsFromFetchObj(&$obj) { - foreach ($this->fields as $field => $info) - { - if($this->isDate($info)) - { - if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; - else $this->{$field} = strtotime($obj->{$field}); - } - elseif($this->isArray($info)) - { - $this->{$field} = @unserialize($obj->{$field}); - // Hack for data not in UTF8 - if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field})); - } - elseif($this->isInt($info)) - { - if ($field == 'rowid') $this->id = (int) $obj->{$field}; - else $this->{$field} = (int) $obj->{$field}; - } - elseif($this->isFloat($info)) - { - $this->{$field} = (double) $obj->{$field}; - } - elseif($this->isNull($info)) - { - $val = $obj->{$field}; - // zero is not null - $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val); - } - else - { - $this->{$field} = $obj->{$field}; - } + foreach ($this->fields as $field => $info) + { + if($this->isDate($info)) + { + if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0; + else $this->{$field} = strtotime($obj->{$field}); + } + elseif($this->isArray($info)) + { + $this->{$field} = @unserialize($obj->{$field}); + // Hack for data not in UTF8 + if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field})); + } + elseif($this->isInt($info)) + { + if ($field == 'rowid') $this->id = (int) $obj->{$field}; + else $this->{$field} = (int) $obj->{$field}; + } + elseif($this->isFloat($info)) + { + $this->{$field} = (double) $obj->{$field}; + } + elseif($this->isNull($info)) + { + $val = $obj->{$field}; + // zero is not null + $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val); + } + else + { + $this->{$field} = $obj->{$field}; + } - } + } } /** @@ -5042,8 +5094,8 @@ abstract class CommonObject */ private function get_field_list() { - $keys = array_keys($this->fields); - return implode(',', $keys); + $keys = array_keys($this->fields); + return implode(',', $keys); } /** @@ -5054,9 +5106,9 @@ abstract class CommonObject * @return string */ protected function quote($value, $fieldsentry) { - if (is_null($value)) return 'NULL'; - else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value"); - else return "'".$this->db->escape($value)."'"; + if (is_null($value)) return 'NULL'; + else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value"); + else return "'".$this->db->escape($value)."'"; } @@ -5069,47 +5121,47 @@ abstract class CommonObject */ public function createCommon(User $user, $notrigger = false) { - $error = 0; + $error = 0; - $now=dol_now(); + $now=dol_now(); - $fieldvalues = $this->set_save_query(); + $fieldvalues = $this->set_save_query(); if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now); if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id; unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert. - $keys=array(); - $values = array(); - foreach ($fieldvalues as $k => $v) { - $keys[] = $k; - $values[] = $this->quote($v, $this->fields[$k]); - } + $keys=array(); + $values = array(); + foreach ($fieldvalues as $k => $v) { + $keys[] = $k; + $values[] = $this->quote($v, $this->fields[$k]); + } - $this->db->begin(); + $this->db->begin(); - if (! $error) - { - $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' ('.implode( ", ", $keys ).')'; - $sql.= ' VALUES ('.implode( ", ", $values ).')'; + if (! $error) + { + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element; + $sql.= ' ('.implode( ", ", $keys ).')'; + $sql.= ' VALUES ('.implode( ", ", $values ).')'; $res = $this->db->query($sql); - if ($res===false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } + if ($res===false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } - if (! $error && ! $notrigger) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + if (! $error && ! $notrigger) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); - if (!$notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } + if (!$notrigger) { + // Call triggers + $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } // Commit or rollback if ($error) { @@ -5142,30 +5194,30 @@ abstract class CommonObject $res = $this->db->query($sql); if ($res) { - if ($obj = $this->db->fetch_object($res)) - { - if ($obj) - { - $this->setVarsFromFetchObj($obj); - return $this->id; - } - else - { - return 0; - } - } - else - { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - return -1; - } + if ($obj = $this->db->fetch_object($res)) + { + if ($obj) + { + $this->setVarsFromFetchObj($obj); + return $this->id; + } + else + { + return 0; + } + } + else + { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + return -1; + } } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; - return -1; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + return -1; } } @@ -5178,7 +5230,7 @@ abstract class CommonObject */ public function updateCommon(User $user, $notrigger = false) { - $error = 0; + $error = 0; $fieldvalues = $this->set_save_query(); unset($fieldvalues['rowid']); // We don't update this field, it is the key to define which record to update. @@ -5203,28 +5255,28 @@ abstract class CommonObject $this->db->begin(); if (! $error) { - $res = $this->db->query($sql); - if ($res===false) - { - $error++; - $this->errors[] = $this->db->lasterror(); - } + $res = $this->db->query($sql); + if ($res===false) + { + $error++; + $this->errors[] = $this->db->lasterror(); + } } if (! $error && ! $notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user); - if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail - // End call triggers + // Call triggers + $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user); + if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail + // End call triggers } // Commit or rollback if ($error) { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } else { - $this->db->commit(); - return $this->id; + $this->db->commit(); + return $this->id; } } @@ -5237,37 +5289,37 @@ abstract class CommonObject */ public function deleteCommon(User $user, $notrigger = false) { - $error=0; + $error=0; - $this->db->begin(); + $this->db->begin(); - if (! $error) { - if (! $notrigger) { - // Call triggers - $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail - // End call triggers - } - } + if (! $error) { + if (! $notrigger) { + // Call triggers + $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); + if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + // End call triggers + } + } - if (! $error) - { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + if (! $error) + { + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; - $res = $this->db->query($sql); - if($res===false) { - $error++; - $this->errors[] = $this->db->lasterror(); - } - } + $res = $this->db->query($sql); + if($res===false) { + $error++; + $this->errors[] = $this->db->lasterror(); + } + } - // Commit or rollback + // Commit or rollback if ($error) { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } else { - $this->db->commit(); - return 1; + $this->db->commit(); + return 1; } } @@ -5279,9 +5331,32 @@ abstract class CommonObject */ public function initAsSpecimenCommon() { - $this->id = 0; + $this->id = 0; - // TODO... + // TODO... + } + + /** + * Load comments linked with current task + * @return boolean 1 if ok + */ + public function fetchComments() + { + require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php'; + + $comment = new Comment($this->db); + $this->comments = Comment::fetchAllFor($this->element, $this->id); + return 1; + } + + /** + * Return nb comments already posted + * + * @return int + */ + public function getNbComments() + { + return count($this->comments); } } diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index aa1651d6fc6..e0e032d7e25 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -259,9 +259,8 @@ class Conf // Load translation object with current language if (empty($this->global->MAIN_LANG_DEFAULT)) $this->global->MAIN_LANG_DEFAULT="en_US"; - // By default, we repeat info on all tabs - if (! isset($this->global->MAIN_REPEATCONTACTONEACHTAB)) $this->global->MAIN_REPEATCONTACTONEACHTAB=1; - if (! isset($this->global->MAIN_REPEATADDRESSONEACHTAB)) $this->global->MAIN_REPEATADDRESSONEACHTAB=1; + //if (! isset($this->global->MAIN_REPEATCONTACTONEACHTAB)) $this->global->MAIN_REPEATCONTACTONEACHTAB=1; + //if (! isset($this->global->MAIN_REPEATADDRESSONEACHTAB)) $this->global->MAIN_REPEATADDRESSONEACHTAB=1; $rootfordata = DOL_DATA_ROOT; $rootforuser = DOL_DATA_ROOT; diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index d4432435704..37dedea8b6b 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -445,14 +445,14 @@ class DiscountAbsolute $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f'; $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; - $sql.= ' AND f.type = 2'; + $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received } else if ($invoice->element == 'invoice_supplier') { $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; - $sql.= ' AND f.type = 2'; + $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received } else { diff --git a/htdocs/core/class/emailsenderprofile.class.php b/htdocs/core/class/emailsenderprofile.class.php new file mode 100644 index 00000000000..f211a0b1670 --- /dev/null +++ b/htdocs/core/class/emailsenderprofile.class.php @@ -0,0 +1,444 @@ + + * Copyright (C) 2014-2016 Juanjo Menent + * Copyright (C) 2015 Florian Henry + * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) ---Put here your own copyright and developer email--- + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/emailsenderprofile.class.php + * \ingroup monmodule + * \brief This file is a CRUD class file for EmailSenderProfile (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for EmailSenderProfile + */ +class EmailSenderProfile extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'emailsenderprofile'; + /** + * @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 + */ + protected $ismultientitymanaged = 1; + /** + * @var string String with name of icon for emailsenderprofile + */ + public $picto = 'emailsenderprofile@monmodule'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the filed must be managed. + * 'visible' says if field is visible in list (-1 means not shown by default but can be added into list to be viewed). + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1), + 'email' => array('type'=>'varchar(255)', 'label'=>'Email', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1), + //'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + //'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>-1,), + 'signature' => array('type'=>'text', 'label'=>'Signature', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), + 'position' => array('type'=>'integer', 'label'=>'Position', 'visible'=>-1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-1, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'active' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1, 'index'=>1), + ); + public $rowid; + public $entity; + public $label; + public $email; + public $date_creation; + public $tms; + //public $fk_user_creat; + //public $fk_user_modif; + public $signature; + public $position; + public $active; + // END MODULEBUILDER PROPERTIES + + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'emailsenderprofiledet'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + //public $fk_element = 'fk_emailsenderprofile'; + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'EmailSenderProfileline'; + /** + * @var array Array of child tables (child tables to delete before deleting a record) + */ + //protected $childtables=array('emailsenderprofiledet'); + /** + * @var EmailSenderProfileLine[] Array of subtable lines + */ + //public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone and object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $hookmanager, $langs; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines=array(); + + // Load lines with object EmailSenderProfileLine + + return count($this->lines)?1:0; + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @return string String with URL + */ + function getNomUrl($withpicto=0) + { + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + $result = ''; + $companylink = ''; + + $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.=' '; + } + $result.= $linkstart . $this->label . $linkend; + return $result; + } + + /** + * Return link to download file from a direct external access + * + * @param int $withpicto Add download picto into link + * @return string HTML link to file + */ + function getDirectExternalLink($withpicto=0) + { + return 'todo'; + } + + /** + * Retourne le libelle du status d'un user (actif, inactif) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label of status + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 5) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + } + + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql.= ' fk_user_creat, fk_user_modif'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql.= ' WHERE t.rowid = '.$id; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + + } + else + { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + +} + +/** + * Class EmailSenderProfileLine. You can also remove this and generate a CRUD class for lines objects. + */ +/* +class EmailSenderProfileLine +{ + // @var int ID + public $id; + // @var mixed Sample line property 1 + public $prop1; + // @var mixed Sample line property 2 + public $prop2; +} +*/ \ No newline at end of file diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index f79198a7096..7130287b6bd 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -140,14 +140,14 @@ class ExtraFields * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check - * @param int $list Into list view by default + * @param int $list Into list view by default (-1, 0 or 1) * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) * @param string $computed Computed value * @param string $entity Entity of extrafields * @param string $langfile Language file * @return int <=0 if KO, >0 if OK */ - function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list=0, $ishidden=0, $computed='', $entity='', $langfile='') + function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list=-1, $ishidden=0, $computed='', $entity='', $langfile='') { if (empty($attrname)) return -1; if (empty($label)) return -1; @@ -279,7 +279,7 @@ class ExtraFields * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check - * @param int $list Into list view by default + * @param int $list Into list view by default (-1, 0 or 1) * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value @@ -287,7 +287,7 @@ class ExtraFields * @param string $langfile Language file * @return int <=0 if KO, >0 if OK */ - private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list=0, $ishidden=0, $default='', $computed='',$entity='', $langfile='') + private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list=-1, $ishidden=0, $default='', $computed='',$entity='', $langfile='') { global $conf,$user; @@ -747,7 +747,7 @@ class ExtraFields $this->attribute_pos[$tab->name]=$tab->pos; $this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable; $this->attribute_perms[$tab->name]=$tab->perms; - $this->attribute_langfile[$tab->langs]=$tab->langs; + $this->attribute_langfile[$tab->name]=$tab->langs; $this->attribute_list[$tab->name]=$tab->list; $this->attribute_hidden[$tab->name]=$tab->ishidden; $this->attribute_entityid[$tab->name]=$tab->entity; @@ -804,15 +804,15 @@ class ExtraFields * Return HTML string to put an input field into a page * * @param string $key Key of attribute - * @param string $value Preselected value to show (for date type it must be in timestamp format) + * @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, 1, 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,18 +923,21 @@ class ExtraFields } else { $checked=' value="1" '; } - $out=''; + $out=''; } elseif ($type == 'price') { - $out=' '.$langs->getCurrencySymbol($conf->currency); + 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); } elseif ($type == 'double') { - if (!empty($value)) { + 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') { @@ -942,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) { @@ -964,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']); @@ -1129,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') @@ -1137,11 +1140,11 @@ class ExtraFields $out=''; foreach ($param['options'] as $keyopt => $val) { - $out.=''.$val.'
      '; + $out.='/>
      '; } } elseif ($type == 'chkbxlst') @@ -1265,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 ++; @@ -1283,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.
      '; @@ -1302,39 +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') { - $out=''; + // If prefix is 'search_', field is used as a filter, we use a common text field. + $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 * @@ -1683,7 +1688,7 @@ class ExtraFields */ function showSeparator($key) { - $out = '
      '; + $out = ''; return $out; } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 8db18e2c748..389519d7b7f 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -46,527 +46,533 @@ */ class Form { - var $db; - var $error; - var $num; + var $db; + var $error; + var $num; - // Cache arrays - var $cache_types_paiements=array(); - var $cache_conditions_paiements=array(); - var $cache_availability=array(); - var $cache_demand_reason=array(); - var $cache_types_fees=array(); - var $cache_vatrates=array(); + // Cache arrays + var $cache_types_paiements=array(); + var $cache_conditions_paiements=array(); + var $cache_availability=array(); + var $cache_demand_reason=array(); + var $cache_types_fees=array(); + var $cache_vatrates=array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Output key field for an editable field - * - * @param string $text Text of label or key to translate - * @param string $htmlname Name of select field ('edit' prefix will be added) - * @param string $preselected Value to show/edit (not used in this function) - * @param object $object Object - * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field. - * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...) - * @param string $moreparam More param to add on a href URL. - * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS. - * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' ' - * @return string HTML edit field - */ - function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0) - { - global $conf,$langs; + /** + * Output key field for an editable field + * + * @param string $text Text of label or key to translate + * @param string $htmlname Name of select field ('edit' prefix will be added) + * @param string $preselected Value to show/edit (not used in this function) + * @param object $object Object + * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field. + * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...) + * @param string $moreparam More param to add on a href URL. + * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS. + * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' ' + * @return string HTML edit field + */ + function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0) + { + global $conf,$langs; - $ret=''; + $ret=''; - // TODO change for compatibility - if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata)) - { - if (! empty($perm)) - { - $tmp=explode(':',$typeofdata); - $ret.= '
      '; - if ($fieldrequired) $ret.=''; - $ret.= $langs->trans($text); - if ($fieldrequired) $ret.=''; - $ret.= '
      '."\n"; - } - else - { - if ($fieldrequired) $ret.=''; - $ret.= $langs->trans($text); - if ($fieldrequired) $ret.=''; - } - } - else + // TODO change for compatibility + if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata)) { - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
      '; + print ''; print ''; print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; print ''; - $arrayofoperators=array('<'=>'<','>'=>'>'); + $arrayofoperators=array('<'=>'<','>'=>'>'); print $form->selectarray('filter_opouvertureprevue',$arrayofoperators,$filter_opouvertureprevue,1); print ' '; $filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear); @@ -442,7 +484,7 @@ if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) if (! empty($arrayfields['cd.date_ouverture']['checked'])) { print ''; - $arrayofoperators=array('<'=>'<','>'=>'>'); + $arrayofoperators=array('<'=>'<','>'=>'>'); print $form->selectarray('filter_op1',$arrayofoperators,$filter_op1,1); print ' '; $filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year); @@ -461,41 +503,41 @@ if (! empty($arrayfields['cd.date_fin_validite']['checked'])) } if (! empty($arrayfields['cd.date_cloture']['checked'])) { - print ''; - $arrayofoperators=array('<'=>'<','>'=>'>'); - print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1); - print ' '; - $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear); - print $form->select_date($filter_date_cloture,'opcloture',0,0,1,'',1,0,1); - print ''; + $arrayofoperators=array('<'=>'<','>'=>'>'); + print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1); + print ' '; + $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear); + print $form->select_date($filter_date_cloture,'opcloture',0,0,1,'',1,0,1); + print ''; + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } else { // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') echo $extrafields->showInputField($key, $search_array_options['search_options_'.$key], '', '', 'search_'); } - print ''; - print ''; + print ''; - print ''; + print ''; + // Status + print ''; $arrayofstatus=array( - '0'=>$langs->trans("ServiceStatusInitial"), - '4'=>$langs->trans("ServiceStatusRunning"), - '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"), - '4&filter=expired'=>$langs->trans("ServiceStatusLate"), - '5'=>$langs->trans("ServiceStatusClosed") + '0'=>$langs->trans("ServiceStatusInitial"), + '4'=>$langs->trans("ServiceStatusRunning"), + '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"), + '4&filter=expired'=>$langs->trans("ServiceStatusLate"), + '5'=>$langs->trans("ServiceStatusClosed") ); print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone'); print '
      '; + if (! empty($arrayfields['c.ref']['checked'])) + { + print ''; print $contractstatic->getNomUrl(1,16); print ''; + if (! empty($arrayfields['p.description']['checked'])) + { + print ''; if ($obj->pid) { $productstatic->id=$obj->pid; @@ -566,8 +608,8 @@ while ($i < min($num,$limit)) $productstatic->ref=$obj->pref; $productstatic->entity=$obj->pentity; print $productstatic->getNomUrl(1,'',24); - print $obj->label?' - '.dol_trunc($obj->label,16):''; - if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '
      '.dol_nl2br($obj->description); + print $obj->label?' - '.dol_trunc($obj->label,16):''; + if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '
      '.dol_nl2br($obj->description); } else { @@ -575,22 +617,54 @@ while ($i < min($num,$limit)) if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24); } print '
      '; + print $obj->qty; + print ''; + print price($obj->total_ht); + print ''; + print price($obj->total_tva); + print ''; + print price2num($obj->tva_tx).'%'; + print ''; + print price($obj->subprice); + print ''; + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; $companystatic->id=$obj->socid; $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'customer',28); print ''; print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue)):' '); if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) @@ -598,45 +672,45 @@ while ($i < min($num,$limit)) else print '    '; print ''.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').''.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); + if (! empty($arrayfields['cd.date_fin_validite']['checked'])) + { + print ''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) { - $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); + $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 '    '; - print ''.dol_print_date($db->jdate($obj->date_cloture)).''.dol_print_date($db->jdate($obj->date_cloture)).''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; if ($obj->cstatut == 0) // If contract is draft, we say line is also draft { - print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)); + print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)); } else { - print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); + print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); } print ''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; } print '
        '.$langs->trans('Description').''.$langs->trans('Description').''.$langs->trans("SupplierProposalRefFourn").''.$langs->trans("SupplierProposalRefFourn").''.$langs->trans('VAT').''.$langs->trans('VAT').''.$langs->trans('PriceUHT').''.$langs->trans('PriceUHT').''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''.$langs->trans('PriceUTTC').''.$langs->trans('PriceUTTC').''.$langs->trans('Qty').''.$langs->trans('Qty').''.$langs->trans('Unit').''.$langs->trans('Unit').''.$langs->trans('ReductionShort').''.$langs->trans('ReductionShort').'' . $langs->trans('Progress') . '' . $langs->trans('Progress') . ''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('MarginRate').''.$langs->trans('MarkRate').''.$langs->trans('MarginRate').''.$langs->trans('MarkRate').''.$langs->trans('TotalHTShort').''.$langs->trans('TotalHTShort').''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''.$langs->trans('TotalTTCShort').''.$langs->trans('TotalTTCShort').'
      '.$langs->trans('Ref').''.$langs->trans('Description').''.$langs->trans('VATRate').''.$langs->trans('PriceUHT').'
      '.$langs->trans('Ref').''.$langs->trans('Description').''.$langs->trans('VATRate').''.$langs->trans('PriceUHT').''.$langs->trans('PriceUHTCurrency').''.$langs->trans('Qty').''.$langs->trans('Unit').''.$langs->trans('ReductionShort').'
      '.$langs->trans('Qty').''.$langs->trans('Unit').''.$langs->trans('ReductionShort').'
      '; switch($mode) { - case "view": - $out .= $extrafields->showOutputField($key, $value); - break; - case "edit": - $out .= $extrafields->showInputField($key, $value, '', $keyprefix, '', 0, $this->id); - break; + case "view": + $out .= $extrafields->showOutputField($key, $value); + break; + case "edit": + $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id); + break; } $out .= '
      '.$this->attribute_label[$key].'
      '.$this->attribute_label[$key].'
      '; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
      '; - if ($fieldrequired) $ret.=''; - $ret.=$langs->trans($text); - if ($fieldrequired) $ret.=''; - if (! empty($notabletag)) $ret.=' '; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; - if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; - if (! empty($notabletag) && $notabletag == 1) $ret.=' : '; - if (! empty($notabletag) && $notabletag == 3) $ret.=' '; - if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
      '; - } + if (! empty($perm)) + { + $tmp=explode(':',$typeofdata); + $ret.= '
      '; + if ($fieldrequired) $ret.=''; + $ret.= $langs->trans($text); + if ($fieldrequired) $ret.=''; + $ret.= '
      '."\n"; + } + else + { + if ($fieldrequired) $ret.=''; + $ret.= $langs->trans($text); + if ($fieldrequired) $ret.=''; + } + } + else + { + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
      '; + if ($fieldrequired) $ret.=''; + $ret.=$langs->trans($text); + if ($fieldrequired) $ret.=''; + if (! empty($notabletag)) $ret.=' '; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.=''; + if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; + if (! empty($notabletag) && $notabletag == 1) $ret.=' : '; + if (! empty($notabletag) && $notabletag == 3) $ret.=' '; + if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='
      '; + } - return $ret; - } + return $ret; + } - /** - * Output val field for an editable field - * - * @param string $text Text of label (not used in this function) - * @param string $htmlname Name of select field - * @param string $value Value to show/edit - * @param object $object Object - * @param boolean $perm Permission to allow button to edit parameter - * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...) - * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value - * @param object $extObject External object - * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') - * @param string $moreparam More param to add on a href URL - * @param int $notabletag Do no output table tags - * @return string HTML edit field - */ - function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0) - { - global $conf,$langs,$db; + /** + * Output value of a field for an editable field + * + * @param string $text Text of label (not used in this function) + * @param string $htmlname Name of select field + * @param string $value Value to show/edit + * @param object $object Object + * @param boolean $perm Permission to allow button to edit parameter + * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...) + * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value + * @param object $extObject External object + * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') + * @param string $moreparam More param to add on a href URL + * @param int $notabletag Do no output table tags + * @param string $formatfunc Call a specific function to output field + * @return string HTML edit field + */ + function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='') + { + global $conf,$langs,$db; - $ret=''; + $ret=''; - // Check parameters - if (empty($typeofdata)) return 'ErrorBadParameter'; + // Check parameters + if (empty($typeofdata)) return 'ErrorBadParameter'; - // When option to edit inline is activated - if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker - { - $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg); - } - else - { - if (GETPOST('action','aZ09') == 'edit'.$htmlname) - { - $ret.="\n"; - $ret.='
      '; - $ret.=''; - $ret.=''; - $ret.=''; - if (empty($notabletag)) $ret.=''; - if (empty($notabletag)) $ret.=''; + // When option to edit inline is activated + if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker + { + $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg); + } + else + { + if (GETPOST('action','aZ09') == 'edit'.$htmlname) + { + $ret.="\n"; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.=''; + if (empty($notabletag)) $ret.='
      '; - if (preg_match('/^(string|email)/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - $ret.=''; - } - else if (preg_match('/^(numeric|amount)/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - $valuetoshow=price2num($editvalue?$editvalue:$value); - $ret.=''; - } - else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - $cols=$tmp[2]; - $morealt=''; - if (preg_match('/%/',$cols)) - { - $morealt=' style="width: '.$cols.'"'; - $cols=''; - } - $ret.=''; - } - else if ($typeofdata == 'day' || $typeofdata == 'datepicker') - { - $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1); - } - else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') - { - $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1); - } - else if (preg_match('/^select;/',$typeofdata)) - { - $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); - foreach($arraydata as $val) - { - $tmp=explode(':',$val); - $arraylist[$tmp[0]]=$tmp[1]; - } - $ret.=$this->selectarray($htmlname,$arraylist,$value); - } - else if (preg_match('/^ckeditor/',$typeofdata)) - { - $tmp=explode(':',$typeofdata); - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100')); - $ret.=$doleditor->Create(1); - } - if (empty($notabletag)) $ret.='
      '; + if (empty($notabletag)) $ret.=''; - if (empty($notabletag)) $ret.=''; + if (empty($notabletag)) $ret.=''; - if (empty($notabletag)) $ret.='
      '; + if (preg_match('/^(string|email)/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + $ret.=''; + } + else if (preg_match('/^(numeric|amount)/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + $valuetoshow=price2num($editvalue?$editvalue:$value); + $ret.=''; + } + else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + $cols=$tmp[2]; + $morealt=''; + if (preg_match('/%/',$cols)) + { + $morealt=' style="width: '.$cols.'"'; + $cols=''; + } + $ret.=''; + } + else if ($typeofdata == 'day' || $typeofdata == 'datepicker') + { + $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1); + } + else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') + { + $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1); + } + else if (preg_match('/^select;/',$typeofdata)) + { + $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); + foreach($arraydata as $val) + { + $tmp=explode(':',$val); + $arraylist[$tmp[0]]=$tmp[1]; + } + $ret.=$this->selectarray($htmlname,$arraylist,$value); + } + else if (preg_match('/^ckeditor/',$typeofdata)) + { + $tmp=explode(':',$typeofdata); + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100')); + $ret.=$doleditor->Create(1); + } + if (empty($notabletag)) $ret.=''; - //else $ret.='
      '; - $ret.=''; - if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='
      '."\n"; - $ret.=''; - if (empty($notabletag)) $ret.='
      '; + //else $ret.='
      '; + $ret.=''; + if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='
      '."\n"; + $ret.=''; + if (empty($notabletag)) $ret.='
      '."\n"; - $ret.='
      '."\n"; - } - else + if (empty($notabletag)) $ret.=''."\n"; + $ret.=''."\n"; + } + else { if (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1); - elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : ''); - elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value); - elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day'); - elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour'); - else if (preg_match('/^select;/',$typeofdata)) - { - $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); - foreach($arraydata as $val) - { - $tmp=explode(':',$val); - $arraylist[$tmp[0]]=$tmp[1]; - } - $ret.=$arraylist[$value]; - } - else if (preg_match('/^ckeditor/',$typeofdata)) - { - $tmpcontent=dol_htmlentitiesbr($value); - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $firstline=preg_replace('/
      .*/','',$tmpcontent); - $firstline=preg_replace('/[\n\r].*/','',$firstline); - $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':''); - } - $ret.=$tmpcontent; - } - else $ret.=$value; - } - } - return $ret; - } + elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : ''); + elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value); + elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day'); + elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour'); + else if (preg_match('/^select;/',$typeofdata)) + { + $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata)); + foreach($arraydata as $val) + { + $tmp=explode(':',$val); + $arraylist[$tmp[0]]=$tmp[1]; + } + $ret.=$arraylist[$value]; + } + else if (preg_match('/^ckeditor/',$typeofdata)) + { + $tmpcontent=dol_htmlentitiesbr($value); + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $firstline=preg_replace('/
      .*/','',$tmpcontent); + $firstline=preg_replace('/[\n\r].*/','',$firstline); + $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':''); + } + $ret.=$tmpcontent; + } + else $ret.=$value; - /** - * Output edit in place form - * - * @param object $object Object - * @param string $value Value to show/edit - * @param string $htmlname DIV ID (field name) - * @param int $condition Condition to edit - * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx') - * @param string $editvalue When in edit mode, use this value as $value instead of value - * @param object $extObject External object - * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') - * @return string HTML edit in place - */ - private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null) - { - global $conf; + if ($formatfunc && method_exists($object, $formatfunc)) + { + $ret=$object->$formatfunc($ret); + } + } + } + return $ret; + } - $out=''; + /** + * Output edit in place form + * + * @param object $object Object + * @param string $value Value to show/edit + * @param string $htmlname DIV ID (field name) + * @param int $condition Condition to edit + * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx') + * @param string $editvalue When in edit mode, use this value as $value instead of value + * @param object $extObject External object + * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') + * @return string HTML edit in place + */ + private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null) + { + global $conf; - // Check parameters - if ($inputType == 'textarea') $value = dol_nl2br($value); - else if (preg_match('/^numeric/',$inputType)) $value = price($value); - else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day'); + $out=''; - if ($condition) - { - $element = false; - $table_element = false; - $fk_element = false; - $loadmethod = false; - $savemethod = false; - $ext_element = false; - $button_only = false; - $inputOption = ''; + // Check parameters + if ($inputType == 'textarea') $value = dol_nl2br($value); + else if (preg_match('/^numeric/',$inputType)) $value = price($value); + else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day'); - if (is_object($object)) - { - $element = $object->element; - $table_element = $object->table_element; - $fk_element = $object->id; - } + if ($condition) + { + $element = false; + $table_element = false; + $fk_element = false; + $loadmethod = false; + $savemethod = false; + $ext_element = false; + $button_only = false; + $inputOption = ''; - if (is_object($extObject)) - { - $ext_element = $extObject->element; - } + if (is_object($object)) + { + $element = $object->element; + $table_element = $object->table_element; + $fk_element = $object->id; + } - if (preg_match('/^(string|email|numeric)/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; - if (! empty($tmp[1])) $inputOption=$tmp[1]; - if (! empty($tmp[2])) $savemethod=$tmp[2]; + if (is_object($extObject)) + { + $ext_element = $extObject->element; + } + + if (preg_match('/^(string|email|numeric)/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; + if (! empty($tmp[1])) $inputOption=$tmp[1]; + if (! empty($tmp[2])) $savemethod=$tmp[2]; $out.= ''."\n"; - } - else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType))) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; - if (! empty($tmp[1])) $inputOption=$tmp[1]; - if (! empty($tmp[2])) $savemethod=$tmp[2]; + } + else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType))) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; + if (! empty($tmp[1])) $inputOption=$tmp[1]; + if (! empty($tmp[2])) $savemethod=$tmp[2]; - $out.= ''."\n"; // Use for timestamp format - } - else if (preg_match('/^(select|autocomplete)/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; $loadmethod=$tmp[1]; - if (! empty($tmp[2])) $savemethod=$tmp[2]; - if (! empty($tmp[3])) $button_only=true; - } - else if (preg_match('/^textarea/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; - $rows=(empty($tmp[1])?'8':$tmp[1]); - $cols=(empty($tmp[2])?'80':$tmp[2]); - } - else if (preg_match('/^ckeditor/',$inputType)) - { - $tmp=explode(':',$inputType); - $inputType=$tmp[0]; $toolbar=$tmp[1]; - if (! empty($tmp[2])) $width=$tmp[2]; - if (! empty($tmp[3])) $heigth=$tmp[3]; - if (! empty($tmp[4])) $savemethod=$tmp[4]; + $out.= ''."\n"; // Use for timestamp format + } + else if (preg_match('/^(select|autocomplete)/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; $loadmethod=$tmp[1]; + if (! empty($tmp[2])) $savemethod=$tmp[2]; + if (! empty($tmp[3])) $button_only=true; + } + else if (preg_match('/^textarea/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; + $rows=(empty($tmp[1])?'8':$tmp[1]); + $cols=(empty($tmp[2])?'80':$tmp[2]); + } + else if (preg_match('/^ckeditor/',$inputType)) + { + $tmp=explode(':',$inputType); + $inputType=$tmp[0]; $toolbar=$tmp[1]; + if (! empty($tmp[2])) $width=$tmp[2]; + if (! empty($tmp[3])) $heigth=$tmp[3]; + if (! empty($tmp[4])) $savemethod=$tmp[4]; - if (! empty($conf->fckeditor->enabled)) - { - $out.= ''."\n"; - } - else - { - $inputType = 'textarea'; - } - } + if (! empty($conf->fckeditor->enabled)) + { + $out.= ''."\n"; + } + else + { + $inputType = 'textarea'; + } + } - $out.= ''."\n"; - $out.= ''."\n"; - $out.= ''."\n"; - $out.= ''."\n"; - if (! empty($savemethod)) $out.= ''."\n"; - if (! empty($ext_element)) $out.= ''."\n"; - if (! empty($custommsg)) - { - if (is_array($custommsg)) - { - if (!empty($custommsg['success'])) - $out.= ''."\n"; - if (!empty($custommsg['error'])) - $out.= ''."\n"; - } - else - $out.= ''."\n"; - } - if ($inputType == 'textarea') { - $out.= ''."\n"; - $out.= ''."\n"; - } - $out.= ''.$value.''."\n"; - $out.= ''.(! empty($editvalue) ? $editvalue : $value).''."\n"; - } - else - { - $out = $value; - } + $out.= ''."\n"; + $out.= ''."\n"; + $out.= ''."\n"; + $out.= ''."\n"; + if (! empty($savemethod)) $out.= ''."\n"; + if (! empty($ext_element)) $out.= ''."\n"; + if (! empty($custommsg)) + { + if (is_array($custommsg)) + { + if (!empty($custommsg['success'])) + $out.= ''."\n"; + if (!empty($custommsg['error'])) + $out.= ''."\n"; + } + else + $out.= ''."\n"; + } + if ($inputType == 'textarea') { + $out.= ''."\n"; + $out.= ''."\n"; + } + $out.= ''.$value.''."\n"; + $out.= ''.(! empty($editvalue) ? $editvalue : $value).''."\n"; + } + else + { + $out = $value; + } - return $out; - } + return $out; + } - /** - * Show a text and picto with tooltip on text or picto. - * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip - * - * @param string $text Text to show - * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded. - * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2 - * @param int $direction -1=image is before, 0=no image, 1=image is after - * @param string $img Html code for image (use img_xxx() function to get it) - * @param string $extracss Add a CSS style to td tags - * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span - * @param string $incbefore Include code before the text - * @param int $noencodehtmltext Do not encode into html entity the htmltext - * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) - * @return string Code html du tooltip (texte+picto) - * @see Use function textwithpicto if you can. - * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip - */ - function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='') - { - global $conf; + /** + * Show a text and picto with tooltip on text or picto. + * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip + * + * @param string $text Text to show + * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded. + * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2 + * @param int $direction -1=image is before, 0=no image, 1=image is after + * @param string $img Html code for image (use img_xxx() function to get it) + * @param string $extracss Add a CSS style to td tags + * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span + * @param string $incbefore Include code before the text + * @param int $noencodehtmltext Do not encode into html entity the htmltext + * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) + * @return string Code html du tooltip (texte+picto) + * @see Use function textwithpicto if you can. + * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip + */ + function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='') + { + global $conf; - if ($incbefore) $text = $incbefore.$text; - if (! $htmltext) return $text; + if ($incbefore) $text = $incbefore.$text; + if (! $htmltext) return $text; - $tag='td'; - if ($notabs == 2) $tag='div'; - if ($notabs == 3) $tag='span'; - // Sanitize tooltip - $htmltext=str_replace("\\","\\\\",$htmltext); - $htmltext=str_replace("\r","",$htmltext); - $htmltext=str_replace("\n","",$htmltext); + $tag='td'; + if ($notabs == 2) $tag='div'; + if ($notabs == 3) $tag='span'; + // Sanitize tooltip + $htmltext=str_replace("\\","\\\\",$htmltext); + $htmltext=str_replace("\r","",$htmltext); + $htmltext=str_replace("\n","",$htmltext); - $extrastyle=''; - if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; } - if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; } + $extrastyle=''; + if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; } + if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; } - $classfortooltip='classfortooltip'; + $classfortooltip='classfortooltip'; - $s='';$textfordialog=''; + $s='';$textfordialog=''; - $htmltext=str_replace('"',""",$htmltext); - if ($tooltiptrigger != '') - { - $classfortooltip='classfortooltiponclick'; - $textfordialog.=''; - } - if ($tooltipon == 2 || $tooltipon == 3) - { - $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"'; - if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip - else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"'; - } - else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag - if ($tooltipon == 1 || $tooltipon == 3) - { - $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" '; - if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip - else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"'; - } - else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag - if (empty($notabs)) $s.=''; - elseif ($notabs == 2) $s.='
      '; - // Define value if value is before - if ($direction < 0) { - $s.='<'.$tag.$paramfortooltipimg; - if ($tag == 'td') { - $s .= ' valign="top" width="14"'; - } - $s.= '>'.$textfordialog.$img.''; - } - // Use another method to help avoid having a space in value in order to use this value with jquery - // Define label - if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.''; - // Define value if value is after - if ($direction > 0) { - $s.='<'.$tag.$paramfortooltipimg; - if ($tag == 'td') $s .= ' valign="middle" width="14"'; - $s.= '>'.$textfordialog.$img.''; - } - if (empty($notabs)) $s.='
      '; + $htmltext=str_replace('"',""",$htmltext); + if ($tooltiptrigger != '') + { + $classfortooltip='classfortooltiponclick'; + $textfordialog.=''; + } + if ($tooltipon == 2 || $tooltipon == 3) + { + $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"'; + if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip + else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"'; + } + else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag + if ($tooltipon == 1 || $tooltipon == 3) + { + $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" '; + if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip + else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"'; + } + else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag + if (empty($notabs)) $s.=''; + elseif ($notabs == 2) $s.='
      '; + // Define value if value is before + if ($direction < 0) { + $s.='<'.$tag.$paramfortooltipimg; + if ($tag == 'td') { + $s .= ' valign="top" width="14"'; + } + $s.= '>'.$textfordialog.$img.''; + } + // Use another method to help avoid having a space in value in order to use this value with jquery + // Define label + if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.''; + // Define value if value is after + if ($direction > 0) { + $s.='<'.$tag.$paramfortooltipimg; + if ($tag == 'td') $s .= ' valign="middle" width="14"'; + $s.= '>'.$textfordialog.$img.''; + } + if (empty($notabs)) $s.='
      '; elseif ($notabs == 2) $s.='
      '; - return $s; - } + return $s; + } - /** - * Show a text with a picto and a tooltip on picto - * - * @param string $text Text to show - * @param string $htmltext Content of tooltip - * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon - * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath - * @param string $extracss Add a CSS style to td, div or span tag - * @param int $noencodehtmltext Do not encode into html entity the htmltext - * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span - * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) - * @return string HTML code of text, picto, tooltip - */ - function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='') - { - global $conf, $langs; + /** + * Show a text with a picto and a tooltip on picto + * + * @param string $text Text to show + * @param string $htmltext Content of tooltip + * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon + * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath + * @param string $extracss Add a CSS style to td, div or span tag + * @param int $noencodehtmltext Do not encode into html entity the htmltext + * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span + * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key) + * @return string HTML code of text, picto, tooltip + */ + function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='') + { + global $conf, $langs; - $alt = ''; - if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp"); + $alt = ''; + if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp"); - //For backwards compatibility - if ($type == '0') $type = 'info'; - elseif ($type == '1') $type = 'help'; + //For backwards compatibility + if ($type == '0') $type = 'info'; + elseif ($type == '1') $type = 'help'; - // If info or help with no javascript, show only text - if (empty($conf->use_javascript_ajax)) - { - if ($type == 'info' || $type == 'help') return $text; - else - { - $alt = $htmltext; - $htmltext = ''; - } - } + // If info or help with no javascript, show only text + if (empty($conf->use_javascript_ajax)) + { + if ($type == 'info' || $type == 'help') return $text; + else + { + $alt = $htmltext; + $htmltext = ''; + } + } - // If info or help with smartphone, show only text (tooltip can't works) - if (! empty($conf->dol_no_mouse_hover)) - { - if ($type == 'info' || $type == 'help') return $text; - } + // If info or help with smartphone, show only text (tooltip can't works) + if (! empty($conf->dol_no_mouse_hover)) + { + if ($type == 'info' || $type == 'help') return $text; + } - if ($type == 'info') $img = img_help(0, $alt); - elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt); - elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar'); - elseif ($type == 'admin') $img = img_picto($alt, 'star'); - elseif ($type == 'warning') $img = img_warning($alt); + if ($type == 'info') $img = img_help(0, $alt); + elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt); + elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar'); + elseif ($type == 'admin') $img = img_picto($alt, 'star'); + elseif ($type == 'warning') $img = img_warning($alt); else $img = img_picto($alt, $type); - return $this->textwithtooltip($text, $htmltext, ($tooltiptrigger?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger); - } + return $this->textwithtooltip($text, $htmltext, ($tooltiptrigger?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger); + } - /** - * Generate select HTML to choose massaction - * - * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default. - * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action. - * @param int $alwaysvisible 1=select button always visible - * @return string Select list - */ - function selectMassAction($selected, $arrayofaction, $alwaysvisible=0) - { - global $conf,$langs,$hookmanager; + /** + * Generate select HTML to choose massaction + * + * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default. + * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action. + * @param int $alwaysvisible 1=select button always visible + * @return string Select list + */ + function selectMassAction($selected, $arrayofaction, $alwaysvisible=0) + { + global $conf,$langs,$hookmanager; - if (count($arrayofaction) == 0) return; + if (count($arrayofaction) == 0) return; - $disabled=0; - $ret='
      '; - $ret.=''; - // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks. - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - $ret.=''; - foreach($arrayofaction as $code => $label) - { - $ret.=''; - } - } - $ret.=$hookmanager->resPrint; + // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks. + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) + { + $ret.=''; + foreach($arrayofaction as $code => $label) + { + $ret.=''; + } + } + $ret.=$hookmanager->resPrint; - $ret.=''; - // Warning: if you set submit button to disabled, post using 'Enter' will no more work. - $ret.=''; - $ret.='
      '; + $ret.=''; + // Warning: if you set submit button to disabled, post using 'Enter' will no more work. + $ret.=''; + $ret.='
      '; - if (! empty($conf->use_javascript_ajax)) - { - $ret.=' + if (! empty($conf->use_javascript_ajax)) + { + $ret.=' '; - } + } - return $ret; - } + return $ret; + } - /** - * Return combo list of activated countries, into language of user - * - * @param string $selected Id or Code or Label of preselected country - * @param string $htmlname Name of html select object - * @param string $htmloption Options html on select object - * @param integer $maxlength Max length for labels (0=no limit) - * @param string $morecss More css class - * @param string $usecodeaskey 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key - * @return string HTML string with select - */ - function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300',$usecodeaskey='') - { - global $conf,$langs; + /** + * Return combo list of activated countries, into language of user + * + * @param string $selected Id or Code or Label of preselected country + * @param string $htmlname Name of html select object + * @param string $htmloption Options html on select object + * @param integer $maxlength Max length for labels (0=no limit) + * @param string $morecss More css class + * @param string $usecodeaskey 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key + * @return string HTML string with select + */ + function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300',$usecodeaskey='') + { + global $conf,$langs; - $langs->load("dict"); + $langs->load("dict"); - $out=''; - $countryArray=array(); + $out=''; + $countryArray=array(); $favorite=array(); - $label=array(); + $label=array(); $atleastonefavorite=0; - $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_country"; - $sql.= " WHERE active > 0"; - //$sql.= " ORDER BY code ASC"; + $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_country"; + $sql.= " WHERE active > 0"; + //$sql.= " ORDER BY code ASC"; - dol_syslog(get_class($this)."::select_country", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $out.= ''; + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + $foundselected=false; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $countryArray[$i]['rowid'] = $obj->rowid; - $countryArray[$i]['code_iso'] = $obj->code_iso; - $countryArray[$i]['code_iso3'] = $obj->code_iso3; - $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:'')); - $countryArray[$i]['favorite'] = $obj->favorite; - $favorite[$i] = $obj->favorite; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $countryArray[$i]['rowid'] = $obj->rowid; + $countryArray[$i]['code_iso'] = $obj->code_iso; + $countryArray[$i]['code_iso3'] = $obj->code_iso3; + $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:'')); + $countryArray[$i]['favorite'] = $obj->favorite; + $favorite[$i] = $obj->favorite; $label[$i] = dol_string_unaccent($countryArray[$i]['label']); - $i++; - } + $i++; + } - array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray); + array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray); - foreach ($countryArray as $row) - { - if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++; + foreach ($countryArray as $row) + { + if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++; if (empty($row['favorite']) && $atleastonefavorite) { $atleastonefavorite=0; $out.= ''; } - if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) ) - { - $foundselected=true; - $out.= ''; - } - } - $out.= ''; - } - else + $foundselected=true; + $out.= ''; + } + } + $out.= ''; + } + else { - dol_print_error($this->db); - } + dol_print_error($this->db); + } - // Make select dynamic - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out .= ajax_combobox('select'.$htmlname); + // Make select dynamic + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $out .= ajax_combobox('select'.$htmlname); - return $out; - } + return $out; + } /** - * Return select list of incoterms - * - * @param string $selected Id or Code of preselected incoterm - * @param string $location_incoterms Value of input location - * @param string $page Defined the form action - * @param string $htmlname Name of html select object - * @param string $htmloption Options html on select object - * @param int $forcecombo Force to use standard combo box (no ajax use) - * @param array $events Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return string HTML string with select and input - */ - function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array()) - { - global $conf,$langs; + * Return select list of incoterms + * + * @param string $selected Id or Code of preselected incoterm + * @param string $location_incoterms Value of input location + * @param string $page Defined the form action + * @param string $htmlname Name of html select object + * @param string $htmloption Options html on select object + * @param int $forcecombo Force to use standard combo box (no ajax use) + * @param array $events Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @return string HTML string with select and input + */ + function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array()) + { + global $conf,$langs; - $langs->load("dict"); + $langs->load("dict"); - $out=''; - $incotermArray=array(); + $out=''; + $incotermArray=array(); - $sql = "SELECT rowid, code"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms"; - $sql.= " WHERE active > 0"; - $sql.= " ORDER BY code ASC"; + $sql = "SELECT rowid, code"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms"; + $sql.= " WHERE active > 0"; + $sql.= " ORDER BY code ASC"; - dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($conf->use_javascript_ajax && ! $forcecombo) + dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($conf->use_javascript_ajax && ! $forcecombo) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname, $events); @@ -749,701 +755,707 @@ class Form if (!empty($page)) { $out .= '
      '; - $out .= ''; - $out .= ''; + $out .= ''; + $out .= ''; } - $out.= ''; $out.= ''; - $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - $foundselected=false; + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + $foundselected=false; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $incotermArray[$i]['rowid'] = $obj->rowid; - $incotermArray[$i]['code'] = $obj->code; - $i++; - } + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $incotermArray[$i]['rowid'] = $obj->rowid; + $incotermArray[$i]['code'] = $obj->code; + $i++; + } - foreach ($incotermArray as $row) - { - if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) - { - $out.= ''; - } - } - $out.= ''; + } + } + $out.= ''; $out .= ''; if (!empty($page)) { - $out .= '
      '; + $out .= ''; } - } - else + } + else { - dol_print_error($this->db); - } + dol_print_error($this->db); + } - return $out; - } + return $out; + } - /** - * Return list of types of lines (product or service) - * Example: 0=product, 1=service, 9=other (for external module) - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select) - * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service') - * @return void - */ - function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0) - { - global $db,$langs,$user,$conf; + /** + * Return list of types of lines (product or service) + * Example: 0=product, 1=service, 9=other (for external module) + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select) + * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service') + * @return void + */ + function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0) + { + global $db,$langs,$user,$conf; - // If product & services are enabled or both disabled. - if ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled)) - || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) ) - { - if (empty($hidetext)) print $langs->trans("Type").': '; - print ''; + if ($showempty) + { + print ''; + } - print ''; + } - foreach($this->cache_types_fees as $key => $value) - { - print ''; - } + foreach($this->cache_types_fees as $key => $value) + { + print ''; + } - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } + print ''; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } - /** - * Return HTML code to select a company. - * - * @param int $selected Preselected products - * @param string $htmlname Name of HTML select field (must be unique in page) - * @param int $filter Filter on thirdparty - * @param int $limit Limit on number of returned lines - * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $forcecombo Force to use combo box - * @return string Return select box for thirdparty. + /** + * Return HTML code to select a company. + * + * @param int $selected Preselected products + * @param string $htmlname Name of HTML select field (must be unique in page) + * @param int $filter Filter on thirdparty + * @param int $limit Limit on number of returned lines + * @param array $ajaxoptions Options for ajax_autocompleter + * @param int $forcecombo Force to use combo box + * @return string Return select box for thirdparty. * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0) - */ - function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0) - { + */ + function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0) + { return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit); - } + } - /** - * Output html form to select a third party - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)') - * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box - * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param int $limit Maximum number of elements - * @param string $morecss Add more css styles to the SELECT component - * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container + /** + * Output html form to select a third party + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in form + * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)') + * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') + * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int $forcecombo Force to use combo box + * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @param int $limit Maximum number of elements + * @param string $morecss Add more css styles to the SELECT component + * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container * @param string $selected_input_value Value of preselected input text (for use with ajax) - * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) - * @param array $ajaxoptions Options for ajax_autocompleter - * @return string HTML string with select box for thirdparty. - */ - function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array()) - { - global $conf,$user,$langs; + * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) + * @param array $ajaxoptions Options for ajax_autocompleter + * @return string HTML string with select box for thirdparty. + */ + function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array()) + { + global $conf,$user,$langs; - $out=''; + $out=''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo) - { - // No immediate load of all database - $placeholder=''; - if ($selected && empty($selected_input_value)) - { - require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $societetmp = new Societe($this->db); - $societetmp->fetch($selected); - $selected_input_value=$societetmp->name; - unset($societetmp); - } - // mode 1 - $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:''); - $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo) + { + // No immediate load of all database + $placeholder=''; + if ($selected && empty($selected_input_value)) + { + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $societetmp = new Societe($this->db); + $societetmp->fetch($selected); + $selected_input_value=$societetmp->name; + unset($societetmp); + } + // mode 1 + $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:''); + $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); $out.=''; - if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; - else if ($hidelabel > 1) { - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; - else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; - if ($hidelabel == 2) { - $out.= img_picto($langs->trans("Search"), 'search'); - } - } - $out.= 'global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; - if ($hidelabel == 3) { - $out.= img_picto($langs->trans("Search"), 'search'); - } - } - else - { - // Immediate load of all database - $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam); - } + if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; + else if ($hidelabel > 1) { + if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; + else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; + if ($hidelabel == 2) { + $out.= img_picto($langs->trans("Search"), 'search'); + } + } + $out.= 'global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + if ($hidelabel == 3) { + $out.= img_picto($langs->trans("Search"), 'search'); + } + } + else + { + // Immediate load of all database + $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam); + } - return $out; - } + return $out; + } - /** - * Output html form to select a third party. - * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company. - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)') - * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param string $filterkey Filter on key value - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $limit Limit number of answers - * @param string $morecss Add more css styles to the SELECT component - * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container - * @return string HTML string with - */ - function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='') - { - global $conf,$user,$langs; + /** + * Output html form to select a third party. + * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company. + * + * @param string $selected Preselected type + * @param string $htmlname Name of field in form + * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)') + * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') + * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @param string $filterkey Filter on key value + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $limit Limit number of answers + * @param string $morecss Add more css styles to the SELECT component + * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container + * @return string HTML string with + */ + function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='') + { + global $conf,$user,$langs; - $out=''; - $num=0; - $outarray=array(); + $out=''; + $num=0; + $outarray=array(); - // On recherche les societes - $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s"; - if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE s.entity IN (".getEntity('societe').")"; - if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id; - if ($filter) $sql.= " AND (".$filter.")"; - if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0"; - // Add criteria - if ($filterkey && $filterkey != '') - { + // On recherche les societes + $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur"; + $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s"; + if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE s.entity IN (".getEntity('societe').")"; + if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id; + if ($filter) $sql.= " AND (".$filter.")"; + if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0"; + // Add criteria + if ($filterkey && $filterkey != '') + { $sql.=" AND ("; - $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on - // For natural search - $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; - foreach ($scrit as $crit) { - if ($i > 0) $sql.=" AND "; - $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')"; - $i++; - } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) - { - $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'"; - } - $sql.=")"; - } - $sql.=$this->db->order("nom","ASC"); + $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on + // For natural search + $scrit = explode(' ', $filterkey); + $i=0; + if (count($scrit) > 1) $sql.="("; + foreach ($scrit as $crit) { + if ($i > 0) $sql.=" AND "; + $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')"; + $i++; + } + if (count($scrit) > 1) $sql.=")"; + if (! empty($conf->barcode->enabled)) + { + $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'"; + } + $sql.=")"; + } + $sql.=$this->db->order("nom","ASC"); $sql.=$this->db->plimit($limit, 0); // Build output string - dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($conf->use_javascript_ajax && ! $forcecombo) - { + dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($conf->use_javascript_ajax && ! $forcecombo) + { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT); - $out.= $comboenhancement; - } + $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT); + $out.= $comboenhancement; + } - // Construct $out and $outarray - $out.= ''."\n"; - $textifempty=''; - // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. - //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; - if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) - { - if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); - else $textifempty.=$langs->trans("All"); - } - if ($showempty) $out.= ''."\n"; + $textifempty=''; + // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. + //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; + if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) + { + if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); + else $textifempty.=$langs->trans("All"); + } + if ($showempty) $out.= ''."\n"; $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $label=''; - if ($conf->global->SOCIETE_ADD_REF_IN_LIST) { - if (($obj->client) && (!empty($obj->code_client))) { - $label = $obj->code_client. ' - '; - } - if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) { - $label .= $obj->code_fournisseur. ' - '; - } - $label.=' '.$obj->name; - } - else - { - $label=$obj->name; - } + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $label=''; + if ($conf->global->SOCIETE_ADD_REF_IN_LIST) { + if (($obj->client) && (!empty($obj->code_client))) { + $label = $obj->code_client. ' - '; + } + if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) { + $label .= $obj->code_fournisseur. ' - '; + } + $label.=' '.$obj->name; + } + else + { + $label=$obj->name; + } if(!empty($obj->name_alias)) { $label.=' ('.$obj->name_alias.')'; } - if ($showtype) - { - if ($obj->client || $obj->fournisseur) $label.=' ('; - if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer"); - if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect"); - if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier"); - if ($obj->client || $obj->fournisseur) $label.=')'; - } - if ($selected > 0 && $selected == $obj->rowid) - { - $out.= ''; - } - else + if ($showtype) { - $out.= ''; - } - - array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label)); - - $i++; - if (($i % 10) == 0) $out.="\n"; - } - } - $out.= ''."\n"; - } - else - { - dol_print_error($this->db); - } - - $this->result=array('nbofthirdparties'=>$num); - - if ($outputmode) return $outarray; - return $out; - } - - - /** - * Return HTML combo list of absolute discounts - * - * @param string $selected Id remise fixe pre-selectionnee - * @param string $htmlname Nom champ formulaire - * @param string $filter Criteres optionnels de filtre - * @param int $socid Id of thirdparty - * @param int $maxvalue Max value for lines that can be selected - * @return int Return number of qualifed lines in list - */ - function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0) - { - global $langs,$conf; - - // On recherche les remises - $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 re.fk_soc = ".(int) $socid; - $sql.= " AND re.entity = " . $conf->entity; - if ($filter) $sql.= " AND ".$filter; - $sql.= " ORDER BY re.description ASC"; - - dol_syslog(get_class($this)."::select_remises", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - print ''; - return $qualifiedlines; - } - else - { - dol_print_error($this->db); - return -1; - } - } - - /** - * Return list of all contacts (for a third party or all) - * - * @param int $socid Id ot third party or 0 for all - * @param string $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int $showempty 0=no empty value, 1=add an empty value - * @param string $exclude List of contacts id to exclude - * @param string $limitto Disable answers that are not id in this array list - * @param integer $showfunction Add function into label - * @param string $moreclass Add more class to class style - * @param integer $showsoc Add company into label - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param bool $options_only Return options only (for ajax treatment) - * @return int <0 if KO, Nb of contact in list if OK - * @deprected You can use selectcontacts directly (warning order of param was changed) - */ - function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false) - { - print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events); - return $this->num; - } - - /** - * Return HTML code of the SELECT of list of all contacts (for a third party or all). - * This also set the number of contacts found into $this->num - * - * @param int $socid Id ot third party or 0 for all - * @param string $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit) - * @param string $exclude List of contacts id to exclude - * @param string $limitto Disable answers that are not id in this array list - * @param integer $showfunction Add function into label - * @param string $moreclass Add more class to class style - * @param bool $options_only Return options only (for ajax treatment) - * @param integer $showsoc Add company into label - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return int <0 if KO, Nb of contact in list if OK - */ - function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array()) - { - global $conf,$langs; - - $langs->load('companies'); - - $out=''; - - // On recherche les societes - $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste"; - if ($showsoc > 0) $sql.= " , s.nom as company"; - $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp"; - if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc"; - $sql.= " WHERE sp.entity IN (".getEntity('societe').")"; - if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid; - if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0"; - $sql.= " ORDER BY sp.lastname ASC"; - - dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - - if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT); - $out.= $comboenhancement; - } - - if ($htmlname != 'none' || $options_only) $out.= ''."\n"; + } + else + { + dol_print_error($this->db); + } + + $this->result=array('nbofthirdparties'=>$num); + + if ($outputmode) return $outarray; + return $out; + } + + + /** + * Return HTML combo list of absolute discounts + * + * @param string $selected Id remise fixe pre-selectionnee + * @param string $htmlname Nom champ formulaire + * @param string $filter Criteres optionnels de filtre + * @param int $socid Id of thirdparty + * @param int $maxvalue Max value for lines that can be selected + * @return int Return number of qualifed lines in list + */ + function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0) + { + global $langs,$conf; + + // On recherche les remises + $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 re.fk_soc = ".(int) $socid; + $sql.= " AND re.entity = " . $conf->entity; + if ($filter) $sql.= " AND ".$filter; + $sql.= " ORDER BY re.description ASC"; + + dol_syslog(get_class($this)."::select_remises", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + print ''; - } + print ''; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + $desc=dol_trunc($obj->description,40); + if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc); + if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc); + if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc); - $this->num = $num; - return $out; - } - else - { - dol_print_error($this->db); - return -1; - } - } + $selectstring=''; + if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected'; - /** - * Return select list of users - * - * @param string $selected Id user preselected - * @param string $htmlname Field name in form - * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue - * @param array $exclude Array list of users id to exclude - * @param int $disabled If select list must be disabled - * @param array $include Array list of users id to include - * @param int $enableonly Array list of users id to be enabled. All other must be disabled - * @param int $force_entity 0 or Id of environment to force - * @return void - * @deprecated Use select_dolusers instead - * @see select_dolusers() - */ - function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity=0) - { - print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity); - } + $disabled=''; + if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) + { + $qualifiedlines--; + $disabled=' disabled'; + } - /** - * Return select list of users - * - * @param string $selected User id or user object of user preselected. If -1, we use id of current user. - * @param string $htmlname Field name in form - * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list - * @param array $exclude Array list of users id to exclude - * @param int $disabled If select list must be disabled - * @param array|string $include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me - * @param array $enableonly Array list of users id to be enabled. If defined, it means that other must be disabled - * @param int $force_entity 0 or Id of environment to force - * @param int $maxlength Maximum length of string into list (0=no limit) - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param string $morefilter Add more filters into sql request - * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list - * @param string $enableonlytext If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty. - * @param string $morecss More css - * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on). - * @return string HTML select string - * @see select_dolgroups - */ - function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0) - { - global $conf,$user,$langs; + if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) + { + $tmpfac = new Facture($this->db); + if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref; + } - // If no preselected user defined, we take current user - if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id; + print ''; + $i++; + } + } + print ''; + return $qualifiedlines; + } + else + { + dol_print_error($this->db); + return -1; + } + } - $excludeUsers=null; - $includeUsers=null; + /** + * Return list of all contacts (for a third party or all) + * + * @param int $socid Id ot third party or 0 for all + * @param string $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML field ('none' for a not editable field) + * @param int $showempty 0=no empty value, 1=add an empty value + * @param string $exclude List of contacts id to exclude + * @param string $limitto Disable answers that are not id in this array list + * @param integer $showfunction Add function into label + * @param string $moreclass Add more class to class style + * @param integer $showsoc Add company into label + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @param bool $options_only Return options only (for ajax treatment) + * @return int <0 if KO, Nb of contact in list if OK + * @deprected You can use selectcontacts directly (warning order of param was changed) + */ + function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false) + { + print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events); + return $this->num; + } - // Permettre l'exclusion d'utilisateurs - if (is_array($exclude)) $excludeUsers = implode(",",$exclude); - // Permettre l'inclusion d'utilisateurs - if (is_array($include)) $includeUsers = implode(",",$include); + /** + * Return HTML code of the SELECT of list of all contacts (for a third party or all). + * This also set the number of contacts found into $this->num + * + * @param int $socid Id ot third party or 0 for all + * @param string $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML field ('none' for a not editable field) + * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit) + * @param string $exclude List of contacts id to exclude + * @param string $limitto Disable answers that are not id in this array list + * @param integer $showfunction Add function into label + * @param string $moreclass Add more class to class style + * @param bool $options_only Return options only (for ajax treatment) + * @param integer $showsoc Add company into label + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @return int <0 if KO, Nb of contact in list if OK + */ + function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array()) + { + global $conf,$langs; + + $langs->load('companies'); + + $out=''; + + // On recherche les societes + $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste"; + if ($showsoc > 0) $sql.= " , s.nom as company"; + $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp"; + if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc"; + $sql.= " WHERE sp.entity IN (".getEntity('societe').")"; + if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid; + if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0"; + $sql.= " ORDER BY sp.lastname ASC"; + + dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + + if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT); + $out.= $comboenhancement; + } + + if ($htmlname != 'none' || $options_only) $out.= ''; + } + + $this->num = $num; + return $out; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** + * Return select list of users + * + * @param string $selected Id user preselected + * @param string $htmlname Field name in form + * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue + * @param array $exclude Array list of users id to exclude + * @param int $disabled If select list must be disabled + * @param array $include Array list of users id to include + * @param int $enableonly Array list of users id to be enabled. All other must be disabled + * @param int $force_entity 0 or Id of environment to force + * @return void + * @deprecated Use select_dolusers instead + * @see select_dolusers() + */ + function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity=0) + { + print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity); + } + + /** + * Return select list of users + * + * @param string $selected User id or user object of user preselected. If -1, we use id of current user. + * @param string $htmlname Field name in form + * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list + * @param array $exclude Array list of users id to exclude + * @param int $disabled If select list must be disabled + * @param array|string $include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me + * @param array $enableonly Array list of users id to be enabled. If defined, it means that other must be disabled + * @param int $force_entity 0 or Id of environment to force + * @param int $maxlength Maximum length of string into list (0=no limit) + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param string $morefilter Add more filters into sql request + * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list + * @param string $enableonlytext If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty. + * @param string $morecss More css + * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on). + * @return string HTML select string + * @see select_dolgroups + */ + function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0) + { + global $conf,$user,$langs; + + // If no preselected user defined, we take current user + if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id; + + $excludeUsers=null; + $includeUsers=null; + + // Permettre l'exclusion d'utilisateurs + if (is_array($exclude)) $excludeUsers = implode(",",$exclude); + // Permettre l'inclusion d'utilisateurs + if (is_array($include)) $includeUsers = implode(",",$include); else if ($include == 'hierarchy') { // Build list includeUsers to have only hierarchy @@ -1451,194 +1463,194 @@ class Form } else if ($include == 'hierarchyme') { - // Build list includeUsers to have only hierarchy and current user - $includeUsers = implode(",",$user->getAllChildIds(1)); + // Build list includeUsers to have only hierarchy and current user + $includeUsers = implode(",",$user->getAllChildIds(1)); } - $out=''; + $out=''; - // On recherche les utilisateurs - $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; - if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - $sql.= ", e.label"; - } - $sql.= " FROM ".MAIN_DB_PREFIX ."user as u"; - if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity"; - if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")"; - else $sql.= " WHERE u.entity IS NOT NULL"; - } - else - { - if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug"; - $sql.= " ON ug.fk_user = u.rowid"; - $sql.= " WHERE ug.entity = ".$conf->entity; - } - else - { - $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; - } - } - if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id; - if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")"; - if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")"; - if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0"; - if (! empty($morefilter)) $sql.=" ".$morefilter; + // On recherche les utilisateurs + $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; + if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) + { + $sql.= ", e.label"; + } + $sql.= " FROM ".MAIN_DB_PREFIX ."user as u"; + if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity"; + if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")"; + else $sql.= " WHERE u.entity IS NOT NULL"; + } + else + { + if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql.= " ON ug.fk_user = u.rowid"; + $sql.= " WHERE ug.entity = ".$conf->entity; + } + else + { + $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; + } + } + if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id; + if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")"; + if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")"; + if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0"; + if (! empty($morefilter)) $sql.=" ".$morefilter; - if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){ - $sql.= " ORDER BY u.firstname ASC"; - }else{ - $sql.= " ORDER BY u.lastname ASC"; - } + if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){ + $sql.= " ORDER BY u.firstname ASC"; + }else{ + $sql.= " ORDER BY u.lastname ASC"; + } - dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - if ($num) - { - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox($htmlname); - $out.=$comboenhancement; - } + dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox($htmlname); + $out.=$comboenhancement; + } - // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined - $out.= ''; + if ($show_empty) $out.= ''."\n"; if ($show_every) $out.= ''."\n"; - $userstatic=new User($this->db); + $userstatic=new User($this->db); - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - $userstatic->id=$obj->rowid; - $userstatic->lastname=$obj->lastname; - $userstatic->firstname=$obj->firstname; + $userstatic->id=$obj->rowid; + $userstatic->lastname=$obj->lastname; + $userstatic->firstname=$obj->firstname; - $disableline=''; - if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1'); + $disableline=''; + if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1'); - if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid)) - { - $out.= ''; + $out.= ''; - $i++; - } - } - else - { - $out.= ''; - } - else - { - dol_print_error($this->db); - } + $i++; + } + } + else + { + $out.= ''; + } + else + { + dol_print_error($this->db); + } - return $out; - } + return $out; + } - /** - * Return select list of users. Selected users are stored into session. - * List of users are provided into $_SESSION['assignedtouser']. - * - * @param string $action Value for $action - * @param string $htmlname Field name in form - * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue - * @param array $exclude Array list of users id to exclude - * @param int $disabled If select list must be disabled - * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users - * @param array $enableonly Array list of users id to be enabled. All other must be disabled - * @param int $force_entity 0 or Id of environment to force - * @param int $maxlength Maximum length of string into list (0=no limit) - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param string $morefilter Add more filters into sql request - * @return string HTML select string - * @see select_dolgroups - */ - function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='') - { - global $conf,$user,$langs; + /** + * Return select list of users. Selected users are stored into session. + * List of users are provided into $_SESSION['assignedtouser']. + * + * @param string $action Value for $action + * @param string $htmlname Field name in form + * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue + * @param array $exclude Array list of users id to exclude + * @param int $disabled If select list must be disabled + * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users + * @param array $enableonly Array list of users id to be enabled. All other must be disabled + * @param int $force_entity 0 or Id of environment to force + * @param int $maxlength Maximum length of string into list (0=no limit) + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param string $morefilter Add more filters into sql request + * @return string HTML select string + * @see select_dolgroups + */ + function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='') + { + global $conf,$user,$langs; - $userstatic=new User($this->db); + $userstatic=new User($this->db); $out=''; - // Method with no ajax - //$out.='
      '; - if ($action == 'view') - { + // Method with no ajax + //$out.=''; + if ($action == 'view') + { $out.=''; - } + } else { $out.=''; @@ -1671,60 +1683,60 @@ class Form if ($nbassignetouser) $out.='
      '; //$out.=''; - return $out; - } + return $out; + } - /** - * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list - * - * @param int $selected Preselected products - * @param string $htmlname Name of HTML select field (must be unique in page) - * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param int $limit Limit on number of returned lines - * @param int $price_level Level of price to show - * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell - * @param int $finished 2=all, 1=finished, 0=raw material - * @param string $selected_input_value Value of preselected input text (for use with ajax) - * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) - * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. - * @param int $forcecombo Force to use combo box - * @param string $morecss Add more css on select - * @param int $hidepriceinlabel 1=Hide prices in label - * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used - * 'warehouseopen' = select products from open warehouses, + /** + * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list + * + * @param int $selected Preselected products + * @param string $htmlname Name of HTML select field (must be unique in page) + * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param int $limit Limit on number of returned lines + * @param int $price_level Level of price to show + * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell + * @param int $finished 2=all, 1=finished, 0=raw material + * @param string $selected_input_value Value of preselected input text (for use with ajax) + * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) + * @param array $ajaxoptions Options for ajax_autocompleter + * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param int $hidepriceinlabel 1=Hide prices in label + * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used + * 'warehouseopen' = select products from open warehouses, * 'warehouseclosed' = select products from closed warehouses, * 'warehouseinternal' = select products from warehouses for internal correct/transfer only - * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) - * @return void - */ - function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array()) - { - global $langs,$conf; + * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) + * @return void + */ + function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array()) + { + global $langs,$conf; - $price_level = (! empty($price_level) ? $price_level : 0); + $price_level = (! empty($price_level) ? $price_level : 0); - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) - { - $placeholder=''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + $placeholder=''; - if ($selected && empty($selected_input_value)) - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $producttmpselect = new Product($this->db); - $producttmpselect->fetch($selected); - $selected_input_value=$producttmpselect->ref; - unset($producttmpselect); - } - // mode=1 means customers products - $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus; - //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $urloption.='&socid='.$socid; - } - print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + if ($selected && empty($selected_input_value)) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $producttmpselect = new Product($this->db); + $producttmpselect->fetch($selected); + $selected_input_value=$producttmpselect->ref; + unset($producttmpselect); + } + // mode=1 means customers products + $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus; + //Price by customer + if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $urloption.='&socid='.$socid; + } + print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); if (!empty($conf->variants->enabled)) { ?> @@ -1798,92 +1810,92 @@ class Form }); trans("RefOrLabel").' : '; - else if ($hidelabel > 1) { - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; - else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; - if ($hidelabel == 2) { - print img_picto($langs->trans("Search"), 'search'); - } - } - print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; - if ($hidelabel == 3) { - print img_picto($langs->trans("Search"), 'search'); - } - } - else + } + if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; + else if ($hidelabel > 1) { + if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; + else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; + if ($hidelabel == 2) { + print img_picto($langs->trans("Search"), 'search'); + } + } + print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + if ($hidelabel == 3) { + print img_picto($langs->trans("Search"), 'search'); + } + } + else { - print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus); - } - } + print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus); + } + } - /** - * Return list of products for a customer - * - * @param int $selected Preselected product - * @param string $htmlname Name of select html - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param int $limit Limit on number of returned lines - * @param int $price_level Level of price to show - * @param string $filterkey Filter on product - * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell - * @param int $finished Filter on finished field: 2=No filter - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. - * @param int $forcecombo Force to use combo box - * @param string $morecss Add more css on select - * @param int $hidepriceinlabel 1=Hide prices in label - * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used - * 'warehouseopen' = select products from open warehouses, + /** + * Return list of products for a customer + * + * @param int $selected Preselected product + * @param string $htmlname Name of select html + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param int $limit Limit on number of returned lines + * @param int $price_level Level of price to show + * @param string $filterkey Filter on product + * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell + * @param int $finished Filter on finished field: 2=No filter + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param int $hidepriceinlabel 1=Hide prices in label + * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used + * 'warehouseopen' = select products from open warehouses, * 'warehouseclosed' = select products from closed warehouses, * 'warehouseinternal' = select products from warehouses for internal correct/transfer only - * @return array Array of keys for json - */ - function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='') - { - global $langs,$conf,$user,$db; + * @return array Array of keys for json + */ + function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='') + { + global $langs,$conf,$user,$db; - $out=''; - $outarray=array(); + $out=''; + $outarray=array(); - $warehouseStatusArray = array(); - if (! empty($warehouseStatus)) - { - require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; - if (preg_match('/warehouseclosed/', $warehouseStatus)) - { - $warehouseStatusArray[] = Entrepot::STATUS_CLOSED; - } - if (preg_match('/warehouseopen/', $warehouseStatus)) - { - $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL; - } - if (preg_match('/warehouseinternal/', $warehouseStatus)) - { - $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL; - } - } + $warehouseStatusArray = array(); + if (! empty($warehouseStatus)) + { + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; + if (preg_match('/warehouseclosed/', $warehouseStatus)) + { + $warehouseStatusArray[] = Entrepot::STATUS_CLOSED; + } + if (preg_match('/warehouseopen/', $warehouseStatus)) + { + $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL; + } + if (preg_match('/warehouseinternal/', $warehouseStatus)) + { + $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL; + } + } - $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; - (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock"; + $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; + (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock"; - $sql = "SELECT "; - $sql.= $selectFields . $selectFieldsGrouped; - //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,'; - $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; - $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; - } + $sql = "SELECT "; + $sql.= $selectFields . $selectFieldsGrouped; + //Price by customer + if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,'; + $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx'; + $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx"; + } - // Multilang : we add translation - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $sql.= ", pl.label as label_translated"; - $selectFields.= ", label_translated"; - } + // Multilang : we add translation + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $sql.= ", pl.label as label_translated"; + $selectFields.= ", label_translated"; + } // Price by quantity if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { @@ -1895,115 +1907,115 @@ class Form if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level; $sql.= " ORDER BY date_price"; $sql.= " DESC LIMIT 1) as price_by_qty"; - $selectFields.= ", price_rowid, price_by_qty"; + $selectFields.= ", price_rowid, price_by_qty"; + } + $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + if (count($warehouseStatusArray)) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid"; } - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - if (count($warehouseStatusArray)) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid"; - } - //Price by customer - if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { - $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; - } - // Multilang : we add translation - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'"; - } + //Price by customer + if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) { + $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid"; + } + // Multilang : we add translation + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'"; + } - if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { - $sql .= " LEFT JOIN llx_product_attribute_combination pac ON pac.fk_product_child = p.rowid"; - } + if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { + $sql .= " LEFT JOIN llx_product_attribute_combination pac ON pac.fk_product_child = p.rowid"; + } - $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; - if (count($warehouseStatusArray)) - { - $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))'; - } + $sql.= ' WHERE p.entity IN ('.getEntity('product').')'; + if (count($warehouseStatusArray)) + { + $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))'; + } - if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { - $sql .= " AND pac.rowid IS NULL"; - } + if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) { + $sql .= " AND pac.rowid IS NULL"; + } - if ($finished == 0) - { - $sql.= " AND p.finished = ".$finished; - } - elseif ($finished == 1) - { - $sql.= " AND p.finished = ".$finished; - if ($status >= 0) $sql.= " AND p.tosell = ".$status; - } - elseif ($status >= 0) - { - $sql.= " AND p.tosell = ".$status; - } - if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype; - // Add criteria on ref/label - if ($filterkey != '') - { - $sql.=' AND ('; - $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on - // For natural search - $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; - foreach ($scrit as $crit) - { - if ($i > 0) $sql.=" AND "; - $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; - if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; - $sql.=")"; - $i++; - } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; - $sql.=')'; - } - if (count($warehouseStatusArray)) - { - $sql.= ' GROUP BY'.$selectFields; - } - $sql.= $db->order("p.ref"); - $sql.= $db->plimit($limit, 0); + if ($finished == 0) + { + $sql.= " AND p.finished = ".$finished; + } + elseif ($finished == 1) + { + $sql.= " AND p.finished = ".$finished; + if ($status >= 0) $sql.= " AND p.tosell = ".$status; + } + elseif ($status >= 0) + { + $sql.= " AND p.tosell = ".$status; + } + if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype; + // Add criteria on ref/label + if ($filterkey != '') + { + $sql.=' AND ('; + $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on + // For natural search + $scrit = explode(' ', $filterkey); + $i=0; + if (count($scrit) > 1) $sql.="("; + foreach ($scrit as $crit) + { + if ($i > 0) $sql.=" AND "; + $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'"; + if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'"; + $sql.=")"; + $i++; + } + if (count($scrit) > 1) $sql.=")"; + if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'"; + $sql.=')'; + } + if (count($warehouseStatusArray)) + { + $sql.= ' GROUP BY'.$selectFields; + } + $sql.= $db->order("p.ref"); + $sql.= $db->plimit($limit, 0); - // Build output string - dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; - $num = $this->db->num_rows($result); + // Build output string + dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; + $num = $this->db->num_rows($result); - $events=null; + $events=null; - if ($conf->use_javascript_ajax && ! $forcecombo) - { + if ($conf->use_javascript_ajax && ! $forcecombo) + { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT); - $out.= $comboenhancement; - } + $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT); + $out.= $comboenhancement; + } - $out.=''; - $textifempty=''; - // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. - //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; - if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) - { - if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); - else $textifempty.=$langs->trans("All"); - } - if ($showempty) $out.=''; + $textifempty=''; + // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. + //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; + if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); + else $textifempty.=$langs->trans("All"); + } + if ($showempty) $out.=''; - $i = 0; - while ($num && $i < $num) - { - $opt = ''; + $i = 0; + while ($num && $i < $num) + { + $opt = ''; $optJson = array(); $objp = $this->db->fetch_object($result); @@ -2044,19 +2056,19 @@ class Form } else { - if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) { - $price_product = new Product($this->db); - $price_product->fetch($objp->rowid, '', '', 1); - $priceparser = new PriceParser($this->db); - $price_result = $priceparser->parseProduct($price_product); - if ($price_result >= 0) { - $objp->price = $price_result; - $objp->unitprice = $price_result; - //Calculate the VAT - $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100)); - $objp->price_ttc = price2num($objp->price_ttc,'MU'); - } - } + if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) { + $price_product = new Product($this->db); + $price_product->fetch($objp->rowid, '', '', 1); + $priceparser = new PriceParser($this->db); + $price_result = $priceparser->parseProduct($price_product); + if ($price_result >= 0) { + $objp->price = $price_result; + $objp->unitprice = $price_result; + //Calculate the VAT + $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100)); + $objp->price_ttc = price2num($objp->price_ttc,'MU'); + } + } $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel); // Add new entry // "key" value of json key array is used by jQuery automatically as selected value @@ -2065,128 +2077,128 @@ class Form array_push($outarray, $optJson); } - $i++; - } + $i++; + } - $out.=''; + $out.=''; - $this->db->free($result); + $this->db->free($result); - if (empty($outputmode)) return $out; - return $outarray; - } - else + if (empty($outputmode)) return $out; + return $outarray; + } + else { - dol_print_error($db); - } - } + dol_print_error($db); + } + } - /** - * constructProductListOption - * - * @param resultset $objp Resultset of fetch - * @param string $opt Option (var used for returned value in string option format) - * @param string $optJson Option (var used for returned value in json format) - * @param int $price_level Price level - * @param string $selected Preselected value - * @param int $hidepriceinlabel Hide price in label - * @return void - */ + /** + * constructProductListOption + * + * @param resultset $objp Resultset of fetch + * @param string $opt Option (var used for returned value in string option format) + * @param string $optJson Option (var used for returned value in json format) + * @param int $price_level Price level + * @param string $selected Preselected value + * @param int $hidepriceinlabel Hide price in label + * @return void + */ private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0) { global $langs,$conf,$user,$db; - $outkey=''; - $outval=''; - $outref=''; - $outlabel=''; - $outdesc=''; - $outbarcode=''; - $outtype=''; - $outprice_ht=''; - $outprice_ttc=''; - $outpricebasetype=''; - $outtva_tx=''; + $outkey=''; + $outval=''; + $outref=''; + $outlabel=''; + $outdesc=''; + $outbarcode=''; + $outtype=''; + $outprice_ht=''; + $outprice_ttc=''; + $outpricebasetype=''; + $outtva_tx=''; $outqty=1; $outdiscount=0; $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO); - $label=$objp->label; - if (! empty($objp->label_translated)) $label=$objp->label_translated; - if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','$1',$label,1); + $label=$objp->label; + if (! empty($objp->label_translated)) $label=$objp->label_translated; + if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','$1',$label,1); - $outkey=$objp->rowid; - $outref=$objp->ref; - $outlabel=$objp->label; - $outdesc=$objp->description; - $outbarcode=$objp->barcode; + $outkey=$objp->rowid; + $outref=$objp->ref; + $outlabel=$objp->label; + $outdesc=$objp->description; + $outbarcode=$objp->barcode; - $outtype=$objp->fk_product_type; - $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; - $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; + $outtype=$objp->fk_product_type; + $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; + $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; - $opt = '\n"; + $opt.= "\n"; $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit); } - /** - * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list) - * - * @param int $socid Id third party - * @param string $selected Preselected product - * @param string $htmlname Name of HTML Select - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param string $filtre For a SQL filter - * @param array $ajaxoptions Options for ajax_autocompleter + /** + * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list) + * + * @param int $socid Id third party + * @param string $selected Preselected product + * @param string $htmlname Name of HTML Select + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param string $filtre For a SQL filter + * @param array $ajaxoptions Options for ajax_autocompleter * @param int $hidelabel Hide label (0=no, 1=yes) * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices - * @return void - */ - function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0) - { - global $langs,$conf; - global $price_level, $status, $finished; + * @return void + */ + function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0) + { + global $langs,$conf; + global $price_level, $status, $finished; - $selected_input_value=''; - if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) - { - if ($selected > 0) - { - require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $producttmpselect = new Product($this->db); - $producttmpselect->fetch($selected); - $selected_input_value=$producttmpselect->ref; - unset($producttmpselect); - } + $selected_input_value=''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + if ($selected > 0) + { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $producttmpselect = new Product($this->db); + $producttmpselect->fetch($selected); + $selected_input_value=$producttmpselect->ref; + unset($producttmpselect); + } // mode=2 means suppliers products - $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; - print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); - print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').''; - } - else - { - print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice); - } - } + $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; + print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); + print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').''; + } + else + { + print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice); + } + } - /** - * Return list of suppliers products - * - * @param int $socid Id societe fournisseur (0 pour aucun filtre) - * @param int $selected Produit pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param string $filtre Pour filtre sql - * @param string $filterkey Filtre des produits - * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request) - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $limit Limit of line number + /** + * Return list of suppliers products + * + * @param int $socid Id societe fournisseur (0 pour aucun filtre) + * @param int $selected Produit pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param string $filtre Pour filtre sql + * @param string $filterkey Filtre des produits + * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request) + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $limit Limit of line number * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices - * @return array Array of keys for json - */ - function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0) - { - global $langs,$conf,$db; + * @return array Array of keys for json + */ + function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0) + { + global $langs,$conf,$db; - $out=''; - $outarray=array(); + $out=''; + $outarray=array(); - $langs->load('stocks'); + $langs->load('stocks'); - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,"; - $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; - $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; - $sql.= " pfp.supplier_reputation"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; - if ($socid) $sql.= " AND pfp.fk_soc = ".$socid; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; - $sql.= " WHERE p.entity IN (".getEntity('product').")"; - $sql.= " AND p.tobuy = 1"; - if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype); - if (! empty($filtre)) $sql.=" ".$filtre; - // Add criteria on ref/label - if ($filterkey != '') - { - $sql.=' AND ('; - $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on - // For natural search - $scrit = explode(' ', $filterkey); - $i=0; - if (count($scrit) > 1) $sql.="("; - foreach ($scrit as $crit) - { - if ($i > 0) $sql.=" AND "; - $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')"; - $i++; - } - if (count($scrit) > 1) $sql.=")"; - if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; - $sql.=')'; - } - $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; - $sql.= $db->plimit($limit, 0); + $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,"; + $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; + $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; + $sql.= " pfp.supplier_reputation"; + $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + if ($socid) $sql.= " AND pfp.fk_soc = ".$socid; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; + $sql.= " WHERE p.entity IN (".getEntity('product').")"; + $sql.= " AND p.tobuy = 1"; + if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype); + if (! empty($filtre)) $sql.=" ".$filtre; + // Add criteria on ref/label + if ($filterkey != '') + { + $sql.=' AND ('; + $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on + // For natural search + $scrit = explode(' ', $filterkey); + $i=0; + if (count($scrit) > 1) $sql.="("; + foreach ($scrit as $crit) + { + if ($i > 0) $sql.=" AND "; + $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')"; + $i++; + } + if (count($scrit) > 1) $sql.=")"; + if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'"; + $sql.=')'; + } + $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC"; + $sql.= $db->plimit($limit, 0); - // Build output string + // Build output string - dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; + dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; - $num = $this->db->num_rows($result); + $num = $this->db->num_rows($result); - //$out.=''; - if (! $selected) $out.=''; - else $out.=''; + //$out.=''; + if (! $selected) $out.=''; + else $out.=''; - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($result); - $outkey=$objp->idprodfournprice; // id in table of price - if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product + $outkey=$objp->idprodfournprice; // id in table of price + if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product - $outref=$objp->ref; - $outval=''; - $outqty=1; + $outref=$objp->ref; + $outval=''; + $outqty=1; $outdiscount=0; - $outtype=$objp->fk_product_type; - $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; - $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; + $outtype=$objp->fk_product_type; + $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):''; + $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):''; - $opt = '\n"; + $opt .= " - ".$reputations[$objp->supplier_reputation]; + $outval.=" - ".$reputations[$objp->supplier_reputation]; + } + } + else + { + if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier + { + $opt.= $langs->trans("NoPriceDefinedForThisSupplier"); + $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier"); + } + else // No supplier price defined for product, even on other suppliers + { + $opt.= $langs->trans("NoPriceDefinedForThisSupplier"); + $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier"); + } + } + $opt .= "\n"; - // Add new entry - // "key" value of json key array is used by jQuery automatically as selected value - // "label" value of json key array is used by jQuery automatically as text for combo box - $out.=$opt; - array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false))); + // Add new entry + // "key" value of json key array is used by jQuery automatically as selected value + // "label" value of json key array is used by jQuery automatically as text for combo box + $out.=$opt; + array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false))); // Exemple of var_dump $outarray // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp" // ["label"]=>string(76) "ppp (fff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)" // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false) - //} - //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); - //$outval=array('label'=>'ppp (fff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)'); - //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); + //} + //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); + //$outval=array('label'=>'ppp (fff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)'); + //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval)); - $i++; - } - $out.=''; + $i++; + } + $out.=''; - $this->db->free($result); + $this->db->free($result); - if (empty($outputmode)) return $out; - return $outarray; - } - else - { - dol_print_error($this->db); - } - } + if (empty($outputmode)) return $out; + return $outarray; + } + else + { + dol_print_error($this->db); + } + } - /** - * Return list of suppliers prices for a product - * - * @param int $productid Id of product - * @param string $htmlname Name of HTML field - * @param int $selected_supplier Pre-selected supplier if more than 1 result - * @return void - */ - function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='') - { - global $langs,$conf; + /** + * Return list of suppliers prices for a product + * + * @param int $productid Id of product + * @param string $htmlname Name of HTML field + * @param int $selected_supplier Pre-selected supplier if more than 1 result + * @return void + */ + function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='') + { + global $langs,$conf; - $langs->load('stocks'); + $langs->load('stocks'); - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; - $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,"; - $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; - $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; - $sql.= " WHERE p.entity IN (".getEntity('productprice').")"; - $sql.= " AND p.tobuy = 1"; - $sql.= " AND s.fournisseur = 1"; - $sql.= " AND p.rowid = ".$productid; - $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC"; + $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; + $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,"; + $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; + $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid"; + $sql.= " WHERE p.entity IN (".getEntity('productprice').")"; + $sql.= " AND p.tobuy = 1"; + $sql.= " AND s.fournisseur = 1"; + $sql.= " AND p.rowid = ".$productid; + $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC"; - dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG); - $result=$this->db->query($sql); + dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG); + $result=$this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); + if ($result) + { + $num = $this->db->num_rows($result); - $form = ''; - if (! $num) - { - $form.= ''; - } - else - { - require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; - $form.= ''; + if (! $num) + { + $form.= ''; + } + else + { + require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; + $form.= ''; - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($result); - $opt = '\n"; + if ($objp->quantity == 1) + { + $opt.= $langs->trans("Unit"); + } + else + { + $opt.= $langs->trans("Units"); + } + if ($objp->quantity > 1) + { + $opt.=" - "; + $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit"); + } + if ($objp->duration) $opt .= " - ".$objp->duration; + $opt .= "\n"; - $form.= $opt; - $i++; - } - } + $form.= $opt; + $i++; + } + } - $form.= ''; - $this->db->free($result); - return $form; - } - else - { - dol_print_error($this->db); - } - } + $form.= ''; + $this->db->free($result); + return $form; + } + else + { + dol_print_error($this->db); + } + } - /** - * Return list of delivery address - * - * @param string $selected Id contact pre-selectionn - * @param int $socid Id of company - * @param string $htmlname Name of HTML field - * @param int $showempty Add an empty field - * @return integer|null - */ - function select_address($selected, $socid, $htmlname='address_id',$showempty=0) - { - // On recherche les utilisateurs - $sql = "SELECT a.rowid, a.label"; - $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a"; - $sql .= " WHERE a.fk_soc = ".$socid; - $sql .= " ORDER BY a.label ASC"; + /** + * Return list of delivery address + * + * @param string $selected Id contact pre-selectionn + * @param int $socid Id of company + * @param string $htmlname Name of HTML field + * @param int $showempty Add an empty field + * @return integer|null + */ + function select_address($selected, $socid, $htmlname='address_id',$showempty=0) + { + // On recherche les utilisateurs + $sql = "SELECT a.rowid, a.label"; + $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a"; + $sql .= " WHERE a.fk_soc = ".$socid; + $sql .= " ORDER BY a.label ASC"; - dol_syslog(get_class($this)."::select_address", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - print ''; + if ($showempty) print ''; + $num = $this->db->num_rows($resql); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - if ($selected && $selected == $obj->rowid) - { - print ''; - } - else - { - print ''; - } - $i++; - } - } - print ''; - return $num; - } - else - { - dol_print_error($this->db); - } - } + if ($selected && $selected == $obj->rowid) + { + print ''; + } + else + { + print ''; + } + $i++; + } + } + print ''; + return $num; + } + else + { + dol_print_error($this->db); + } + } - /** - * Load into cache list of payment terms - * - * @return int Nb of lines loaded, <0 if KO - */ - function load_cache_conditions_paiements() - { - global $langs; + /** + * Load into cache list of payment terms + * + * @return int Nb of lines loaded, <0 if KO + */ + function load_cache_conditions_paiements() + { + global $langs; - $num = count($this->cache_conditions_paiements); - if ($num > 0) return 0; // Cache already loaded + $num = count($this->cache_conditions_paiements); + if ($num > 0) return 0; // Cache already loaded - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT rowid, code, libelle as label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term'; - $sql.= " WHERE active > 0"; - $sql.= " ORDER BY sortorder"; + $sql = "SELECT rowid, code, libelle as label"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term'; + $sql.= " WHERE entity = " . getEntity('c_payment_term'); + $sql.= " AND active > 0"; + $sql.= " ORDER BY sortorder"; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:'')); - $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code; - $this->cache_conditions_paiements[$obj->rowid]['label']=$label; - $i++; - } + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code; + $this->cache_conditions_paiements[$obj->rowid]['label']=$label; + $i++; + } //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table - return $num; - } - else + return $num; + } + else { - dol_print_error($this->db); - return -1; - } - } + dol_print_error($this->db); + return -1; + } + } - /** - * Charge dans cache la liste des délais de livraison possibles - * - * @return int Nb of lines loaded, <0 if KO - */ - function load_cache_availability() - { - global $langs; + /** + * Charge dans cache la liste des délais de livraison possibles + * + * @return int Nb of lines loaded, <0 if KO + */ + function load_cache_availability() + { + global $langs; - $num = count($this->cache_availability); - if ($num > 0) return 0; // Cache already loaded + $num = count($this->cache_availability); + if ($num > 0) return 0; // Cache already loaded - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $langs->load('propal'); - $sql = "SELECT rowid, code, label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability'; - $sql.= " WHERE active > 0"; + $sql = "SELECT rowid, code, label"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability'; + $sql.= " WHERE active > 0"; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:'')); - $this->cache_availability[$obj->rowid]['code'] =$obj->code; - $this->cache_availability[$obj->rowid]['label']=$label; - $i++; - } - - $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1); - - return $num; - } - else + $resql = $this->db->query($sql); + if ($resql) { - dol_print_error($this->db); - return -1; - } - } + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); - /** - * Retourne la liste des types de delais de livraison possibles - * - * @param int $selected Id du type de delais pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $filtertype To add a filter - * @param int $addempty Add empty entry - * @return void - */ - function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0) - { - global $langs,$user; + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_availability[$obj->rowid]['code'] =$obj->code; + $this->cache_availability[$obj->rowid]['label']=$label; + $i++; + } - $this->load_cache_availability(); + $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1); - dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); - - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } - - /** - * Load into cache cache_demand_reason, array of input reasons - * - * @return int Nb of lines loaded, <0 if KO - */ - function loadCacheInputReason() - { - global $langs; - - $num = count($this->cache_demand_reason); - if ($num > 0) return 0; // Cache already loaded - - $sql = "SELECT rowid, code, label"; - $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason'; - $sql.= " WHERE active > 0"; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - $tmparray=array(); - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:'')); - $tmparray[$obj->rowid]['id'] =$obj->rowid; - $tmparray[$obj->rowid]['code'] =$obj->code; - $tmparray[$obj->rowid]['label']=$label; - $i++; - } - - $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1); - - unset($tmparray); - return $num; - } - else + return $num; + } + else { - dol_print_error($this->db); - return -1; - } - } + dol_print_error($this->db); + return -1; + } + } - /** + /** + * Retourne la liste des types de delais de livraison possibles + * + * @param int $selected Id du type de delais pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype To add a filter + * @param int $addempty Add empty entry + * @return void + */ + function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0) + { + global $langs,$user; + + $this->load_cache_availability(); + + dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); + + print ''; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } + + /** + * Load into cache cache_demand_reason, array of input reasons + * + * @return int Nb of lines loaded, <0 if KO + */ + function loadCacheInputReason() + { + global $langs; + + $num = count($this->cache_demand_reason); + if ($num > 0) return 0; // Cache already loaded + + $sql = "SELECT rowid, code, label"; + $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason'; + $sql.= " WHERE active > 0"; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + $tmparray=array(); + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:'')); + $tmparray[$obj->rowid]['id'] =$obj->rowid; + $tmparray[$obj->rowid]['code'] =$obj->code; + $tmparray[$obj->rowid]['label']=$label; + $i++; + } + + $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1); + + unset($tmparray); + return $num; + } + else + { + dol_print_error($this->db); + return -1; + } + } + + /** * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...) * List found into table c_input_reason loaded by loadCacheInputReason - * - * @param int $selected Id or code of type origin to select by default - * @param string $htmlname Nom de la zone select - * @param string $exclude To exclude a code value (Example: SRC_PROP) - * @param int $addempty Add an empty entry - * @return void - */ - function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0) - { - global $langs,$user; + * + * @param int $selected Id or code of type origin to select by default + * @param string $htmlname Nom de la zone select + * @param string $exclude To exclude a code value (Example: SRC_PROP) + * @param int $addempty Add an empty entry + * @return void + */ + function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0) + { + global $langs,$user; - $this->loadCacheInputReason(); + $this->loadCacheInputReason(); - print ''; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } - - /** - * Charge dans cache la liste des types de paiements possibles - * - * @return int Nb of lines loaded, <0 if KO - */ - function load_cache_types_paiements() - { - global $langs; - - $num=count($this->cache_types_paiements); - if ($num > 0) return $num; // Cache already loaded - - dol_syslog(__METHOD__, LOG_DEBUG); - - $this->cache_types_paiements = array(); - - $sql = "SELECT id, code, libelle as label, type, active"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement"; - //if ($active >= 0) $sql.= " WHERE active = ".$active; - - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - - // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut - $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:'')); - $this->cache_types_paiements[$obj->id]['id'] =$obj->id; - $this->cache_types_paiements[$obj->id]['code'] =$obj->code; - $this->cache_types_paiements[$obj->id]['label']=$label; - $this->cache_types_paiements[$obj->id]['type'] =$obj->type; - $this->cache_types_paiements[$obj->id]['active'] =$obj->active; - $i++; - } - - $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1); - - return $num; - } - else + print ''; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } + + /** + * Charge dans cache la liste des types de paiements possibles + * + * @return int Nb of lines loaded, <0 if KO + */ + function load_cache_types_paiements() + { + global $langs; + + $num=count($this->cache_types_paiements); + if ($num > 0) return $num; // Cache already loaded + + dol_syslog(__METHOD__, LOG_DEBUG); + + $this->cache_types_paiements = array(); + + $sql = "SELECT id, code, libelle as label, type, active"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement"; + $sql.= " WHERE entity = " . getEntity('c_paiement'); + //if ($active >= 0) $sql.= " AND active = ".$active; + + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($resql); + + // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut + $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:'')); + $this->cache_types_paiements[$obj->id]['id'] =$obj->id; + $this->cache_types_paiements[$obj->id]['code'] =$obj->code; + $this->cache_types_paiements[$obj->id]['label']=$label; + $this->cache_types_paiements[$obj->id]['type'] =$obj->type; + $this->cache_types_paiements[$obj->id]['active'] =$obj->active; + $i++; + } + + $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1); + + return $num; + } + else + { + dol_print_error($this->db); + return -1; + } + } - /** - * Return list of payment modes. - * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want. - * See instead to force the default value by the caller. - * - * @param int $selected Id of payment term to preselect by default - * @param string $htmlname Nom de la zone select - * @param int $filtertype Not used - * @param int $addempty Add an empty entry - * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info - * @param string $morecss Add more CSS on select tag - * @return void - */ - function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='') - { - global $langs, $user, $conf; + /** + * Return list of payment modes. + * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want. + * See instead to force the default value by the caller. + * + * @param int $selected Id of payment term to preselect by default + * @param string $htmlname Nom de la zone select + * @param int $filtertype Not used + * @param int $addempty Add an empty entry + * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info + * @param string $morecss Add more CSS on select tag + * @return void + */ + function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='') + { + global $langs, $user, $conf; - dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); + dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG); - $this->load_cache_conditions_paiements(); + $this->load_cache_conditions_paiements(); - // Set default value if not already set by caller - if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID; + // Set default value if not already set by caller + if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID; - print ''; - if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } + print ''; + if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } - /** - * Return list of payment methods - * - * @param string $selected Id du mode de paiement pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz)) - * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code - * @param int $empty 1=peut etre vide, 0 sinon - * @param int $noadmininfo 0=Add admin info, 1=Disable admin info - * @param int $maxlength Max length of label - * @param int $active Active or not, -1 = all - * @param string $morecss Add more CSS on select tag - * @return void - */ - function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='') - { - global $langs,$user; + /** + * Return list of payment methods + * + * @param string $selected Id du mode de paiement pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz)) + * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code + * @param int $empty 1=peut etre vide, 0 sinon + * @param int $noadmininfo 0=Add admin info, 1=Disable admin info + * @param int $maxlength Max length of label + * @param int $active Active or not, -1 = all + * @param string $morecss Add more CSS on select tag + * @return void + */ + function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='') + { + global $langs,$user; - dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG); + dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG); - $filterarray=array(); - if ($filtertype == 'CRDT') $filterarray=array(0,2,3); - elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3); - elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype); + $filterarray=array(); + if ($filtertype == 'CRDT') $filterarray=array(0,2,3); + elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3); + elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype); - $this->load_cache_types_paiements(); + $this->load_cache_types_paiements(); - print ''; + if ($empty) print ''; + foreach($this->cache_types_paiements as $id => $arraytypes) + { + // If not good status + if ($active >= 0 && $arraytypes['active'] != $active) continue; - // On passe si on a demande de filtrer sur des modes de paiments particuliers - if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue; + // On passe si on a demande de filtrer sur des modes de paiments particuliers + if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue; - // We discard empty line if showempty is on because an empty line has already been output. - if ($empty && empty($arraytypes['code'])) continue; + // We discard empty line if showempty is on because an empty line has already been output. + if ($empty && empty($arraytypes['code'])) continue; - if ($format == 0) print ''; - } - print ''; - if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } + if ($format == 0) print ''; + } + print ''; + if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } - /** - * Selection HT or TTC - * - * @param string $selected Id pre-selectionne - * @param string $htmlname Nom de la zone select - * @return string Code of HTML select to chose tax or not - */ - function selectPriceBaseType($selected='',$htmlname='price_base_type') - { - global $langs; + /** + * Selection HT or TTC + * + * @param string $selected Id pre-selectionne + * @param string $htmlname Nom de la zone select + * @return string Code of HTML select to chose tax or not + */ + function selectPriceBaseType($selected='',$htmlname='price_base_type') + { + global $langs; - $return=''; + $return=''; - $return.= ''; + $options = array( 'HT'=>$langs->trans("HT"), 'TTC'=>$langs->trans("TTC") - ); - foreach($options as $id => $value) - { - if ($selected == $id) - { - $return.= ''; - } - $return.= ''; + ); + foreach($options as $id => $value) + { + if ($selected == $id) + { + $return.= ''; + } + $return.= ''; - return $return; - } + return $return; + } - /** - * Return a HTML select list of shipping mode - * - * @param string $selected Id shipping mode pre-selected - * @param string $htmlname Name of select zone - * @param string $filtre To filter list - * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @param string $moreattrib To add more attribute on select - * @return void - */ - function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='') - { - global $langs, $conf, $user; + /** + * Return a HTML select list of shipping mode + * + * @param string $selected Id shipping mode pre-selected + * @param string $htmlname Name of select zone + * @param string $filtre To filter list + * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @param string $moreattrib To add more attribute on select + * @return void + */ + function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='') + { + global $langs, $conf, $user; - $langs->load("admin"); - $langs->load("deliveries"); + $langs->load("admin"); + $langs->load("deliveries"); - $sql = "SELECT rowid, code, libelle as label"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode"; - $sql.= " WHERE active > 0"; - if ($filtre) $sql.=" AND ".$filtre; - $sql.= " ORDER BY libelle ASC"; + $sql = "SELECT rowid, code, libelle as label"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode"; + $sql.= " WHERE active > 0"; + if ($filtre) $sql.=" AND ".$filtre; + $sql.= " ORDER BY libelle ASC"; - dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) { - print '"; - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); - } else { - print $langs->trans("NoShippingMethodDefined"); - } - } else { - dol_print_error($this->db); - } - } + dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + if ($num) { + print '"; + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + } else { + print $langs->trans("NoShippingMethodDefined"); + } + } else { + dol_print_error($this->db); + } + } - /** - * Display form to select shipping mode - * - * @param string $page Page - * @param int $selected Id of shipping mode - * @param string $htmlname Name of select html field - * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @return void - */ - function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0) - { - global $langs, $db; + /** + * Display form to select shipping mode + * + * @param string $page Page + * @param int $selected Id of shipping mode + * @param string $htmlname Name of select html field + * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @return void + */ + function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0) + { + global $langs, $db; - $langs->load("deliveries"); + $langs->load("deliveries"); - if ($htmlname != "none") { - print '
      '; - print ''; - print ''; - $this->selectShippingMethod($selected, $htmlname, '', $addempty); - print ''; - print '
      '; - } else { - if ($selected) { - $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); - print $langs->trans("SendingMethod".strtoupper($code)); - } else { - print " "; - } - } - } + if ($htmlname != "none") { + print '
      '; + print ''; + print ''; + $this->selectShippingMethod($selected, $htmlname, '', $addempty); + print ''; + print '
      '; + } else { + if ($selected) { + $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); + print $langs->trans("SendingMethod".strtoupper($code)); + } else { + print " "; + } + } + } /** * Creates HTML last in cycle situation invoices selector @@ -3263,357 +3277,360 @@ class Form return $opt; } - /** - * Creates HTML units selector (code => label) - * - * @param string $selected Preselected Unit ID - * @param string $htmlname Select name - * @param int $showempty Add a nempty line - * @return string HTML select - */ - function selectUnits($selected = '', $htmlname = 'units', $showempty=0) - { - global $langs; + /** + * Creates HTML units selector (code => label) + * + * @param string $selected Preselected Unit ID + * @param string $htmlname Select name + * @param int $showempty Add a nempty line + * @return string HTML select + */ + function selectUnits($selected = '', $htmlname = 'units', $showempty=0) + { + global $langs; - $langs->load('products'); + $langs->load('products'); - $return= ''; - $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units'; - $sql.= ' WHERE active > 0'; + $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units'; + $sql.= ' WHERE active > 0'; - $resql = $this->db->query($sql); - if($resql && $this->db->num_rows($resql) > 0) - { - if ($showempty) $return .= ''; + $resql = $this->db->query($sql); + if($resql && $this->db->num_rows($resql) > 0) + { + if ($showempty) $return .= ''; - while($res = $this->db->fetch_object($resql)) - { - if ($selected == $res->rowid) - { - $return.=''; - } - else - { - $return.=''; - } - } - $return.=''; - } - return $return; - } + while($res = $this->db->fetch_object($resql)) + { + if ($selected == $res->rowid) + { + $return.=''; + } + else + { + $return.=''; + } + } + $return.=''; + } + return $return; + } - /** - * Return a HTML select list of bank accounts - * - * @param string $selected Id account pre-selected - * @param string $htmlname Name of select zone - * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both) - * @param string $filtre To filter list - * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @param string $moreattrib To add more attribute on select - * @param int $showcurrency Show currency in label - * @return void - */ - function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0) - { - global $langs, $conf; + /** + * Return a HTML select list of bank accounts + * + * @param string $selected Id account pre-selected + * @param string $htmlname Name of select zone + * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both) + * @param string $filtre To filter list + * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @param string $moreattrib To add more attribute on select + * @param int $showcurrency Show currency in label + * @return void + */ + function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0) + { + global $langs, $conf; - $langs->load("admin"); + $langs->load("admin"); - $sql = "SELECT rowid, label, bank, clos as status, currency_code"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; - $sql.= " WHERE entity IN (".getEntity('bank_account').")"; - if ($statut != 2) $sql.= " AND clos = '".$statut."'"; - if ($filtre) $sql.=" AND ".$filtre; - $sql.= " ORDER BY label"; + $sql = "SELECT rowid, label, bank, clos as status, currency_code"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; + $sql.= " WHERE entity IN (".getEntity('bank_account').")"; + if ($statut != 2) $sql.= " AND clos = '".$statut."'"; + if ($filtre) $sql.=" AND ".$filtre; + $sql.= " ORDER BY label"; - dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) - { - print ''; + if ($useempty == 1 || ($useempty == 2 && $num > 1)) + { + print ''; + } - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid) - { - print ''; - $i++; - } - print ""; - } - else - { - print $langs->trans("NoActiveBankAccountDefined"); - } - } - else { - dol_print_error($this->db); - } - } + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + } + else + { + print $langs->trans("NoActiveBankAccountDefined"); + } + } + else { + dol_print_error($this->db); + } + } - /** - * Display form to select bank account - * - * @param string $page Page - * @param int $selected Id of bank account - * @param string $htmlname Name of select html field - * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @return void - */ - function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0) - { - global $langs; - if ($htmlname != "none") { - print '
      '; - print ''; - print ''; - $this->select_comptes($selected, $htmlname, 0, '', $addempty); - print ''; - print '
      '; - } else { + /** + * Display form to select bank account + * + * @param string $page Page + * @param int $selected Id of bank account + * @param string $htmlname Name of select html field + * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @return void + */ + function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0) + { + global $langs; + if ($htmlname != "none") { + print '
      '; + print ''; + print ''; + $this->select_comptes($selected, $htmlname, 0, '', $addempty); + print ''; + print '
      '; + } else { - $langs->load('banks'); + $langs->load('banks'); - if ($selected) { - require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; - $bankstatic=new Account($this->db); - $bankstatic->fetch($selected); - print $bankstatic->getNomUrl(1); - } else { - print " "; - } - } - } + if ($selected) { + require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; + $bankstatic=new Account($this->db); + $bankstatic->fetch($selected); + print $bankstatic->getNomUrl(1); + } else { + print " "; + } + } + } - /** - * Return list of categories having choosed type - * - * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. - * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element) - * @param string $htmlname HTML field name - * @param int $maxlength Maximum length for labels - * @param int $excludeafterid Exclude all categories after this leaf in category tree. - * @param int $outputmode 0=HTML select string, 1=Array - * @return string - * @see select_categories - */ - function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0) - { - global $conf, $langs; - $langs->load("categories"); + /** + * Return list of categories having choosed type + * + * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. + * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element) + * @param string $htmlname HTML field name + * @param int $maxlength Maximum length for labels + * @param int $excludeafterid Exclude all categories after this leaf in category tree. + * @param int $outputmode 0=HTML select string, 1=Array + * @return string + * @see select_categories + */ + function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0) + { + global $conf, $langs; + $langs->load("categories"); include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // For backward compatibility if (is_numeric($type)) { - dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); } if ($type === Categorie::TYPE_BANK_LINE) { - // TODO Move this into common category feature - $categids=array(); - $sql = "SELECT c.label, c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c"; - $sql.= " WHERE entity = ".$conf->entity; - $sql.= " ORDER BY c.label"; - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $objp = $this->db->fetch_object($result); - if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label); - $i++; - } - $this->db->free($result); - } - else dol_print_error($this->db); + // TODO Move this into common category feature + $categids=array(); + $sql = "SELECT c.label, c.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c"; + $sql.= " WHERE entity = ".$conf->entity; + $sql.= " ORDER BY c.label"; + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $objp = $this->db->fetch_object($result); + if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label); + $i++; + } + $this->db->free($result); + } + else dol_print_error($this->db); } else { - $cat = new Categorie($this->db); - $cate_arbo = $cat->get_full_arbo($type, $excludeafterid); + $cat = new Categorie($this->db); + $cate_arbo = $cat->get_full_arbo($type, $excludeafterid); } - $output = ''; $outarray=array(); - if (is_array($cate_arbo)) - { - if (! count($cate_arbo)) $output.= ''; - else - { - $output.= ''; - foreach($cate_arbo as $key => $value) - { - if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1)) - { - $add = 'selected '; - } - else - { - $add = ''; - } - $output.= ''; + if (is_array($cate_arbo)) + { + if (! count($cate_arbo)) $output.= ''; + else + { + $output.= ''; + foreach($cate_arbo as $key => $value) + { + if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1)) + { + $add = 'selected '; + } + else + { + $add = ''; + } + $output.= ''; $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel']; - } - } - } - $output.= ''; - $output.= "\n"; + } + } + } + $output.= ''; + $output.= "\n"; if ($outputmode) return $outarray; return $output; - } + } - /** - * Show a confirmation HTML form or AJAX popup - * - * @param string $page Url of page to call if confirmation is OK - * @param string $title Title - * @param string $question Question - * @param string $action Action - * @param array $formquestion An array with forms complementary inputs - * @param string $selectedchoice "" or "no" or "yes" - * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx - * @param int $height Force height of box - * @param int $width Force width of box - * @return void - * @deprecated - * @see formconfirm() - */ - function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500) - { - print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width); - } + /** + * Show a confirmation HTML form or AJAX popup + * + * @param string $page Url of page to call if confirmation is OK + * @param string $title Title + * @param string $question Question + * @param string $action Action + * @param array $formquestion An array with forms complementary inputs + * @param string $selectedchoice "" or "no" or "yes" + * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx + * @param int $height Force height of box + * @param int $width Force width of box + * @return void + * @deprecated + * @see formconfirm() + */ + function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500) + { + print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width); + } - /** - * Show a confirmation HTML form or AJAX popup. - * Easiest way to use this is with useajax=1. - * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters) - * just after calling this method. For example: - * print ''."\n"; - * - * @param string $page Url of page to call if confirmation is OK - * @param string $title Title - * @param string $question Question - * @param string $action Action - * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , )) - * @param string $selectedchoice "" or "no" or "yes" - * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx - * @param int $height Force height of box - * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones. - * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form - */ - function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500) - { - global $langs,$conf; - global $useglobalvars; + /** + * Show a confirmation HTML form or AJAX popup. + * Easiest way to use this is with useajax=1. + * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters) + * just after calling this method. For example: + * print ''."\n"; + * + * @param string $page Url of page to call if confirmation is OK + * @param string $title Title + * @param string $question Question + * @param string $action Action + * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , )) + * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', ... + * @param string $selectedchoice "" or "no" or "yes" + * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx + * @param int $height Force height of box + * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones. + * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form + */ + function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500) + { + global $langs,$conf; + global $useglobalvars; - $more=''; - $formconfirm=''; - $inputok=array(); - $inputko=array(); + $more=''; + $formconfirm=''; + $inputok=array(); + $inputko=array(); - // Clean parameters - $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; - if ($conf->browser->layout == 'phone') $width='95%'; + // Clean parameters + $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; + if ($conf->browser->layout == 'phone') $width='95%'; - if (is_array($formquestion) && ! empty($formquestion)) - { - // First add hidden fields and value - foreach ($formquestion as $key => $input) - { - if (is_array($input) && ! empty($input)) - { - if ($input['type'] == 'hidden') - { - $more.=''."\n"; - } - } - } + if (is_array($formquestion) && ! empty($formquestion)) + { + // First add hidden fields and value + foreach ($formquestion as $key => $input) + { + if (is_array($input) && ! empty($input)) + { + if ($input['type'] == 'hidden') + { + $more.=''."\n"; + } + } + } - // Now add questions - $more.=''."\n"; - $more.=''."\n"; - foreach ($formquestion as $key => $input) - { - if (is_array($input) && ! empty($input)) - { - $size=(! empty($input['size'])?' size="'.$input['size'].'"':''); + // Now add questions + $more.='
      '.(! empty($formquestion['text'])?$formquestion['text']:'').'
      '."\n"; + $more.=''."\n"; + foreach ($formquestion as $key => $input) + { + if (is_array($input) && ! empty($input)) + { + $size=(! empty($input['size'])?' size="'.$input['size'].'"':''); + $moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:''); + $morecss=(! empty($input['morecss'])?' '.$input['morecss']:''); - if ($input['type'] == 'text') - { - $more.=''."\n"; - } - else if ($input['type'] == 'password') - { - $more.=''."\n"; - } - else if ($input['type'] == 'select') - { - $more.=''."\n"; - } - else if ($input['type'] == 'checkbox') - { - $more.=''; - $more.=''; - if ($i==0) $more.=''; - else $more.=''; - $more.=''."\n"; + } + else if ($input['type'] == 'password') + { + $more.=''."\n"; + } + else if ($input['type'] == 'select') + { + $more.=''."\n"; + } + else if ($input['type'] == 'checkbox') + { + $more.=''; + $more.=''; + if ($i==0) $more.=''; + else $more.=''; + $more.=''."\n"; - } - } - } - $more.='
      '.(! empty($formquestion['text'])?$formquestion['text']:'').'
      '.$input['label'].'
      '.$input['label'].'
      '; - if (! empty($input['label'])) $more.=$input['label'].''; - $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1); - $more.='
      '.$input['label'].' '; - $more.=' $selval) - { - $more.='
      '.$input['label'].' 
      '.$input['label'].'
      '; + if (! empty($input['label'])) $more.=$input['label'].''; + $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss); + $more.='
      '.$input['label'].' '; + $more.=' $selval) + { + $more.='
      '.$input['label'].' '; @@ -3626,71 +3643,78 @@ class Form $formquestion[] = array('name'=>$input['name'].'hour'); $formquestion[] = array('name'=>$input['name'].'min'); } - else if ($input['type'] == 'other') - { - $more.='
      '; - if (! empty($input['label'])) $more.=$input['label'].''; - $more.=$input['value']; - $more.='
      '."\n"; - } + else if ($input['type'] == 'other') + { + $more.=''; + if (! empty($input['label'])) $more.=$input['label'].''; + $more.=$input['value']; + $more.=''."\n"; + } + + else if ($input['type'] == 'onecolumn') + { + $more.=''; + $more.=$input['value']; + $more.=''."\n"; + } + } + } + $more.=''."\n"; + } // JQUI method dialog is broken with jmobile, we use standard HTML. // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx // See page product/card.php for example - if (! empty($conf->dol_use_jmobile)) $useajax=0; + if (! empty($conf->dol_use_jmobile)) $useajax=0; if (empty($conf->use_javascript_ajax)) $useajax=0; - if ($useajax) - { - $autoOpen=true; - $dialogconfirm='dialog-confirm'; - $button=''; - if (! is_numeric($useajax)) - { - $button=$useajax; - $useajax=1; - $autoOpen=false; - $dialogconfirm.='-'.$button; - } - $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes'; - $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':''); - // Add input fields into list of fields to read during submit (inputok and inputko) - if (is_array($formquestion)) - { - foreach ($formquestion as $key => $input) - { - //print "xx ".$key." rr ".is_array($input)."
      \n"; - if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']); - if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']); - } - } + if ($useajax) + { + $autoOpen=true; + $dialogconfirm='dialog-confirm'; + $button=''; + if (! is_numeric($useajax)) + { + $button=$useajax; + $useajax=1; + $autoOpen=false; + $dialogconfirm.='-'.$button; + } + $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes'; + $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':''); + // Add input fields into list of fields to read during submit (inputok and inputko) + if (is_array($formquestion)) + { + foreach ($formquestion as $key => $input) + { + //print "xx ".$key." rr ".is_array($input)."
      \n"; + if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']); + if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']); + } + } // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template - $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; - $formconfirm.= "\n\n"; - $formconfirm.= ''; - $formconfirm.= "\n"; - } - else - { - $formconfirm.= "\n\n"; + $formconfirm.= "\n"; + } + else + { + $formconfirm.= "\n\n"; - $formconfirm.= '
      '."\n"; - $formconfirm.= ''."\n"; - $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; + $formconfirm.= ''."\n"; - $formconfirm.= ''."\n"; + $formconfirm.= '
      '."\n"; - // Line title - $formconfirm.= ''."\n"; + // Line title + $formconfirm.= ''."\n"; - // Line form fields - if ($more) - { - $formconfirm.=''."\n"; - } + // Line form fields + if ($more) + { + $formconfirm.=''."\n"; + } - // Line with question - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''; - $formconfirm.= ''."\n"; + // Line with question + $formconfirm.= ''; + $formconfirm.= ''; + $formconfirm.= ''; + $formconfirm.= ''; + $formconfirm.= ''."\n"; - $formconfirm.= '
      '.img_picto('','recent').' '.$title.'
      '.img_picto('','recent').' '.$title.'
      '."\n"; - $formconfirm.=$more; - $formconfirm.='
      '."\n"; + $formconfirm.=$more; + $formconfirm.='
      '.$question.''; - $formconfirm.= $this->selectyesno("confirm",$newselectedchoice); - $formconfirm.= '
      '.$question.''; + $formconfirm.= $this->selectyesno("confirm",$newselectedchoice); + $formconfirm.= '
      '."\n"; + $formconfirm.= ''."\n"; - $formconfirm.= "
      \n"; - $formconfirm.= '
      '; + $formconfirm.= "\n"; + $formconfirm.= '
      '; - $formconfirm.= "\n"; - } + $formconfirm.= "\n"; + } - return $formconfirm; - } + return $formconfirm; + } - /** - * Show a form to select a project - * - * @param int $page Page - * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) - * @param int $selected Id pre-selected project - * @param string $htmlname Name of select field - * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable) - * @param int $maxlength Max length - * @param int $forcefocus Force focus on field (works with javascript only) - * @param int $nooutput No print is done. String is returned. - * @return string Return html content - */ - function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0) - { - global $langs; + /** + * Show a form to select a project + * + * @param int $page Page + * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) + * @param int $selected Id pre-selected project + * @param string $htmlname Name of select field + * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable) + * @param int $maxlength Max length + * @param int $forcefocus Force focus on field (works with javascript only) + * @param int $nooutput No print is done. String is returned. + * @return string Return html content + */ + function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0) + { + global $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; - $out=''; + $out=''; - $formproject=new FormProjets($this->db); + $formproject=new FormProjets($this->db); - $langs->load("project"); - if ($htmlname != "none") - { - $out.="\n"; - $out.='
      '; - $out.=''; - $out.=''; - $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); - $out.=''; - $out.='
      '; - } - else - { - if ($selected) - { - $projet = new Project($this->db); - $projet->fetch($selected); - //print ''.$projet->title.''; - $out.=$projet->getNomUrl(0,'',1); - } - else - { - $out.=" "; - } - } + $langs->load("project"); + if ($htmlname != "none") + { + $out.="\n"; + $out.='
      '; + $out.=''; + $out.=''; + $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); + $out.=''; + $out.='
      '; + } + else + { + if ($selected) + { + $projet = new Project($this->db); + $projet->fetch($selected); + //print ''.$projet->title.''; + $out.=$projet->getNomUrl(0,'',1); + } + else + { + $out.=" "; + } + } - if (empty($nooutput)) - { - print $out; - return ''; - } - return $out; - } + if (empty($nooutput)) + { + print $out; + return ''; + } + return $out; + } - /** - * Show a form to select payment conditions - * - * @param int $page Page - * @param string $selected Id condition pre-selectionne - * @param string $htmlname Name of select html field - * @param int $addempty Add empty entry - * @return void - */ - function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0) - { - global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - $this->select_conditions_paiements($selected,$htmlname,-1,$addempty); - print ''; - print '
      '; - } - else - { - if ($selected) - { - $this->load_cache_conditions_paiements(); - print $this->cache_conditions_paiements[$selected]['label']; - } else { - print " "; - } - } - } + /** + * Show a form to select payment conditions + * + * @param int $page Page + * @param string $selected Id condition pre-selectionne + * @param string $htmlname Name of select html field + * @param int $addempty Add empty entry + * @return void + */ + function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0) + { + global $langs; + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + $this->select_conditions_paiements($selected,$htmlname,-1,$addempty); + print ''; + print '
      '; + } + else + { + if ($selected) + { + $this->load_cache_conditions_paiements(); + print $this->cache_conditions_paiements[$selected]['label']; + } else { + print " "; + } + } + } - /** - * Show a form to select a delivery delay - * - * @param int $page Page - * @param string $selected Id condition pre-selectionne - * @param string $htmlname Name of select html field - * @param int $addempty Ajoute entree vide - * @return void - */ - function form_availability($page, $selected='', $htmlname='availability', $addempty=0) - { - global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty); - print ''; - print '
      '; - } - else - { - if ($selected) - { - $this->load_cache_availability(); - print $this->cache_availability[$selected]['label']; - } else { - print " "; - } - } - } + /** + * Show a form to select a delivery delay + * + * @param int $page Page + * @param string $selected Id condition pre-selectionne + * @param string $htmlname Name of select html field + * @param int $addempty Ajoute entree vide + * @return void + */ + function form_availability($page, $selected='', $htmlname='availability', $addempty=0) + { + global $langs; + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty); + print ''; + print '
      '; + } + else + { + if ($selected) + { + $this->load_cache_availability(); + print $this->cache_availability[$selected]['label']; + } else { + print " "; + } + } + } - /** + /** * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...) * List found into table c_input_reason loaded by loadCacheInputReason - * - * @param string $page Page - * @param string $selected Id condition pre-selectionne - * @param string $htmlname Name of select html field - * @param int $addempty Add empty entry - * @return void - */ - function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0) - { - global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - $this->selectInputReason($selected,$htmlname,-1,$addempty); - print ''; - print '
      '; - } - else - { - if ($selected) - { - $this->loadCacheInputReason(); - foreach ($this->cache_demand_reason as $key => $val) - { - if ($val['id'] == $selected) - { - print $val['label']; - break; - } - } - } else { - print " "; - } - } - } - - /** - * Show a form + html select a date - * - * @param string $page Page - * @param string $selected Date preselected - * @param string $htmlname Html name of date input fields or 'none' - * @param int $displayhour Display hour selector - * @param int $displaymin Display minutes selector - * @param int $nooutput 1=No print output, return string - * @return string - * @see select_date - */ - function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0) - { - global $langs; - - $ret=''; - - if ($htmlname != "none") - { - $ret.='
      '; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.=''; - $ret.='
      '; - $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1); - $ret.='
      '; - } - else - { - if ($displayhour) $ret.=dol_print_date($selected,'dayhour'); - else $ret.=dol_print_date($selected,'day'); - } - - if (empty($nooutput)) print $ret; - return $ret; - } - - - /** - * Show a select form to choose a user - * - * @param string $page Page - * @param string $selected Id of user preselected - * @param string $htmlname Name of input html field. If 'none', we just output the user link. - * @param array $exclude List of users id to exclude - * @param array $include List of users id to include - * @return void - */ - function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='') - { - global $langs; - - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include); - print ''; - print '
      '; - } - else + * + * @param string $page Page + * @param string $selected Id condition pre-selectionne + * @param string $htmlname Name of select html field + * @param int $addempty Add empty entry + * @return void + */ + function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0) + { + global $langs; + if ($htmlname != "none") { - if ($selected) - { - require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php'; - $theuser=new User($this->db); - $theuser->fetch($selected); - print $theuser->getNomUrl(1); - } else { - print " "; - } - } - } - - - /** - * Show form with payment mode - * - * @param string $page Page - * @param int $selected Id mode pre-selectionne - * @param string $htmlname Name of select html field - * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz)) - * @param int $active Active or not, -1 = all - * @return void - */ - function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1) - { - global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active); - print ''; - print '
      '; - } - else - { - if ($selected) - { - $this->load_cache_types_paiements(); - print $this->cache_types_paiements[$selected]['label']; - } else { - print " "; - } - } - } + print '
      '; + print ''; + print ''; + $this->selectInputReason($selected,$htmlname,-1,$addempty); + print ''; + print '
      '; + } + else + { + if ($selected) + { + $this->loadCacheInputReason(); + foreach ($this->cache_demand_reason as $key => $val) + { + if ($val['id'] == $selected) + { + print $val['label']; + break; + } + } + } else { + print " "; + } + } + } /** - * Show form with multicurrency code - * - * @param string $page Page - * @param string $selected code pre-selectionne - * @param string $htmlname Name of select html field - * @return void - */ - function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code') - { - global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - print $this->selectMultiCurrency($selected, $htmlname, 0); - print ''; - print '
      '; - } - else - { - dol_include_once('/core/lib/company.lib.php'); - print !empty($selected) ? currency_name($selected,1) : ' '; - } - } + * Show a form + html select a date + * + * @param string $page Page + * @param string $selected Date preselected + * @param string $htmlname Html name of date input fields or 'none' + * @param int $displayhour Display hour selector + * @param int $displaymin Display minutes selector + * @param int $nooutput 1=No print output, return string + * @return string + * @see select_date + */ + function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0) + { + global $langs; + + $ret=''; + + if ($htmlname != "none") + { + $ret.='
      '; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.=''; + $ret.='
      '; + $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1); + $ret.='
      '; + } + else + { + if ($displayhour) $ret.=dol_print_date($selected,'dayhour'); + else $ret.=dol_print_date($selected,'day'); + } + + if (empty($nooutput)) print $ret; + return $ret; + } + /** - * Show form with multicurrency rate - * - * @param string $page Page - * @param double $rate Current rate - * @param string $htmlname Name of select html field - * @param string $currency Currency code to explain the rate - * @return void - */ - function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='') - { - global $langs, $mysoc, $conf; + * Show a select form to choose a user + * + * @param string $page Page + * @param string $selected Id of user preselected + * @param string $htmlname Name of input html field. If 'none', we just output the user link. + * @param array $exclude List of users id to exclude + * @param array $include List of users id to include + * @return void + */ + function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='') + { + global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - print ' '; + if ($htmlname != "none") + { + print ''; + print ''; + print ''; + print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include); + print ''; + print '
      '; + } + else + { + if ($selected) + { + require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php'; + $theuser=new User($this->db); + $theuser->fetch($selected); + print $theuser->getNomUrl(1); + } else { + print " "; + } + } + } + + + /** + * Show form with payment mode + * + * @param string $page Page + * @param int $selected Id mode pre-selectionne + * @param string $htmlname Name of select html field + * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz)) + * @param int $active Active or not, -1 = all + * @return void + */ + function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1) + { + global $langs; + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active); + print ''; + print '
      '; + } + else + { + if ($selected) + { + $this->load_cache_types_paiements(); + print $this->cache_types_paiements[$selected]['label']; + } else { + print " "; + } + } + } + + /** + * Show form with multicurrency code + * + * @param string $page Page + * @param string $selected code pre-selectionne + * @param string $htmlname Name of select html field + * @return void + */ + function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code') + { + global $langs; + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + print $this->selectMultiCurrency($selected, $htmlname, 0); + print ''; + print '
      '; + } + else + { + dol_include_once('/core/lib/company.lib.php'); + print !empty($selected) ? currency_name($selected,1) : ' '; + } + } + + /** + * Show form with multicurrency rate + * + * @param string $page Page + * @param double $rate Current rate + * @param string $htmlname Name of select html field + * @param string $currency Currency code to explain the rate + * @return void + */ + function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='') + { + global $langs, $mysoc, $conf; + + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + print ' '; print ' '; - print ''; - print '
      '; - } - else - { - if (! empty($rate)) - { - print price($rate, 1, $langs, 1, 0); - if ($currency && $rate != 1) print '   ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')'; - } - else - { - print 1; - } - } - } + print ''; + print ''; + } + else + { + if (! empty($rate)) + { + print price($rate, 1, $langs, 1, 0); + if ($currency && $rate != 1) print '   ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')'; + } + else + { + print 1; + } + } + } - /** - * Show a select box with available absolute discounts - * - * @param string $page Page URL where form is shown - * @param int $selected Value pre-selected - * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'. - * @param int $socid Third party id - * @param float $amount Total amount available - * @param string $filter SQL filter on discounts - * @param int $maxvalue Max value for lines that can be selected - * @param string $more More string to add - * @param int $hidelist 1=Hide list - * @return void - */ - function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0) - { - global $conf,$langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - print '
      '; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) - { - if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - else - { - if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); - else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); - } - if (empty($hidelist)) print ': '; - print '
      '; - if (empty($hidelist)) - { - print '
      '; - $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles - if ($filter) $newfilter.=' AND ('.$filter.')'; - $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); - if ($nbqualifiedlines > 0) - { - print '   '; - } - print '
      '; - } - if ($more) - { - print '
      '; - print $more; - print '
      '; - } - print '
      '; - } - else - { - if ($selected) - { - print $selected; - } - else - { - print "0"; - } - } - } + /** + * Show a select box with available absolute discounts + * + * @param string $page Page URL where form is shown + * @param int $selected Value pre-selected + * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'. + * @param int $socid Third party id + * @param float $amount Total amount available + * @param string $filter SQL filter on discounts + * @param int $maxvalue Max value for lines that can be selected + * @param string $more More string to add + * @param int $hidelist 1=Hide list + * @return void + */ + function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0) + { + global $conf,$langs; + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + print '
      '; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + { + if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + else + { + if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); + else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)); + } + if (empty($hidelist)) print ': '; + print '
      '; + if (empty($hidelist)) + { + print '
      '; + $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles + if ($filter) $newfilter.=' AND ('.$filter.')'; + $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); + if ($nbqualifiedlines > 0) + { + print '   '; + } + print '
      '; + } + if ($more) + { + print '
      '; + print $more; + print '
      '; + } + print '
      '; + } + else + { + if ($selected) + { + print $selected; + } + else + { + print "0"; + } + } + } - /** - * Show forms to select a contact - * - * @param string $page Page - * @param Societe $societe Filter on third party - * @param int $selected Id contact pre-selectionne - * @param string $htmlname Name of HTML select. If 'none', we just show contact link. - * @return void - */ - function form_contacts($page, $societe, $selected='', $htmlname='contactid') - { - global $langs, $conf; + /** + * Show forms to select a contact + * + * @param string $page Page + * @param Societe $societe Filter on third party + * @param int $selected Id contact pre-selectionne + * @param string $htmlname Name of HTML select. If 'none', we just show contact link. + * @return void + */ + function form_contacts($page, $societe, $selected='', $htmlname='contactid') + { + global $langs, $conf; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
      '; - $num=$this->select_contacts($societe->id, $selected, $htmlname); - if ($num==0) - { - $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); - print ''.$addcontact.''; - } - print '
      '; - } - else - { - if ($selected) - { - require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; - $contact=new Contact($this->db); - $contact->fetch($selected); - print $contact->getFullName($langs); - } else { - print " "; - } - } - } + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
      '; + $num=$this->select_contacts($societe->id, $selected, $htmlname); + if ($num==0) + { + $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + print ''.$addcontact.''; + } + print '
      '; + } + else + { + if ($selected) + { + require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; + $contact=new Contact($this->db); + $contact->fetch($selected); + print $contact->getFullName($langs); + } else { + print " "; + } + } + } - /** - * Output html select to select thirdparty - * - * @param string $page Page - * @param string $selected Id preselected - * @param string $htmlname Name of HTML select - * @param string $filter optional filters criteras - * @param int $showempty Add an empty field - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @return void - */ - function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array()) - { - global $langs; + /** + * Output html select to select thirdparty + * + * @param string $page Page + * @param string $selected Id preselected + * @param string $htmlname Name of HTML select + * @param string $filter optional filters criteras + * @param int $showempty Add an empty field + * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int $forcecombo Force to use combo box + * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) + * @return void + */ + function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array()) + { + global $langs; - if ($htmlname != "none") - { - print '
      '; - print ''; - print ''; - print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); - print ''; - print '
      '; - } - else - { - if ($selected) - { - require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; - $soc = new Societe($this->db); - $soc->fetch($selected); - print $soc->getNomUrl($langs); - } - else - { - print " "; - } - } - } + if ($htmlname != "none") + { + print '
      '; + print ''; + print ''; + print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); + print ''; + print '
      '; + } + else + { + if ($selected) + { + require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; + $soc = new Societe($this->db); + $soc->fetch($selected); + print $soc->getNomUrl($langs); + } + else + { + print " "; + } + } + } - /** - * Retourne la liste des devises, dans la langue de l'utilisateur - * - * @param string $selected preselected currency code - * @param string $htmlname name of HTML select list - * @return void - */ - function select_currency($selected='',$htmlname='currency_id') - { - print $this->selectCurrency($selected,$htmlname); - } + /** + * Retourne la liste des devises, dans la langue de l'utilisateur + * + * @param string $selected preselected currency code + * @param string $htmlname name of HTML select list + * @return void + */ + function select_currency($selected='',$htmlname='currency_id') + { + print $this->selectCurrency($selected,$htmlname); + } - /** - * Retourne la liste des devises, dans la langue de l'utilisateur - * - * @param string $selected preselected currency code - * @param string $htmlname name of HTML select list - * @return string - */ + /** + * Retourne la liste des devises, dans la langue de l'utilisateur + * + * @param string $selected preselected currency code + * @param string $htmlname name of HTML select list + * @return string + */ function selectCurrency($selected='',$htmlname='currency_id') { global $conf,$langs,$user; @@ -4349,18 +4373,18 @@ class Form } /** - * Return array of currencies in user language + * Return array of currencies in user language * - * @param string $selected preselected currency code - * @param string $htmlname name of HTML select list - * @param integer $useempty 1=Add empty line - * @return string - */ - function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0) - { - global $db,$conf,$langs,$user; + * @param string $selected preselected currency code + * @param string $htmlname name of HTML select list + * @param integer $useempty 1=Add empty line + * @return string + */ + function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0) + { + global $db,$conf,$langs,$user; - $langs->loadCacheCurrencies(''); // Load ->cache_currencies + $langs->loadCacheCurrencies(''); // Load ->cache_currencies $TCurrency = array(); @@ -4373,435 +4397,440 @@ class Form } $out=''; - $out.= ''; if ($useempty) $out .= ''; // If company current currency not in table, we add it into list. Should always be available. if (! in_array($conf->currency, $TCurrency)) { - $TCurrency[$conf->currency] = $conf->currency; + $TCurrency[$conf->currency] = $conf->currency; } if (count($TCurrency) > 0) { foreach ($langs->cache_currencies as $code_iso => $currency) - { - if (isset($TCurrency[$code_iso])) + { + if (isset($TCurrency[$code_iso])) { if (!empty($selected) && $selected == $code_iso) $out.= ''; + $out.= $currency['label']; + $out.= ' ('.$langs->getCurrencySymbol($code_iso).')'; + $out.= ''; } - } + } } - $out.= ''; + $out.= ''; // Make select dynamic include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $out.= ajax_combobox($htmlname); - return $out; - } + return $out; + } - /** - * Load into the cache vat rates of a country - * - * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'") - * @return int Nb of loaded lines, 0 if already loaded, <0 if KO - */ - function load_cache_vatrates($country_code) - { - global $langs; + /** + * Load into the cache vat rates of a country + * + * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'") + * @return int Nb of loaded lines, 0 if already loaded, <0 if KO + */ + function load_cache_vatrates($country_code) + { + global $langs; - $num = count($this->cache_vatrates); - if ($num > 0) return $num; // Cache already loaded + $num = count($this->cache_vatrates); + if ($num > 0) return $num; // Cache already loaded - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql.= " WHERE t.fk_pays = c.rowid"; - $sql.= " AND t.active > 0"; - $sql.= " AND c.code IN (".$country_code.")"; - $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC"; + $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql.= " WHERE t.fk_pays = c.rowid"; + $sql.= " AND t.active > 0"; + $sql.= " AND c.code IN (".$country_code.")"; + $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC"; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - if ($num) - { - for ($i = 0; $i < $num; $i++) - { - $obj = $this->db->fetch_object($resql); - $this->cache_vatrates[$i]['rowid'] = $obj->rowid; - $this->cache_vatrates[$i]['code'] = $obj->code; - $this->cache_vatrates[$i]['txtva'] = $obj->taux; - $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly; - $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1; - $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type; - $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2; - $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type; + $resql=$this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + if ($num) + { + for ($i = 0; $i < $num; $i++) + { + $obj = $this->db->fetch_object($resql); + $this->cache_vatrates[$i]['rowid'] = $obj->rowid; + $this->cache_vatrates[$i]['code'] = $obj->code; + $this->cache_vatrates[$i]['txtva'] = $obj->taux; + $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly; + $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1; + $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type; + $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2; + $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type; - $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or * - $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label - $positiverates=''; - if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux; - if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1; - if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2; - if (empty($positiverates)) $positiverates='0'; - $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label - } + $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or * + $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label + $positiverates=''; + if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux; + if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1; + if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2; + if (empty($positiverates)) $positiverates='0'; + $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':''); // Must never be used as key, only label + } - return $num; - } - else - { - $this->error = ''.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).''; - return -1; - } - } - else - { - $this->error = ''.$this->db->error().''; - return -2; - } - } + return $num; + } + else + { + $this->error = ''.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).''; + return -1; + } + } + else + { + $this->error = ''.$this->db->error().''; + return -2; + } + } - /** - * Output an HTML select vat rate. - * The name of this function should be selectVat. We keep bad name for compatibility purpose. - * - * @param string $htmlname Name of HTML select field - * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing. - * @param Societe $societe_vendeuse Thirdparty seller - * @param Societe $societe_acheteuse Thirdparty buyer - * @param int $idprod Id product. O if unknown of NA. - * @param int $info_bits Miscellaneous information on line (1 for NPR) - * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined) - * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle. - * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle. - * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle. + /** + * Output an HTML select vat rate. + * The name of this function should be selectVat. We keep bad name for compatibility purpose. + * + * @param string $htmlname Name of HTML select field + * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing. + * @param Societe $societe_vendeuse Thirdparty seller + * @param Societe $societe_acheteuse Thirdparty buyer + * @param int $idprod Id product. O if unknown of NA. + * @param int $info_bits Miscellaneous information on line (1 for NPR) + * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined) + * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle. + * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle. + * Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle. - * Sinon la TVA proposee par defaut=0. Fin de regle. - * @param bool $options_only Return HTML options lines only (for ajax treatment) - * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key - * @return string - */ - function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0) - { - global $langs,$conf,$mysoc; + * Sinon la TVA proposee par defaut=0. Fin de regle. + * @param bool $options_only Return HTML options lines only (for ajax treatment) + * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key + * @return string + */ + function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0) + { + global $langs,$conf,$mysoc; - $return=''; + $return=''; - // Define defaultnpr, defaultttx and defaultcode - $defaultnpr=($info_bits & 0x01); - $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr); - $defaulttx=str_replace('*','',$selectedrate); - $defaultcode=''; - if (preg_match('/\((.*)\)/', $defaulttx, $reg)) - { - $defaultcode=$reg[1]; - $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx); - } - //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode); + // Define defaultnpr, defaultttx and defaultcode + $defaultnpr=($info_bits & 0x01); + $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr); + $defaulttx=str_replace('*','',$selectedrate); + $defaultcode=''; + if (preg_match('/\((.*)\)/', $defaulttx, $reg)) + { + $defaultcode=$reg[1]; + $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx); + } + //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode); - // Check parameters - if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code) - { - if ($societe_vendeuse->id == $mysoc->id) - { - $return.= ''.$langs->trans("ErrorYourCountryIsNotDefined").''; - } - else - { - $return.= ''.$langs->trans("ErrorSupplierCountryIsNotDefined").''; - } - return $return; - } + // Check parameters + if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code) + { + if ($societe_vendeuse->id == $mysoc->id) + { + $return.= ''.$langs->trans("ErrorYourCountryIsNotDefined").''; + } + else + { + $return.= ''.$langs->trans("ErrorSupplierCountryIsNotDefined").''; + } + return $return; + } - //var_dump($societe_acheteuse); - //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type"; - //exit; + //var_dump($societe_acheteuse); + //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type"; + //exit; - // Define list of countries to use to search VAT rates to show - // First we defined code_country to use to find list - if (is_object($societe_vendeuse)) - { - $code_country="'".$societe_vendeuse->country_code."'"; - } - else - { - $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente - } - if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on - { - if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany()))) - { - // We also add the buyer - if (is_numeric($type)) - { - if ($type == 1) // We know product is a service - { - $code_country.=",'".$societe_acheteuse->country_code."'"; - } - } - else if (! $idprod) // We don't know type of product - { - $code_country.=",'".$societe_acheteuse->country_code."'"; - } - else - { - $prodstatic=new Product($this->db); - $prodstatic->fetch($idprod); - if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service - { - $code_country.=",'".$societe_acheteuse->country_code."'"; - } - } - } - } + // Define list of countries to use to search VAT rates to show + // First we defined code_country to use to find list + if (is_object($societe_vendeuse)) + { + $code_country="'".$societe_vendeuse->country_code."'"; + } + else + { + $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente + } + if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on + { + if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany()))) + { + // We also add the buyer + if (is_numeric($type)) + { + if ($type == 1) // We know product is a service + { + $code_country.=",'".$societe_acheteuse->country_code."'"; + } + } + else if (! $idprod) // We don't know type of product + { + $code_country.=",'".$societe_acheteuse->country_code."'"; + } + else + { + $prodstatic=new Product($this->db); + $prodstatic->fetch($idprod); + if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service + { + $code_country.=",'".$societe_acheteuse->country_code."'"; + } + } + } + } - // Now we get list - $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error + // Now we get list + $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error - if ($num > 0) - { - // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '') - if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) - { - $tmpthirdparty=new Societe($this->db); - $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); - $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); - if (empty($defaulttx)) $defaultnpr=0; - } + if ($num > 0) + { + // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '') + if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) + { + $tmpthirdparty=new Societe($this->db); + $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); + $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod); + if (empty($defaulttx)) $defaultnpr=0; + } - // Si taux par defaut n'a pu etre determine, on prend dernier de la liste. - // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant - if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) - { - if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva']; - else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS); - } + // Si taux par defaut n'a pu etre determine, on prend dernier de la liste. + // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant + if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) + { + if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva']; + else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS); + } - // Disabled if seller is not subject to VAT - $disabled=false; $title=''; - if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") - { - $title=' title="'.$langs->trans('VATIsNotUsed').'"'; - $disabled=true; - } + // Disabled if seller is not subject to VAT + $disabled=false; $title=''; + if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") + { + $title=' title="'.$langs->trans('VATIsNotUsed').'"'; + $disabled=true; + } - if (! $options_only) $return.= ''; - $selectedfound=false; - foreach ($this->cache_vatrates as $rate) - { - // Keep only 0 if seller is not subject to VAT - if ($disabled && $rate['txtva'] != 0) continue; + $selectedfound=false; + foreach ($this->cache_vatrates as $rate) + { + // Keep only 0 if seller is not subject to VAT + if ($disabled && $rate['txtva'] != 0) continue; - // Define key to use into select list - $key = $rate['txtva']; - $key.= $rate['nprtva'] ? '*': ''; - if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')'; - if ($mode < 0) $key = $rate['rowid']; + // Define key to use into select list + $key = $rate['txtva']; + $key.= $rate['nprtva'] ? '*': ''; + if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')'; + if ($mode < 0) $key = $rate['rowid']; - $return.= ''; - } + $return.= ''; + } - if (! $options_only) $return.= ''; - } - else - { - $return.= $this->error; - } + if (! $options_only) $return.= ''; + } + else + { + $return.= $this->error; + } - $this->num = $num; - return $return; - } + $this->num = $num; + return $return; + } - /** - * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. - * Fields are preselected with : - * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') - * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) - * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1) - * - * @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 $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 - * @param int $d 1=Show days, month, years - * @param int $addnowlink Add a link "Now" - * @param int $nooutput Do not output html string but return it - * @param int $disabled Disable input fields - * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59 - * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field. - * @param datetime $adddateof Add a link "Date of invoice" using the following date. - * @return string|null Nothing or string if nooutput is 1 - * @see form_date - */ - function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='') - { - global $conf,$langs; + /** + * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes. + * Fields are preselected with : + * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM') + * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location) + * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1) + * + * @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 $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 + * @param int $d 1=Show days, month, years + * @param int $addnowlink Add a link "Now" + * @param int $nooutput Do not output html string but return it + * @param int $disabled Disable input fields + * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59 + * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field. + * @param datetime $adddateof Add a link "Date of invoice" using the following date. + * @return string|null Nothing or string if nooutput is 1 + * @see form_date + */ + function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='') + { + global $conf,$langs; - $retstring=''; + $retstring=''; - if($prefix=='') $prefix='re'; - if($h == '') $h=0; - if($m == '') $m=0; - $emptydate=0; - $emptyhours=0; - if ($empty == 1) { $emptydate=1; $emptyhours=1; } - if ($empty == 2) { $emptydate=0; $emptyhours=1; } + if($prefix=='') $prefix='re'; + if($h == '') $h=0; + if($m == '') $m=0; + $emptydate=0; + $emptyhours=0; + if ($empty == 1) { $emptydate=1; $emptyhours=1; } + if ($empty == 2) { $emptydate=0; $emptyhours=1; } $orig_set_time=$set_time; - if ($set_time === '' && $emptydate == 0) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone - } + if ($set_time === '' && $emptydate == 0) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone + } - // Analysis of the pre-selection date - if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg)) - { - // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' - $syear = (! empty($reg[1])?$reg[1]:''); - $smonth = (! empty($reg[2])?$reg[2]:''); - $sday = (! empty($reg[3])?$reg[3]:''); - $shour = (! empty($reg[4])?$reg[4]:''); - $smin = (! empty($reg[5])?$reg[5]:''); - } - elseif (strval($set_time) != '' && $set_time != -1) - { - // set_time est un timestamps (0 possible) - $syear = dol_print_date($set_time, "%Y"); - $smonth = dol_print_date($set_time, "%m"); - $sday = dol_print_date($set_time, "%d"); - if ($orig_set_time != '') - { - $shour = dol_print_date($set_time, "%H"); - $smin = dol_print_date($set_time, "%M"); - } - } - else - { - // Date est '' ou vaut -1 - $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; - } + // Analysis of the pre-selection date + if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg)) + { + // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' + $syear = (! empty($reg[1])?$reg[1]:''); + $smonth = (! empty($reg[2])?$reg[2]:''); + $sday = (! empty($reg[3])?$reg[3]:''); + $shour = (! empty($reg[4])?$reg[4]:''); + $smin = (! empty($reg[5])?$reg[5]:''); + } + elseif (strval($set_time) != '' && $set_time != -1) + { + // set_time est un timestamps (0 possible) + $syear = dol_print_date($set_time, "%Y"); + $smonth = dol_print_date($set_time, "%m"); + $sday = dol_print_date($set_time, "%d"); + if ($orig_set_time != '') + { + $shour = dol_print_date($set_time, "%H"); + $smin = dol_print_date($set_time, "%M"); + $ssec = dol_print_date($set_time, "%S"); + } + } + else + { + // Date est '' ou vaut -1 + $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; + $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? '' : $conf->global->MAIN_DEFAULT_DATE_SEC; + } - // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' - $usecalendar='combo'; - if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) $usecalendar=empty($conf->global->MAIN_POPUP_CALENDAR)?'jquery':$conf->global->MAIN_POPUP_CALENDAR; + // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' + $usecalendar='combo'; + if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) { + $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR); + } //if (! empty($conf->browser->phone)) $usecalendar='combo'; - if ($d) - { - // Show date with popup - if ($usecalendar != 'combo') - { - $formated_date=''; - //print "e".$set_time." t ".$conf->format_date_short; - if (strval($set_time) != '' && $set_time != -1) - { - //$formated_date=dol_print_date($set_time,$conf->format_date_short); - $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - } + if ($d) + { + // Show date with popup + if ($usecalendar != 'combo') + { + $formated_date=''; + //print "e".$set_time." t ".$conf->format_date_short; + if (strval($set_time) != '' && $set_time != -1) + { + //$formated_date=dol_print_date($set_time,$conf->format_date_short); + $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + } - // Calendrier popup version eldy - if ($usecalendar == "eldy") - { - // Zone de saisie manuelle de la date - $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - $retstring.='>'; + // Calendrier popup version eldy + if ($usecalendar == "eldy") + { + // Zone de saisie manuelle de la date + $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $retstring.='>'; - // Icone calendrier - if (! $disabled) - { - $retstring.=''; - } - else $retstring.=''; + // Icone calendrier + if (! $disabled) + { + $retstring.=''; + } + else $retstring.=''; - $retstring.=''."\n"; - $retstring.=''."\n"; - $retstring.=''."\n"; - } - elseif ($usecalendar == 'jquery') - { - if (! $disabled) - { - $retstring.=""; - } + $retstring.=""; + } - // Zone de saisie manuelle de la date - $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript - $retstring.='>'; + // Zone de saisie manuelle de la date + $retstring.='trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript + $retstring.='>'; - // Icone calendrier - if (! $disabled) - { - /* Not required. Managed by option buttonImage of jquery + // Icone calendrier + if (! $disabled) + { + /* Not required. Managed by option buttonImage of jquery $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"'); $retstring.="";*/ - } - else - { - $retstring.=''; - } + } + else + { + $retstring.=''; + } - $retstring.=''."\n"; - $retstring.=''."\n"; - $retstring.=''."\n"; - } - else - { - $retstring.="Bad value of MAIN_POPUP_CALENDAR"; - } - } - // Show date with combo selects - else + $retstring.=''."\n"; + $retstring.=''."\n"; + $retstring.=''."\n"; + } + else + { + $retstring.="Bad value of MAIN_POPUP_CALENDAR"; + } + } + // Show date with combo selects + else { - //$retstring.='
      '; - // Day - $retstring.=''; + //$retstring.='
      '; + // Day + $retstring.=''; - if ($emptydate || $set_time == -1) - { - $retstring.=''; - } + if ($emptydate || $set_time == -1) + { + $retstring.=''; + } - for ($day = 1 ; $day <= 31; $day++) - { - $retstring.=''; - } + for ($day = 1 ; $day <= 31; $day++) + { + $retstring.=''; + } - $retstring.=""; + $retstring.=""; - $retstring.=''; - if ($emptydate || $set_time == -1) - { - $retstring.=''; - } + $retstring.=''; + if ($emptydate || $set_time == -1) + { + $retstring.=''; + } - // Month - for ($month = 1 ; $month <= 12 ; $month++) - { - $retstring.='"; - } - $retstring.=""; + // Month + for ($month = 1 ; $month <= 12 ; $month++) + { + $retstring.='"; + } + $retstring.=""; - // Year - if ($emptydate || $set_time == -1) - { - $retstring.=''; - } - else - { - $retstring.=''; + // Year + if ($emptydate || $set_time == -1) + { + $retstring.=''; + } + else + { + $retstring.=''; - for ($year = $syear - 10; $year < $syear + 10 ; $year++) - { - $retstring.=''; - } - $retstring.="\n"; - } - //$retstring.='
      '; - } - } + for ($year = $syear - 10; $year < $syear + 10 ; $year++) + { + $retstring.=''; + } + $retstring.="\n"; + } + //$retstring.='
      '; + } + } - if ($d && $h) $retstring.=($h==2?'
      ':' '); + if ($d && $h) $retstring.=($h==2?'
      ':' '); - if ($h) - { - // Show hour - $retstring.=''; - if ($emptyhours) $retstring.=''; - for ($hour = 0; $hour < 24; $hour++) - { - if (strlen($hour) < 2) $hour = "0" . $hour; - $retstring.=''; - } - $retstring.=''; - if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":"; - } + if ($h) + { + // Show hour + $retstring.=''; + if ($emptyhours) $retstring.=''; + for ($hour = 0; $hour < 24; $hour++) + { + if (strlen($hour) < 2) $hour = "0" . $hour; + $retstring.=''; + } + $retstring.=''; + if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":"; + } - if ($m) - { - // Show minutes - $retstring.=''; - if ($emptyhours) $retstring.=''; - for ($min = 0; $min < 60 ; $min++) - { - if (strlen($min) < 2) $min = "0" . $min; - $retstring.=''; - } - $retstring.=''; - } + if ($m) + { + // Show minutes + $retstring.=''; + if ($emptyhours) $retstring.=''; + for ($min = 0; $min < 60 ; $min++) + { + if (strlen($min) < 2) $min = "0" . $min; + $retstring.=''; + } + $retstring.=''; - // Add a "Now" link - if ($conf->use_javascript_ajax && $addnowlink) - { - // Script which will be inserted in the onClick of the "Now" link - $reset_scripts = ""; + $retstring.=''; + } - // Generate the date part, depending on the use or not of the javascript calendar - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; - /*if ($usecalendar == "eldy") + // Add a "Now" link + if ($conf->use_javascript_ajax && $addnowlink) + { + // Script which will be inserted in the onClick of the "Now" link + $reset_scripts = ""; + + // Generate the date part, depending on the use or not of the javascript calendar + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; + /*if ($usecalendar == "eldy") { $base=DOL_URL_ROOT.'/core/'; $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');'; @@ -4929,306 +4960,306 @@ class Form $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); '; $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); '; }*/ - // Update the hour part - if ($h) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { - $retstring.=' '; - } - } + // Update the hour part + if ($h) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // Update the minute part + if ($m) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // If reset_scripts is not empty, print the link with the reset_scripts in the onClick + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) + { + $retstring.=' '; + } + } - // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $addplusone) - { - // Script which will be inserted in the onClick of the "Add plusone" link - $reset_scripts = ""; + // Add a "Plus one hour" link + if ($conf->use_javascript_ajax && $addplusone) + { + // Script which will be inserted in the onClick of the "Add plusone" link + $reset_scripts = ""; - // Generate the date part, depending on the use or not of the javascript calendar - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; - // Update the hour part - if ($h) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; - $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; - if ($fullday) $reset_scripts .= ' } '; - } - // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { - $retstring.=' '; - } - } + // Generate the date part, depending on the use or not of the javascript calendar + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');'; + // Update the hour part + if ($h) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // Update the minute part + if ($m) + { + if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');'; + if ($fullday) $reset_scripts .= ' } '; + } + // If reset_scripts is not empty, print the link with the reset_scripts in the onClick + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) + { + $retstring.=' '; + } + } - // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $adddateof) - { - $tmparray=dol_getdate($adddateof); - $retstring.=' -
    '; - } - 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; @@ -935,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')); @@ -979,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 @@ -999,10 +1001,10 @@ class FormFile print ''."\n"; if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline) { - print '
    '; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; } print '
    '; @@ -1036,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); @@ -1057,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 ''; @@ -1079,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"; @@ -1103,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 ''; } @@ -1118,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"; @@ -1197,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; @@ -1209,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; @@ -1224,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 3e09c1a83e8..a9ebafc4769 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -34,20 +34,20 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php'; */ class FormMail extends Form { - var $db; + var $db; - var $withform; // 1=Include HTML form tag and show submit button, 0=Do not include form tag and submit button, -1=Do not include form tag but include submit button + var $withform; // 1=Include HTML form tag and show submit button, 0=Do not include form tag and submit button, -1=Do not include form tag but include submit button - var $fromname; - var $frommail; - var $replytoname; - var $replytomail; - var $toname; - var $tomail; + var $fromname; + var $frommail; + var $replytoname; + var $replytomail; + var $toname; + var $tomail; var $trackid; - var $withsubstit; // Show substitution array - var $withfrom; + var $withsubstit; // Show substitution array + var $withfrom; /** * @var int * @deprecated Fill withto with array before calling method. @@ -57,231 +57,221 @@ class FormMail extends Form /** * @var int|int[] */ - public $withto; // Show recipient emails - var $withtofree; // Show free text for recipient emails - var $withtocc; - var $withtoccc; - var $withtopic; - var $withfile; // 0=No attaches files, 1=Show attached files, 2=Can add new attached files - var $withmaindocfile; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) - var $withbody; + public $withto; // Show recipient emails + var $withtofree; // Show free text for recipient emails + var $withtocc; + var $withtoccc; + var $withtopic; + var $withfile; // 0=No attaches files, 1=Show attached files, 2=Can add new attached files + var $withmaindocfile; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) + var $withbody; - var $withfromreadonly; - var $withreplytoreadonly; - var $withtoreadonly; - var $withtoccreadonly; + var $withfromreadonly; + var $withreplytoreadonly; + var $withtoreadonly; + var $withtoccreadonly; var $withtocccreadonly; var $withtopicreadonly; - var $withfilereadonly; - var $withdeliveryreceipt; - var $withcancel; - var $withfckeditor; + var $withfilereadonly; + var $withdeliveryreceipt; + var $withcancel; + var $withfckeditor; - var $substit=array(); - var $substit_lines=array(); - var $param=array(); + var $substit=array(); + var $substit_lines=array(); + var $param=array(); - var $error; + var $error; - public $lines_model; + public $lines_model; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; - $this->withform=1; + $this->withform=1; - $this->withfrom=1; - $this->withto=1; - $this->withtofree=1; - $this->withtocc=1; - $this->withtoccc=0; - $this->witherrorsto=0; - $this->withtopic=1; - $this->withfile=0; // 1=Add section "Attached files". 2=Can add files. - $this->withmaindocfile=0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) - $this->withbody=1; + $this->withfrom=1; + $this->withto=1; + $this->withtofree=1; + $this->withtocc=1; + $this->withtoccc=0; + $this->witherrorsto=0; + $this->withtopic=1; + $this->withfile=0; // 1=Add section "Attached files". 2=Can add files. + $this->withmaindocfile=0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default) + $this->withbody=1; - $this->withfromreadonly=1; - $this->withreplytoreadonly=1; - $this->withtoreadonly=0; - $this->withtoccreadonly=0; - $this->withtocccreadonly=0; - $this->witherrorstoreadonly=0; - $this->withtopicreadonly=0; - $this->withfilereadonly=0; - $this->withbodyreadonly=0; - $this->withdeliveryreceiptreadonly=0; - $this->withfckeditor=-1; // -1 = Auto + $this->withfromreadonly=1; + $this->withreplytoreadonly=1; + $this->withtoreadonly=0; + $this->withtoccreadonly=0; + $this->withtocccreadonly=0; + $this->witherrorstoreadonly=0; + $this->withtopicreadonly=0; + $this->withfilereadonly=0; + $this->withbodyreadonly=0; + $this->withdeliveryreceiptreadonly=0; + $this->withfckeditor=-1; // -1 = Auto - return 1; - } + return 1; + } - /** - * Clear list of attached files in send mail form (also stored in session) - * - * @return void - */ - function clear_attached_files() - { - global $conf,$user; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Clear list of attached files in send mail form (also stored in session) + * + * @return void + */ + function clear_attached_files() + { + global $conf,$user; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - // Set tmp user directory - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path - if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir); + // Set tmp user directory + $vardir=$conf->user->dir_output."/".$user->id; + $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path + if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir); - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - unset($_SESSION["listofpaths".$keytoavoidconflict]); - unset($_SESSION["listofnames".$keytoavoidconflict]); - unset($_SESSION["listofmimes".$keytoavoidconflict]); - } + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + unset($_SESSION["listofpaths".$keytoavoidconflict]); + unset($_SESSION["listofnames".$keytoavoidconflict]); + unset($_SESSION["listofmimes".$keytoavoidconflict]); + } - /** - * Add a file into the list of attached files (stored in SECTION array) - * - * @param string $path Full absolute path on filesystem of file, including file name - * @param string $file Only filename - * @param string $type Mime type - * @return void - */ - function add_attached_files($path,$file,$type) - { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); + /** + * Add a file into the list of attached files (stored in SECTION array) + * + * @param string $path Full absolute path on filesystem of file, including file name + * @param string $file Only filename + * @param string $type Mime type + * @return void + */ + function add_attached_files($path,$file,$type) + { + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - 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]); - if (! in_array($file,$listofnames)) - { - $listofpaths[]=$path; - $listofnames[]=$file; - $listofmimes[]=$type; - $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); - $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); - $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); - } - } - - /** - * Remove a file from the list of attached files (stored in SECTION array) - * - * @param string $keytodelete Key in file array (0, 1, 2, ...) - * @return void - */ - function remove_attached_files($keytodelete) - { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - 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]); - if ($keytodelete >= 0) - { - unset ($listofpaths[$keytodelete]); - unset ($listofnames[$keytodelete]); - unset ($listofmimes[$keytodelete]); - $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); - $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); - $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); - //var_dump($_SESSION['listofpaths']); - } - } - - /** - * Return list of attached files (stored in SECTION array) - * - * @return array array('paths'=> ,'names'=>, 'mimes'=> ) - */ - function get_attached_files() - { - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - 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]); - return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes); - } - - /** - * Show the form to input an email - * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files - * this->withmaindocfile - * - * @param string $addfileaction Name of action when posting file attachments - * @param string $removefileaction Name of action when removing file attachments - * @return void - */ - function show_form($addfileaction='addfile',$removefileaction='removefile') - { - print $this->get_form($addfileaction,$removefileaction); - } - - /** - * Get the form to input an email - * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files - * this->withfile - * this->param: Contains more parameteres like email templates info - * - * @param string $addfileaction Name of action when posting file attachments - * @param string $removefileaction Name of action when removing file attachments - * @return string Form to show - */ - function get_form($addfileaction='addfile',$removefileaction='removefile') - { - global $conf, $langs, $user, $hookmanager, $form; - - if (! is_object($form)) $form=new Form($this->db); - - $langs->load("other"); - $langs->load("mails"); - - $hookmanager->initHooks(array('formmail')); - - $parameters=array( - 'addfileaction' => $addfileaction, - 'removefileaction'=> $removefileaction, - 'trackid'=> $this->trackid - ); - $reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this); - - if (!empty($reshook)) - { - return $hookmanager->resPrint; - } - else + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + 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]); + if (! in_array($file,$listofnames)) { - $out=''; + $listofpaths[]=$path; + $listofnames[]=$file; + $listofmimes[]=$type; + $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); + $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); + $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); + } + } - $disablebademails=1; + /** + * Remove a file from the list of attached files (stored in SECTION array) + * + * @param string $keytodelete Key in file array (0, 1, 2, ...) + * @return void + */ + function remove_attached_files($keytodelete) + { + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); - // Define list of attached files - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + 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]); + if ($keytodelete >= 0) + { + unset ($listofpaths[$keytodelete]); + unset ($listofnames[$keytodelete]); + unset ($listofmimes[$keytodelete]); + $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); + $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); + $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); + //var_dump($_SESSION['listofpaths']); + } + } - 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]); + /** + * Return list of attached files (stored in SECTION array) + * + * @return array array('paths'=> ,'names'=>, 'mimes'=> ) + */ + function get_attached_files() + { + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); - // Define output language + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + 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]); + return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes); + } + + /** + * Show the form to input an email + * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files + * this->withmaindocfile + * + * @param string $addfileaction Name of action when posting file attachments + * @param string $removefileaction Name of action when removing file attachments + * @return void + */ + function show_form($addfileaction='addfile',$removefileaction='removefile') + { + print $this->get_form($addfileaction,$removefileaction); + } + + /** + * Get the form to input an email + * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files + * this->withfile + * this->param: Contains more parameteres like email templates info + * + * @param string $addfileaction Name of action when posting file attachments + * @param string $removefileaction Name of action when removing file attachments + * @return string Form to show + */ + function get_form($addfileaction='addfile',$removefileaction='removefile') + { + global $conf, $langs, $user, $hookmanager, $form; + + if (! is_object($form)) $form=new Form($this->db); + + $langs->load("other"); + $langs->load("mails"); + + $hookmanager->initHooks(array('formmail')); + + $parameters=array( + 'addfileaction' => $addfileaction, + 'removefileaction'=> $removefileaction, + 'trackid'=> $this->trackid + ); + $reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this); + + if (!empty($reshook)) + { + return $hookmanager->resPrint; + } + else + { + $out=''; + + $disablebademails=1; + + // Define output language $outputlangs = $langs; $newlang = ''; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $this->param['langsmodels']; @@ -292,540 +282,590 @@ 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); - } - //var_dump($this->param["models"]); - //var_dump($model_id); - //var_dump($arraydefaultmessage); - - $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"; - } - - if ($this->param['models'] != 'none') - { - $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); - if ($result < 0) - { - setEventMessages($this->error, $this->errors, 'errors'); - } - $modelmail_array=array(); - 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','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)) - { - // 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(); - if (empty($user->email)) - { - $langs->load('errors'); - $liste['user'] = $user->getFullName($langs) . ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'>'; - } - else - { - $liste['user'] = $user->getFullName($langs) .' <'.$user->email.'>'; - } - $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; - // Add also email aliases if there is one - $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); - 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); // Deal with format differences between message and signature (text / HTML) - if(dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__SIGNATURE__'])) { - $this->substit['__SIGNATURE__'] = dol_nl2br($this->substit['__SIGNATURE__']); - } else if(!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__SIGNATURE__'])) { + if(dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__USER_SIGNATURE__'])) { + $this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']); + } else if(!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__USER_SIGNATURE__'])) { $defaultmessage = dol_nl2br($defaultmessage); } - if (isset($_POST["message"]) && ! $_POST['modelselected']) $defaultmessage=$_POST["message"]; + if (isset($_POST["message"]) && ! $_POST['modelselected']) $defaultmessage=$_POST["message"]; else { $defaultmessage=make_substitutions($defaultmessage,$this->substit); @@ -834,59 +874,59 @@ class FormMail extends Form $defaultmessage=preg_replace("/^\n+/","",$defaultmessage); } - $out.= ''; - $out.= ''; - $out.= ''; + $out.= ''; + $out.= '\n"; - } + $doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,'95%'); + $out.= $doleditor->Create(1); + } + $out.= "\n"; + } - $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%"); + } } - $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("MailText").''; - if ($this->withbodyreadonly) - { - $out.= nl2br($defaultmessage); - $out.= ''; - } - else - { - if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes'; + $out.= '
    '.$langs->trans("MailText").''; + if ($this->withbodyreadonly) + { + $out.= nl2br($defaultmessage); + $out.= ''; + } + else + { + if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes'; - // Editor wysiwyg - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - if ($this->withfckeditor == -1) - { - if (! empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $this->withfckeditor=1; + // Editor wysiwyg + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + if ($this->withfckeditor == -1) + { + if (! empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $this->withfckeditor=1; else $this->withfckeditor=0; - } + } - $doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,'95%'); - $out.= $doleditor->Create(1); - } - $out.= "
    '."\n"; + $out.= ''."\n"; - if ($this->withform == 1 || $this->withform == -1) - { - $out.= '
    '; - $out.= 'withfile == 2 && $conf->use_javascript_ajax) - { - $out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"'; - } - $out.= ' />'; - if ($this->withcancel) - { - $out.= '     '; - $out.= ''; - } - $out.= '
    '."\n"; - } + if ($this->withform == 1 || $this->withform == -1) + { + $out.= '
    '; + $out.= 'withfile == 2 && $conf->use_javascript_ajax) + { + $out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"'; + } + $out.= ' />'; + if ($this->withcancel) + { + $out.= '     '; + $out.= ''; + } + $out.= '
    '."\n"; + } - if ($this->withform == 1) $out.= '
    '."\n"; + if ($this->withform == 1) $out.= ''."\n"; - // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set - if (! empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) - { - $out.= ''; - } + } - $out.= "\n"; + $out.= "\n"; - return $out; - } - } + return $out; + } + } /** - * Return templates of email with type = $type_template or type = 'all' - * This search into table c_email_templates. + * Return templates of email with type = $type_template or type = 'all'. + * This search into table c_email_templates. Used by the get_form function. * * @param DoliDB $db Database handler * @param string $type_template Get message for type=$type_template, type='all' also included. * @param string $user Use template public or limited to this user * @param Translate $outputlangs Output lang object - * @param int $id Id template to find + * @param int $id Id of template to find, or -1 for first found with position = 0, or 0 for all * @param int $active 1=Only active template, 0=Only disabled, -1=All * @return array array('topic'=>,'content'=>,..) */ - private function getEMailTemplate($db, $type_template, $user, $outputlangs, $id=0, $active=1) + public function getEMailTemplate($db, $type_template, $user, $outputlangs, $id=0, $active=1) { $ret=array(); - $sql = "SELECT label, topic, content, content_lines, lang"; + $sql = "SELECT label, topic, joinfiles, content, content_lines, lang"; $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates'; $sql.= " WHERE (type_template='".$db->escape($type_template)."' OR type_template='all')"; $sql.= " AND entity IN (".getEntity('c_email_templates', 0).")"; $sql.= " AND (private = 0 OR fk_user = ".$user->id.")"; // Get all public or private owned if ($active >= 0) $sql.=" AND active = ".$active; if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')"; - if (!empty($id)) $sql.= " AND rowid=".$id; + if ($id > 0) $sql.= " AND rowid=".$id; + if ($id == -1) $sql.= " AND position=0"; $sql.= $db->order("position,lang,label","ASC"); + if ($id == -1) $sql.= $db->plimit(1); //print $sql; $resql = $db->query($sql); @@ -940,31 +982,33 @@ class FormMail extends Form if ($obj) { $ret['label']=$obj->label; + $ret['lang']=$obj->lang; $ret['topic']=$obj->topic; + $ret['joinfiles']=$obj->joinfiles; $ret['content']=$obj->content; $ret['content_lines']=$obj->content_lines; - $ret['lang']=$obj->lang; } else // If there is no template at all { $defaultmessage=''; if ($type_template=='facture_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoice"); } - elseif ($type_template=='facture_relance') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); } - elseif ($type_template=='propal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); } - elseif ($type_template=='supplier_proposal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); } - elseif ($type_template=='order_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); } - elseif ($type_template=='order_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); } - elseif ($type_template=='invoice_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); } - elseif ($type_template=='shipping_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); } - elseif ($type_template=='fichinter_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); } - elseif ($type_template=='thirdparty') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); } - elseif ($type_template=='user') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); } + elseif ($type_template=='facture_relance') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); } + elseif ($type_template=='propal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); } + elseif ($type_template=='supplier_proposal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); } + elseif ($type_template=='order_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); } + elseif ($type_template=='order_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); } + elseif ($type_template=='invoice_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); } + elseif ($type_template=='shipping_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); } + elseif ($type_template=='fichinter_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); } + elseif ($type_template=='thirdparty') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); } + elseif ($type_template=='user') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); } - $ret['label']='default'; - $ret['topic']=''; - $ret['content']=$defaultmessage; + $ret['label']='default'; + $ret['lang']=$outputlangs->defaultlang; + $ret['topic']=''; + $ret['joinfiles']=1; + $ret['content']=$defaultmessage; $ret['content_lines']=''; - $ret['lang']=$outputlangs->defaultlang; } $db->free($resql); @@ -1076,51 +1120,51 @@ class FormMail extends Form * @return void * @see getCommonSubstitutionArray */ - function setSubstitFromObject($object, $outputlangs=null) + function setSubstitFromObject($object, $outputlangs) { global $conf, $user; - $parameters=array('mode'=>$mode); + $parameters=array(); $tmparray=getCommonSubstitutionArray($outputlangs, 0, null, $object); complete_substitutions_array($tmparray, $outputlangs, null, $parameters); $this->substit=$tmparray; - // Fill substit_lines with each object lines content - if (is_array($object->lines)) - { - foreach ($object->lines as $line) - { - $substit_line = array( - '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '', - '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '', - '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '', - '__LABEL__' => isset($line->label) ? $line->label : '', - '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '', - '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs), - '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs), - '__QUANTITY__' => $line->qty, - '__SUBPRICE__' => price($line->subprice), - '__AMOUNT__' => price($line->total_ttc), - '__AMOUNT_EXCL_TAX__' => price($line->total_ht), - //'__PRODUCT_EXTRAFIELD_FIELD__' Done dinamically just after - ); + // Fill substit_lines with each object lines content + if (is_array($object->lines)) + { + foreach ($object->lines as $line) + { + $substit_line = array( + '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '', + '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '', + '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '', + '__LABEL__' => isset($line->label) ? $line->label : '', + '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '', + '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs), + '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs), + '__QUANTITY__' => $line->qty, + '__SUBPRICE__' => price($line->subprice), + '__AMOUNT__' => price($line->total_ttc), + '__AMOUNT_EXCL_TAX__' => price($line->total_ht), + //'__PRODUCT_EXTRAFIELD_FIELD__' Done dinamically just after + ); - // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__ - if (!empty($line->fk_product)) - { - $extrafields = new ExtraFields($this->db); - $extralabels = $extrafields->fetch_name_optionals_label('product', true); - $product = new Product($this->db); - $product->fetch($line->fk_product, '', '', 1); - $product->fetch_optionals($product->id, $extralabels); - foreach ($extrafields->attribute_label as $key => $label) { - $substit_line['__PRODUCT_EXTRAFIELD_' . strtoupper($key) . '__'] = $product->array_options['options_' . $key]; - } - } - $this->substit_lines[] = $substit_line; - } - } + // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__ + if (!empty($line->fk_product)) + { + $extrafields = new ExtraFields($this->db); + $extralabels = $extrafields->fetch_name_optionals_label('product', true); + $product = new Product($this->db); + $product->fetch($line->fk_product, '', '', 1); + $product->fetch_optionals($product->id, $extralabels); + foreach ($extrafields->attribute_label as $key => $label) { + $substit_line['__PRODUCT_EXTRAFIELD_' . strtoupper($key) . '__'] = $product->array_options['options_' . $key]; + } + } + $this->substit_lines[] = $substit_line; + } + } } /** @@ -1135,6 +1179,7 @@ class FormMail extends Form { global $conf, $langs; + $tmparray=array(); if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines') { $parameters=array('mode'=>$mode); @@ -1143,11 +1188,11 @@ class FormMail extends Form if ($mode == 'formwithlines') { - $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function + $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function } if ($mode == 'formforlines') { - $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function + $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function } } @@ -1168,7 +1213,7 @@ class FormMail extends Form $tmparray['__OTHER3__'] = 'Other3'; $tmparray['__OTHER4__'] = 'Other4'; $tmparray['__OTHER5__'] = 'Other5'; - $tmparray['__SIGNATURE__'] = 'TagSignature'; + $tmparray['__USER_SIGNATURE__'] = 'TagSignature'; $tmparray['__CHECK_READ__'] = 'TagCheckMail'; $tmparray['__UNSUBSCRIBE__'] = 'TagUnsubscribe'; //,'__PERSONALIZED__' => 'Personalized' // Hidden because not used yet in mass emailing diff --git a/htdocs/core/class/ldap.class.php b/htdocs/core/class/ldap.class.php index 64e6f9fd5ef..20a9b85cf86 100644 --- a/htdocs/core/class/ldap.class.php +++ b/htdocs/core/class/ldap.class.php @@ -92,8 +92,8 @@ class Ldap /** - * The internal LDAP connection handle - */ + * The internal LDAP connection handle + */ var $connection; /** * Result of any connections etc. @@ -402,10 +402,10 @@ class Ldap * Add a LDAP entry * Ldap object connect and bind must have been done * - * @param string $dn DN entry key - * @param array $info Attributes array + * @param string $dn DN entry key + * @param array $info Attributes array * @param User $user Objet user that create - * @return int <0 if KO, >0 if OK + * @return int <0 if KO, >0 if OK */ function add($dn, $info, $user) { @@ -458,7 +458,7 @@ class Ldap * * @param string $dn DN entry key * @param array $info Attributes array - * @param string $user Objet user that modify + * @param User $user Objet user that modify * @return int <0 if KO, >0 if OK */ function modify($dn, $info, $user) @@ -504,17 +504,69 @@ class Ldap } } + /** + * Rename a LDAP entry + * Ldap object connect and bind must have been done + * + * @param string $dn Old DN entry key (uid=qqq,ou=xxx,dc=aaa,dc=bbb) (before update) + * @param string $newrdn New RDN entry key (uid=qqq) + * @param string $newparent New parent (ou=xxx,dc=aaa,dc=bbb) + * @param User $user Objet user that modify + * @param bool $deleteoldrdn If TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. + * @return int <0 if KO, >0 if OK + */ + function rename($dn, $newrdn, $newparent, $user, $deleteoldrdn = true) + { + global $conf; + + dol_syslog(get_class($this)."::modify dn=".$dn." newrdn=".$newrdn." newparent=".$newparent." deleteoldrdn=".($deleteoldrdn?1:0)); + + // Check parameters + if (! $this->connection) + { + $this->error="NotConnected"; + return -2; + } + if (! $this->bind) + { + $this->error="NotConnected"; + return -3; + } + + // Encode to LDAP page code + $dn=$this->convFromOutputCharset($dn,$this->ldapcharset); + $newrdn=$this->convFromOutputCharset($newrdn,$this->ldapcharset); + $newparent=$this->convFromOutputCharset($newparent,$this->ldapcharset); + + //print_r($info); + $result=@ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn); + + if ($result) + { + dol_syslog(get_class($this)."::rename successfull", LOG_DEBUG); + return 1; + } + else + { + $this->error=@ldap_error($this->connection); + dol_syslog(get_class($this)."::rename failed: ".$this->error, LOG_ERR); + return -1; + } + } + /** * Modify a LDAP entry (to use if dn != olddn) * Ldap object connect and bind must have been done * - * @param string $dn DN entry key - * @param array $info Attributes array - * @param User $user Objet user that update - * @param string $olddn Old DN entry key (before update) - * @return int <0 if KO, >0 if OK + * @param string $dn DN entry key + * @param array $info Attributes array + * @param User $user Objet user that update + * @param string $olddn Old DN entry key (before update) + * @param string $newrdn New RDN entry key (uid=qqq) (for ldap_rename) + * @param string $newparent New parent (ou=xxx,dc=aaa,dc=bbb) (for ldap_rename) + * @return int <0 if KO, >0 if OK */ - function update($dn,$info,$user,$olddn) + function update($dn, $info, $user, $olddn, $newrdn=false, $newparent=false) { global $conf; @@ -534,9 +586,17 @@ class Ldap if (! $olddn || $olddn != $dn) { - // If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one. - $result = $this->add($dn, $info, $user); - if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn); // If add fails, we do not try to delete old one + if (! empty($olddn) && ! empty($newrdn) && ! empty($newparent) && $conf->global->LDAP_SERVER_PROTOCOLVERSION === '3') + { + // This function currently only works with LDAPv3 + $result = $this->rename($olddn, $newrdn, $newparent, $user, true); + } + else + { + // If change we make is rename the key of LDAP record, we create new one and if ok, we delete old one. + $result = $this->add($dn, $info, $user); + if ($result > 0 && $olddn && $olddn != $dn) $result = $this->delete($olddn); // If add fails, we do not try to delete old one + } } else { @@ -689,7 +749,7 @@ class Ldap // Attribute methods ----------------------------------------------------- - /** + /** * Add a LDAP attribute in entry * Ldap object connect and bind must have been done * @@ -741,7 +801,7 @@ class Ldap } } - /** + /** * Update a LDAP attribute in entry * Ldap object connect and bind must have been done * @@ -793,7 +853,7 @@ class Ldap } } - /** + /** * Delete a LDAP attribute in entry * Ldap object connect and bind must have been done * @@ -845,7 +905,7 @@ class Ldap } } - /** + /** * Returns an array containing attributes and values for first record * * @param string $dn DN entry key @@ -1202,7 +1262,7 @@ class Ldap $i=0; while ($i <= 2) { - dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter); + dol_syslog(get_class($this)."::fetch search with searchDN=".$searchDN." filter=".$filter); $this->result = @ldap_search($this->connection, $searchDN, $filter); if ($this->result) { @@ -1213,9 +1273,9 @@ class Ldap } else { - $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection); - dol_syslog(get_class($this)."::fetch search fails"); - return -1; + $this->error = ldap_errno($this->connection)." ".ldap_error($this->connection); + dol_syslog(get_class($this)."::fetch search fails"); + return -1; } if (! $result) @@ -1241,7 +1301,7 @@ class Ldap $this->firstname = $this->convToOutputCharset($result[0][$this->attr_firstname][0],$this->ldapcharset); $this->login = $this->convToOutputCharset($result[0][$this->attr_login][0],$this->ldapcharset); $this->phone = $this->convToOutputCharset($result[0][$this->attr_phone][0],$this->ldapcharset); - $this->skype = $this->convToOutputCharset($result[0][$this->attr_skype][0],$this->ldapcharset); + $this->skype = $this->convToOutputCharset($result[0][$this->attr_skype][0],$this->ldapcharset); $this->fax = $this->convToOutputCharset($result[0][$this->attr_fax][0],$this->ldapcharset); $this->mail = $this->convToOutputCharset($result[0][$this->attr_mail][0],$this->ldapcharset); $this->mobile = $this->convToOutputCharset($result[0][$this->attr_mobile][0],$this->ldapcharset); @@ -1264,7 +1324,7 @@ class Ldap $this->domainFQDN = $domain; // Set ldapUserDn (each user can have a different dn) - //var_dump($result[0]);exit; + //var_dump($result[0]);exit; $this->ldapUserDN=$result[0]['dn']; ldap_free_result($this->result); @@ -1290,35 +1350,37 @@ class Ldap } /** - * UserAccountControl Flgs to more human understandable form... - * - * @param string $uacf UACF - * @return void - */ + * UserAccountControl Flgs to more human understandable form... + * + * @param string $uacf UACF + * @return void + */ function parseUACF($uacf) { //All flags array - $flags = array( "TRUSTED_TO_AUTH_FOR_DELEGATION" => 16777216, - "PASSWORD_EXPIRED" => 8388608, - "DONT_REQ_PREAUTH" => 4194304, - "USE_DES_KEY_ONLY" => 2097152, - "NOT_DELEGATED" => 1048576, - "TRUSTED_FOR_DELEGATION" => 524288, - "SMARTCARD_REQUIRED" => 262144, - "MNS_LOGON_ACCOUNT" => 131072, - "DONT_EXPIRE_PASSWORD" => 65536, - "SERVER_TRUST_ACCOUNT" => 8192, - "WORKSTATION_TRUST_ACCOUNT" => 4096, - "INTERDOMAIN_TRUST_ACCOUNT" => 2048, - "NORMAL_ACCOUNT" => 512, - "TEMP_DUPLICATE_ACCOUNT" => 256, - "ENCRYPTED_TEXT_PWD_ALLOWED" => 128, - "PASSWD_CANT_CHANGE" => 64, - "PASSWD_NOTREQD" => 32, - "LOCKOUT" => 16, - "HOMEDIR_REQUIRED" => 8, - "ACCOUNTDISABLE" => 2, - "SCRIPT" => 1); + $flags = array( + "TRUSTED_TO_AUTH_FOR_DELEGATION" => 16777216, + "PASSWORD_EXPIRED" => 8388608, + "DONT_REQ_PREAUTH" => 4194304, + "USE_DES_KEY_ONLY" => 2097152, + "NOT_DELEGATED" => 1048576, + "TRUSTED_FOR_DELEGATION" => 524288, + "SMARTCARD_REQUIRED" => 262144, + "MNS_LOGON_ACCOUNT" => 131072, + "DONT_EXPIRE_PASSWORD" => 65536, + "SERVER_TRUST_ACCOUNT" => 8192, + "WORKSTATION_TRUST_ACCOUNT" => 4096, + "INTERDOMAIN_TRUST_ACCOUNT" => 2048, + "NORMAL_ACCOUNT" => 512, + "TEMP_DUPLICATE_ACCOUNT" => 256, + "ENCRYPTED_TEXT_PWD_ALLOWED" => 128, + "PASSWD_CANT_CHANGE" => 64, + "PASSWD_NOTREQD" => 32, + "LOCKOUT" => 16, + "HOMEDIR_REQUIRED" => 8, + "ACCOUNTDISABLE" => 2, + "SCRIPT" => 1 + ); //Parse flags to text $retval = array(); @@ -1334,20 +1396,22 @@ class Ldap } /** - * SamAccountType value to text - * - * @param string $samtype SamType - * @return string Sam string - */ + * SamAccountType value to text + * + * @param string $samtype SamType + * @return string Sam string + */ function parseSAT($samtype) { - $stypes = array( 805306368 => "NORMAL_ACCOUNT", - 805306369 => "WORKSTATION_TRUST", - 805306370 => "INTERDOMAIN_TRUST", - 268435456 => "SECURITY_GLOBAL_GROUP", - 268435457 => "DISTRIBUTION_GROUP", - 536870912 => "SECURITY_LOCAL_GROUP", - 536870913 => "DISTRIBUTION_LOCAL_GROUP"); + $stypes = array( + 805306368 => "NORMAL_ACCOUNT", + 805306369 => "WORKSTATION_TRUST", + 805306370 => "INTERDOMAIN_TRUST", + 268435456 => "SECURITY_GLOBAL_GROUP", + 268435457 => "DISTRIBUTION_GROUP", + 536870912 => "SECURITY_LOCAL_GROUP", + 536870913 => "DISTRIBUTION_LOCAL_GROUP" + ); $retval = ""; while (list($sat, $val) = each($stypes)) { @@ -1379,7 +1443,7 @@ class Ldap /** * Convert a string into output/memory charset - * + * * @param string $str String to convert * @param string $pagecodefrom Page code of src string * @return string Converted string @@ -1394,7 +1458,7 @@ class Ldap /** * Convert a string from output/memory charset - * + * * @param string $str String to convert * @param string $pagecodeto Page code for result string * @return string Converted string @@ -1422,7 +1486,7 @@ class Ldap $search='('.$conf->global->$keygroup.'=*)'; $result = $this->search($this->groups,$search); - if($result) + if ($result) { $c = $result['count']; $gids = array(); diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php index 6f2f9e56d61..d40fcadc17c 100644 --- a/htdocs/core/class/notify.class.php +++ b/htdocs/core/class/notify.class.php @@ -30,240 +30,241 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/CMailFile.class.php'; */ class Notify { - var $id; - var $db; - var $error; - var $errors=array(); + var $id; + var $db; + var $error; + var $errors=array(); - var $author; - var $ref; - var $date; - var $duree; - var $note; - var $fk_project; + var $author; + var $ref; + var $date; + var $duree; + var $note; + var $fk_project; // Les codes actions sont definis dans la table llx_notify_def - // codes actions supported are - public $arrayofnotifsupported = array( - 'BILL_VALIDATE', - 'BILL_PAYED', - 'ORDER_VALIDATE', - 'PROPAL_VALIDATE', - 'FICHINTER_VALIDATE', - 'FICHINTER_ADD_CONTACT', - 'ORDER_SUPPLIER_VALIDATE', - 'ORDER_SUPPLIER_APPROVE', - 'ORDER_SUPPLIER_REFUSE', - 'SHIPPING_VALIDATE' - ); + // codes actions supported are + public $arrayofnotifsupported = array( + 'BILL_VALIDATE', + 'BILL_PAYED', + 'ORDER_VALIDATE', + 'PROPAL_VALIDATE', + 'PROPAL_CLOSE_SIGNED', + 'FICHINTER_VALIDATE', + 'FICHINTER_ADD_CONTACT', + 'ORDER_SUPPLIER_VALIDATE', + 'ORDER_SUPPLIER_APPROVE', + 'ORDER_SUPPLIER_REFUSE', + 'SHIPPING_VALIDATE' + ); - - /** + + /** * Constructor * * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } + */ + function __construct($db) + { + $this->db = $db; + } - /** - * Return message that say how many notification (and to which email) will occurs on requested event. - * This is to show confirmation messages before event is recorded. - * - * @param string $action Id of action in llx_c_action_trigger - * @param int $socid Id of third party - * @param Object $object Object the notification is about - * @return string Message - */ + /** + * Return message that say how many notification (and to which email) will occurs on requested event. + * This is to show confirmation messages before event is recorded. + * + * @param string $action Id of action in llx_c_action_trigger + * @param int $socid Id of third party + * @param Object $object Object the notification is about + * @return string Message + */ function confirmMessage($action,$socid,$object) { global $langs; $langs->load("mails"); $listofnotiftodo=$this->getNotificationsArray($action,$socid,$object,0); - + $nb=-1; if (is_array($listofnotiftodo)) $nb=count($listofnotiftodo); if ($nb < 0) $texte=img_object($langs->trans("Notifications"),'email').' '.$langs->trans("ErrorFailedToGetListOfNotificationsToSend"); if ($nb == 0) $texte=img_object($langs->trans("Notifications"),'email').' '.$langs->trans("NoNotificationsWillBeSent"); if ($nb == 1) $texte=img_object($langs->trans("Notifications"),'email').' '.$langs->trans("ANotificationsWillBeSent"); if ($nb >= 2) $texte=img_object($langs->trans("Notifications"),'email').' '.$langs->trans("SomeNotificationsWillBeSent",$nb); - + if (is_array($listofnotiftodo)) { - $i=0; - foreach ($listofnotiftodo as $key => $val) - { - if ($i) $texte.=', '; - else $texte.=' ('; - if ($val['isemailvalid']) $texte.=$val['email']; - else $texte.=$val['emaildesc']; - $i++; - } - if ($i) $texte.=')'; + $i=0; + foreach ($listofnotiftodo as $key => $val) + { + if ($i) $texte.=', '; + else $texte.=' ('; + if ($val['isemailvalid']) $texte.=$val['email']; + else $texte.=$val['emaildesc']; + $i++; + } + if ($i) $texte.=')'; } - + return $texte; } - /** - * Return number of notifications activated for action code (and third party) - * - * @param string $notifcode Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage) - * @param int $socid Id of third party or 0 for all thirdparties or -1 for no thirdparties - * @param Object $object Object the notification is about (need it to check threshold value of some notifications) - * @param int $userid Id of user or 0 for all users or -1 for no users - * @param array $scope Scope where to search - * @return array|int <0 if KO, array of notifications to send if OK - */ + /** + * Return number of notifications activated for action code (and third party) + * + * @param string $notifcode Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage) + * @param int $socid Id of third party or 0 for all thirdparties or -1 for no thirdparties + * @param Object $object Object the notification is about (need it to check threshold value of some notifications) + * @param int $userid Id of user or 0 for all users or -1 for no users + * @param array $scope Scope where to search + * @return array|int <0 if KO, array of notifications to send if OK + */ function getNotificationsArray($notifcode, $socid=0, $object=null, $userid=0, $scope=array('thirdparty', 'user', 'global')) { global $conf, $user; $error=0; - $resarray=array(); + $resarray=array(); - $valueforthreshold = 0; - if (is_object($object)) $valueforthreshold = $object->total_ht; - - if (! $error) - { - if ($socid >= 0 && in_array('thirdparty', $scope)) - { - $sql = "SELECT a.code, c.email, c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n,"; - $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,"; - $sql.= " ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE n.fk_contact = c.rowid"; - $sql.= " AND a.rowid = n.fk_action"; - $sql.= " AND n.fk_soc = s.rowid"; - if ($notifcode) - { - if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage - else $sql.= " AND a.code = '".$notifcode."'"; // New usage - } - $sql.= " AND s.entity IN (".getEntity('societe').")"; - if ($socid > 0) $sql.= " AND s.rowid = ".$socid; - - dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG); - - $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) - { - $newval2=trim($obj->email); - $isvalid=isValidEmail($newval2); - if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'tocontact', 'code'=>trim($obj->code), 'emaildesc'=>'Contact id '.$obj->rowid, 'email'=>$newval2, 'contactid'=>$obj->rowid, 'isemailvalid'=>$isvalid); - } - $i++; - } - } - else - { - $error++; - $this->error=$this->db->lasterror(); - } - } - } - - if (! $error) - { - if ($userid >= 0 && in_array('user', $scope)) - { - $sql = "SELECT a.code, c.email, c.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n,"; - $sql.= " ".MAIN_DB_PREFIX."user as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a"; - $sql.= " WHERE n.fk_user = c.rowid"; - $sql.= " AND a.rowid = n.fk_action"; - if ($notifcode) - { - if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage - else $sql.= " AND a.code = '".$notifcode."'"; // New usage - } - $sql.= " AND c.entity IN (".getEntity('user').")"; - if ($userid > 0) $sql.= " AND c.rowid = ".$userid; - - dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG); - - $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) - { - $newval2=trim($obj->email); - $isvalid=isValidEmail($newval2); - if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'touser', 'code'=>trim($obj->code), 'emaildesc'=>'User id '.$obj->rowid, 'email'=>$newval2, 'userid'=>$obj->rowid, 'isemailvalid'=>$isvalid); - } - $i++; - } - } - else - { - $error++; - $this->error=$this->db->lasterror(); - } - } - } + $valueforthreshold = 0; + if (is_object($object)) $valueforthreshold = $object->total_ht; if (! $error) { - if (in_array('global', $scope)) - { - // List of notifications enabled for fixed email - foreach($conf->global as $key => $val) - { - if ($notifcode) - { - if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; - } - else - { - if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_.*_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; - } - - $threshold = (float) $reg[1]; - if ($valueforthreshold < $threshold) continue; - - $tmpemail=explode(',',$val); - foreach($tmpemail as $key2 => $val2) - { - $newval2=trim($val2); - if ($newval2 == '__SUPERVISOREMAIL__') - { - if ($user->fk_user > 0) - { - $tmpuser=new User($this->db); - $tmpuser->fetch($user->fk_user); - if ($tmpuser->email) $newval2=trim($tmpuser->email); - else $newval2=''; - } - else $newval2=''; - } - if ($newval2) - { - $isvalid=isValidEmail($newval2, 0); - if (empty($resarray[$newval2])) $resarray[$newval2]=array('type'=> 'tofixedemail', 'code'=>trim($key), 'emaildesc'=>trim($val2), 'email'=>$newval2, 'isemailvalid'=>$isvalid); - } - } - } - } + if ($socid >= 0 && in_array('thirdparty', $scope)) + { + $sql = "SELECT a.code, c.email, c.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n,"; + $sql.= " ".MAIN_DB_PREFIX."socpeople as c,"; + $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,"; + $sql.= " ".MAIN_DB_PREFIX."societe as s"; + $sql.= " WHERE n.fk_contact = c.rowid"; + $sql.= " AND a.rowid = n.fk_action"; + $sql.= " AND n.fk_soc = s.rowid"; + if ($notifcode) + { + if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage + else $sql.= " AND a.code = '".$notifcode."'"; // New usage + } + $sql.= " AND s.entity IN (".getEntity('societe').")"; + if ($socid > 0) $sql.= " AND s.rowid = ".$socid; + + dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG); + + $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) + { + $newval2=trim($obj->email); + $isvalid=isValidEmail($newval2); + if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'tocontact', 'code'=>trim($obj->code), 'emaildesc'=>'Contact id '.$obj->rowid, 'email'=>$newval2, 'contactid'=>$obj->rowid, 'isemailvalid'=>$isvalid); + } + $i++; + } + } + else + { + $error++; + $this->error=$this->db->lasterror(); + } + } + } + + if (! $error) + { + if ($userid >= 0 && in_array('user', $scope)) + { + $sql = "SELECT a.code, c.email, c.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n,"; + $sql.= " ".MAIN_DB_PREFIX."user as c,"; + $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a"; + $sql.= " WHERE n.fk_user = c.rowid"; + $sql.= " AND a.rowid = n.fk_action"; + if ($notifcode) + { + if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage + else $sql.= " AND a.code = '".$notifcode."'"; // New usage + } + $sql.= " AND c.entity IN (".getEntity('user').")"; + if ($userid > 0) $sql.= " AND c.rowid = ".$userid; + + dol_syslog(__METHOD__." ".$notifcode.", ".$socid."", LOG_DEBUG); + + $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) + { + $newval2=trim($obj->email); + $isvalid=isValidEmail($newval2); + if (empty($resarray[$newval2])) $resarray[$newval2] = array('type'=> 'touser', 'code'=>trim($obj->code), 'emaildesc'=>'User id '.$obj->rowid, 'email'=>$newval2, 'userid'=>$obj->rowid, 'isemailvalid'=>$isvalid); + } + $i++; + } + } + else + { + $error++; + $this->error=$this->db->lasterror(); + } + } + } + + if (! $error) + { + if (in_array('global', $scope)) + { + // List of notifications enabled for fixed email + foreach($conf->global as $key => $val) + { + if ($notifcode) + { + if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; + } + else + { + if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_.*_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; + } + + $threshold = (float) $reg[1]; + if ($valueforthreshold < $threshold) continue; + + $tmpemail=explode(',',$val); + foreach($tmpemail as $key2 => $val2) + { + $newval2=trim($val2); + if ($newval2 == '__SUPERVISOREMAIL__') + { + if ($user->fk_user > 0) + { + $tmpuser=new User($this->db); + $tmpuser->fetch($user->fk_user); + if ($tmpuser->email) $newval2=trim($tmpuser->email); + else $newval2=''; + } + else $newval2=''; + } + if ($newval2) + { + $isvalid=isValidEmail($newval2, 0); + if (empty($resarray[$newval2])) $resarray[$newval2]=array('type'=> 'tofixedemail', 'code'=>trim($key), 'emaildesc'=>trim($val2), 'email'=>$newval2, 'isemailvalid'=>$isvalid); + } + } + } + } } if ($error) return -1; @@ -272,47 +273,47 @@ class Notify return $resarray; } - /** - * Check if notification are active for couple action/company. - * If yes, send mail and save trace into llx_notify. - * - * @param string $notifcode Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage) - * @param Object $object Object the notification deals on - * @return int <0 if KO, or number of changes if OK - */ - function send($notifcode, $object) - { - global $user,$conf,$langs,$mysoc; - global $hookmanager; - global $dolibarr_main_url_root; + /** + * Check if notification are active for couple action/company. + * If yes, send mail and save trace into llx_notify. + * + * @param string $notifcode Code of action in llx_c_action_trigger (new usage) or Id of action in llx_c_action_trigger (old usage) + * @param Object $object Object the notification deals on + * @return int <0 if KO, or number of changes if OK + */ + function send($notifcode, $object) + { + global $user,$conf,$langs,$mysoc; + global $hookmanager; + global $dolibarr_main_url_root; if (! in_array($notifcode, $this->arrayofnotifsupported)) return 0; - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (! is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); - } - $hookmanager->initHooks(array('notification')); - - dol_syslog(get_class($this)."::send notifcode=".$notifcode.", object=".$object->id); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if (! is_object($hookmanager)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager=new HookManager($this->db); + } + $hookmanager->initHooks(array('notification')); - $langs->load("other"); + dol_syslog(get_class($this)."::send notifcode=".$notifcode.", object=".$object->id); + + $langs->load("other"); // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current // Define some vars - $application = 'Dolibarr'; - if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $application = $conf->global->MAIN_APPLICATION_TITLE; - $replyto = $conf->notification->email_from; - $filename = basename($file); - $mimefile = dol_mimetype($file); + $application = 'Dolibarr'; + if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $application = $conf->global->MAIN_APPLICATION_TITLE; + $replyto = $conf->notification->email_from; + $filename = basename($file); + $mimefile = dol_mimetype($file); $object_type = ''; - $link = ''; + $link = ''; $num = 0; $oldref=(empty($object->oldref)?$object->ref:$object->oldref); @@ -321,56 +322,56 @@ class Notify // Check notification per third party $sql = "SELECT 'tocontactid' as type_target, c.email, c.rowid as cid, c.lastname, c.firstname, c.default_lang,"; $sql.= " a.rowid as adid, a.label, a.code, n.rowid, n.type"; - $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,"; - $sql.= " ".MAIN_DB_PREFIX."notify_def as n,"; - $sql.= " ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE n.fk_contact = c.rowid AND a.rowid = n.fk_action"; - $sql.= " AND n.fk_soc = s.rowid"; - if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage - else $sql.= " AND a.code = '".$notifcode."'"; // New usage - $sql .= " AND s.rowid = ".$object->socid; + $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c,"; + $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,"; + $sql.= " ".MAIN_DB_PREFIX."notify_def as n,"; + $sql.= " ".MAIN_DB_PREFIX."societe as s"; + $sql.= " WHERE n.fk_contact = c.rowid AND a.rowid = n.fk_action"; + $sql.= " AND n.fk_soc = s.rowid"; + if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage + else $sql.= " AND a.code = '".$notifcode."'"; // New usage + $sql .= " AND s.rowid = ".$object->socid; // Check notification per user - $sql.= "\nUNION\n"; + $sql.= "\nUNION\n"; - $sql.= "SELECT 'touserid' as type_target, c.email, c.rowid as cid, c.lastname, c.firstname, c.lang as default_lang,"; - $sql.= " a.rowid as adid, a.label, a.code, n.rowid, n.type"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as c,"; - $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,"; - $sql.= " ".MAIN_DB_PREFIX."notify_def as n"; - $sql.= " WHERE n.fk_user = c.rowid AND a.rowid = n.fk_action"; - if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage - else $sql.= " AND a.code = '".$notifcode."'"; // New usage - - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); + $sql.= "SELECT 'touserid' as type_target, c.email, c.rowid as cid, c.lastname, c.firstname, c.lang as default_lang,"; + $sql.= " a.rowid as adid, a.label, a.code, n.rowid, n.type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as c,"; + $sql.= " ".MAIN_DB_PREFIX."c_action_trigger as a,"; + $sql.= " ".MAIN_DB_PREFIX."notify_def as n"; + $sql.= " WHERE n.fk_user = c.rowid AND a.rowid = n.fk_action"; + if (is_numeric($notifcode)) $sql.= " AND n.fk_action = ".$notifcode; // Old usage + else $sql.= " AND a.code = '".$notifcode."'"; // New usage - if ($num > 0) - { - $i = 0; - while ($i < $num && ! $error) // For each notification couple defined (third party/actioncode) - { - $obj = $this->db->fetch_object($result); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); - $sendto = dolGetFirstLastname($obj->firstname,$obj->lastname) . " <".$obj->email.">"; + if ($num > 0) + { + $i = 0; + while ($i < $num && ! $error) // For each notification couple defined (third party/actioncode) + { + $obj = $this->db->fetch_object($result); + + $sendto = dolGetFirstLastname($obj->firstname,$obj->lastname) . " <".$obj->email.">"; $notifcodedefid = $obj->adid; - if (dol_strlen($obj->email)) - { - // Set output language - $outputlangs = $langs; - if ($obj->default_lang && $obj->default_lang != $langs->defaultlang) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($obj->default_lang); - } + if (dol_strlen($obj->email)) + { + // Set output language + $outputlangs = $langs; + if ($obj->default_lang && $obj->default_lang != $langs->defaultlang) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($obj->default_lang); + } - $subject = '['.$mysoc->name.'] '.$outputlangs->transnoentitiesnoconv("DolibarrNotification"); - - switch ($notifcode) { + $subject = '['.$mysoc->name.'] '.$outputlangs->transnoentitiesnoconv("DolibarrNotification"); + + switch ($notifcode) { case 'BILL_VALIDATE': $link='/compta/facture/card.php?facid='.$object->id; $dir_output = $conf->facture->dir_output; @@ -395,6 +396,12 @@ class Notify $object_type = 'propal'; $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$newref); break; + case 'PROPAL_CLOSE_SIGNED': + $link='/comm/propal/card.php?id='.$object->id; + $dir_output = $conf->propal->dir_output; + $object_type = 'propal'; + $mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned",$newref); + break; case 'FICHINTER_ADD_CONTACT': $link='/fichinter/card.php?id='.$object->id; $dir_output = $conf->facture->dir_output; @@ -409,7 +416,7 @@ class Notify break; case 'ORDER_SUPPLIER_VALIDATE': $link='/fourn/commande/card.php?id='.$object->id; - $dir_output = $conf->fournisseur->dir_output.'/commande/'; + $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$object->ref,$user->getFullName($langs)); @@ -417,7 +424,7 @@ class Notify break; case 'ORDER_SUPPLIER_APPROVE': $link='/fourn/commande/card.php?id='.$object->id; - $dir_output = $conf->fournisseur->dir_output.'/commande/'; + $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); @@ -425,7 +432,7 @@ class Notify break; case 'ORDER_SUPPLIER_REFUSE': $link='/fourn/commande/card.php?id='.$object->id; - $dir_output = $conf->fournisseur->dir_output.'/commande/'; + $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$newref,$user->getFullName($langs)); @@ -437,7 +444,7 @@ class Notify $mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated",$newref); break; } - $ref = dol_sanitizeFileName($newref); + $ref = dol_sanitizeFileName($newref); $pdf_path = $dir_output."/".$ref."/".$ref.".pdf"; if (! dol_is_file($pdf_path)) { @@ -449,104 +456,104 @@ class Notify $filepdf = $pdf_path; } - $message = $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n"; - $message.= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; - $message.= "\n"; - $message.= $mesg; - if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); + $message = $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n"; + $message.= $outputlangs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; + $message.= "\n"; + $message.= $mesg; + if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); - $parameters=array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$file, 'mimefile'=>$mimefile, 'filename'=>$filename); - $reshook=$hookmanager->executeHooks('formatNotificationMessage',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (! empty($hookmanager->resArray['subject'])) $subject.=$hookmanager->resArray['subject']; - if (! empty($hookmanager->resArray['message'])) $message.=$hookmanager->resArray['message']; - } - - $mailfile = new CMailFile( - $subject, - $sendto, - $replyto, - $message, - array($file), - array($mimefile), - array($filename[count($filename)-1]), - '', - '', - 0, - -1 - ); + $parameters=array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$file, 'mimefile'=>$mimefile, 'filename'=>$filename); + $reshook=$hookmanager->executeHooks('formatNotificationMessage',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (! empty($hookmanager->resArray['subject'])) $subject.=$hookmanager->resArray['subject']; + if (! empty($hookmanager->resArray['message'])) $message.=$hookmanager->resArray['message']; + } - if ($mailfile->sendfile()) - { - if ($obj->type_target == 'touserid') { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_user, type, objet_type, type_target, objet_id, email)"; - $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid?$object->socid:'null').", ".$obj->cid.", '".$obj->type."', '".$object_type."', '".$obj->type_target."', ".$object->id.", '".$this->db->escape($obj->email)."')"; - - } - else { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, objet_type, type_target, objet_id, email)"; - $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid?$object->socid:'null').", ".$obj->cid.", '".$obj->type."', '".$object_type."', '".$obj->type_target."', ".$object->id.", '".$this->db->escape($obj->email)."')"; - - } - if (! $this->db->query($sql)) - { - dol_print_error($this->db); - } - } - else + $mailfile = new CMailFile( + $subject, + $sendto, + $replyto, + $message, + array($file), + array($mimefile), + array($filename[count($filename)-1]), + '', + '', + 0, + -1 + ); + + if ($mailfile->sendfile()) + { + if ($obj->type_target == 'touserid') { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_user, type, objet_type, type_target, objet_id, email)"; + $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid?$object->socid:'null').", ".$obj->cid.", '".$obj->type."', '".$object_type."', '".$obj->type_target."', ".$object->id.", '".$this->db->escape($obj->email)."')"; + + } + else { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, objet_type, type_target, objet_id, email)"; + $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid?$object->socid:'null').", ".$obj->cid.", '".$obj->type."', '".$object_type."', '".$obj->type_target."', ".$object->id.", '".$this->db->escape($obj->email)."')"; + + } + if (! $this->db->query($sql)) + { + dol_print_error($this->db); + } + } + else { $error++; - $this->errors[]=$mailfile->error; - } - } - else - { - dol_syslog("No notification sent for ".$sendto." because email is empty"); - } - $i++; - } - } - else - { - dol_syslog("No notification to thirdparty sent, nothing into notification setup for the thirdparty socid = ".$object->socid); + $this->errors[]=$mailfile->error; + } + } + else + { + dol_syslog("No notification sent for ".$sendto." because email is empty"); + } + $i++; + } } - } - else - { - $error++; - $this->errors[]=$this->db->lasterror(); - dol_syslog("Failed to get list of notification to send ".$this->db->lasterror(), LOG_ERR); - return -1; - } + else + { + dol_syslog("No notification to thirdparty sent, nothing into notification setup for the thirdparty socid = ".$object->socid); + } + } + else + { + $error++; + $this->errors[]=$this->db->lasterror(); + dol_syslog("Failed to get list of notification to send ".$this->db->lasterror(), LOG_ERR); + return -1; + } - // Check notification using fixed email - if (! $error) - { - foreach($conf->global as $key => $val) - { - if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; + // Check notification using fixed email + if (! $error) + { + foreach($conf->global as $key => $val) + { + if ($val == '' || ! preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_(.*)$/', $key, $reg)) continue; - $threshold = (float) $reg[1]; - if (!empty($object->total_ht) && $object->total_ht <= $threshold) - { - dol_syslog("A notification is requested for notifcode = ".$notifcode." but amount = ".$object->total_ht." so lower than threshold = ".$threshold.". We discard this notification"); - continue; - } + $threshold = (float) $reg[1]; + if (!empty($object->total_ht) && $object->total_ht <= $threshold) + { + dol_syslog("A notification is requested for notifcode = ".$notifcode." but amount = ".$object->total_ht." so lower than threshold = ".$threshold.". We discard this notification"); + continue; + } - $param='NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_'.$reg[1]; + $param='NOTIFICATION_FIXEDEMAIL_'.$notifcode.'_THRESHOLD_HIGHER_'.$reg[1]; - $sendto = $conf->global->$param; - $notifcodedefid = dol_getIdFromCode($this->db, $notifcode, 'c_action_trigger', 'code', 'rowid'); - if ($notifcodedefid <= 0) dol_print_error($this->db, 'Failed to get id from code'); + $sendto = $conf->global->$param; + $notifcodedefid = dol_getIdFromCode($this->db, $notifcode, 'c_action_trigger', 'code', 'rowid'); + if ($notifcodedefid <= 0) dol_print_error($this->db, 'Failed to get id from code'); - $object_type = ''; - $link = ''; - $num++; + $object_type = ''; + $link = ''; + $num++; - $subject = '['.$mysoc->name.'] '.$langs->transnoentitiesnoconv("DolibarrNotification"); + $subject = '['.$mysoc->name.'] '.$langs->transnoentitiesnoconv("DolibarrNotification"); - switch ($notifcode) { + switch ($notifcode) { case 'BILL_VALIDATE': $link='/compta/facture/card.php?facid='.$object->id; $dir_output = $conf->facture->dir_output; @@ -571,29 +578,35 @@ class Notify $object_type = 'propal'; $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$newref); break; - case 'FICHINTER_ADD_CONTACT': - $link='/fichinter/card.php?id='.$object->id; - $dir_output = $conf->facture->dir_output; - $object_type = 'ficheinter'; - $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact",$newref); - break; + case 'PROPAL_CLOSE_SIGNED': + $link='/comm/propal/card.php?id='.$object->id; + $dir_output = $conf->propal->dir_output; + $object_type = 'propal'; + $mesg = $langs->transnoentitiesnoconv("EMailTextProposalClosedSigned",$newref); + break; + case 'FICHINTER_ADD_CONTACT': + $link='/fichinter/card.php?id='.$object->id; + $dir_output = $conf->facture->dir_output; + $object_type = 'ficheinter'; + $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionAddedContact",$newref); + break; case 'FICHINTER_VALIDATE': $link='/fichinter/card.php?id='.$object->id; $dir_output = $conf->facture->dir_output; $object_type = 'ficheinter'; $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$newref); break; - case 'ORDER_SUPPLIER_VALIDATE': - $link='/fourn/commande/card.php?id='.$object->id; - $dir_output = $conf->fournisseur->dir_output.'/commande/'; - $object_type = 'order_supplier'; - $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$newref,$user->getFullName($langs)); - $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; - break; + case 'ORDER_SUPPLIER_VALIDATE': + $link='/fourn/commande/card.php?id='.$object->id; + $dir_output = $conf->fournisseur->commande->dir_output; + $object_type = 'order_supplier'; + $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; + $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderValidatedBy",$newref,$user->getFullName($langs)); + $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; + break; case 'ORDER_SUPPLIER_APPROVE': $link='/fourn/commande/card.php?id='.$object->id; - $dir_output = $conf->fournisseur->dir_output.'/commande/'; + $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); @@ -601,7 +614,7 @@ class Notify break; case 'ORDER_SUPPLIER_APPROVE2': $link='/fourn/commande/card.php?id='.$object->id; - $dir_output = $conf->fournisseur->dir_output.'/commande/'; + $dir_output = $conf->fournisseur->commande->dir_output; $object_type = 'order_supplier'; $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$newref,$user->getFullName($langs)); @@ -633,73 +646,73 @@ class Notify $filepdf = $pdf_path; } - $message = $langs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n"; - $message.= $langs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; - $message.= "\n"; - $message.= $mesg; - if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); + $message = $langs->transnoentities("YouReceiveMailBecauseOfNotification",$application,$mysoc->name)."\n"; + $message.= $langs->transnoentities("YouReceiveMailBecauseOfNotification2",$application,$mysoc->name)."\n"; + $message.= "\n"; + $message.= $mesg; + if ($link) $message=dol_concatdesc($message,$urlwithroot.$link); - // Replace keyword __SUPERVISOREMAIL__ - if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) - { - $newval=''; - if ($user->fk_user > 0) - { - $supervisoruser=new User($this->db); - $supervisoruser->fetch($user->fk_user); - if ($supervisoruser->email) $newval=trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); - } - dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with ".$newval); - $sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto); - $sendto = preg_replace('/^[\s,]+/','',$sendto); // Clean start of string - $sendto = preg_replace('/[\s,]+$/','',$sendto); // Clean end of string - } + // Replace keyword __SUPERVISOREMAIL__ + if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) + { + $newval=''; + if ($user->fk_user > 0) + { + $supervisoruser=new User($this->db); + $supervisoruser->fetch($user->fk_user); + if ($supervisoruser->email) $newval=trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); + } + dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with ".$newval); + $sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto); + $sendto = preg_replace('/^[\s,]+/','',$sendto); // Clean start of string + $sendto = preg_replace('/[\s,]+$/','',$sendto); // Clean end of string + } - if ($sendto) - { - $parameters=array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$file, 'mimefile'=>$mimefile, 'filename'=>$filename); - $reshook=$hookmanager->executeHooks('formatNotificationMessage',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (! empty($hookmanager->resArray['subject'])) $subject.=$hookmanager->resArray['subject']; - if (! empty($hookmanager->resArray['message'])) $message.=$hookmanager->resArray['message']; - } - - $mailfile = new CMailFile( - $subject, - $sendto, - $replyto, - $message, - array($file), - array($mimefile), - array($filename[count($filename)-1]), - '', - '', - 0, - -1 - ); + if ($sendto) + { + $parameters=array('notifcode'=>$notifcode, 'sendto'=>$sendto, 'replyto'=>$replyto, 'file'=>$file, 'mimefile'=>$mimefile, 'filename'=>$filename); + $reshook=$hookmanager->executeHooks('formatNotificationMessage',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (! empty($hookmanager->resArray['subject'])) $subject.=$hookmanager->resArray['subject']; + if (! empty($hookmanager->resArray['message'])) $message.=$hookmanager->resArray['message']; + } - if ($mailfile->sendfile()) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, type_target, objet_type, objet_id, email)"; - $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid?$object->socid:'null').", null, 'email', 'tofixedemail', '".$object_type."', ".$object->id.", '".$this->db->escape($conf->global->$param)."')"; - if (! $this->db->query($sql)) - { - dol_print_error($this->db); - } - } - else - { - $error++; - $this->errors[]=$mailfile->error; - } - } - } - } + $mailfile = new CMailFile( + $subject, + $sendto, + $replyto, + $message, + array($file), + array($mimefile), + array($filename[count($filename)-1]), + '', + '', + 0, + -1 + ); + + if ($mailfile->sendfile()) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify (daten, fk_action, fk_soc, fk_contact, type, type_target, objet_type, objet_id, email)"; + $sql.= " VALUES ('".$this->db->idate(dol_now())."', ".$notifcodedefid.", ".($object->socid?$object->socid:'null').", null, 'email', 'tofixedemail', '".$object_type."', ".$object->id.", '".$this->db->escape($conf->global->$param)."')"; + if (! $this->db->query($sql)) + { + dol_print_error($this->db); + } + } + else + { + $error++; + $this->errors[]=$mailfile->error; + } + } + } + } if (! $error) return $num; else return -1 * $error; - } + } } diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 169aec16307..66735c62606 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -151,7 +151,7 @@ class Translate $this->load($domain); } } - + /** * Load translation key-value for a particular file, into a memory array. * If data for file already loaded, do nothing. @@ -177,7 +177,7 @@ class Translate global $conf,$db; //dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang); - + // Check parameters if (empty($domain)) { @@ -185,8 +185,8 @@ class Translate return -1; } if ($this->defaultlang == 'none_NONE') return 0; // Special language code to not translate keys - - + + // Load $this->tab_translate[] from database if (empty($loadfromfileonly) && count($this->tab_translate) == 0) $this->loadFromDatabase($db); // Nothing was loaded yet, so we load database. @@ -278,14 +278,14 @@ class Translate * and split the rest until a line feed. * This is more efficient than fgets + explode + trim by a factor of ~2. */ - while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n]")) + while ($line = fscanf($fp, "%[^= ]%*[ =]%[^\n]")) { - if (isset($line[1])) + if (isset($line[1])) { list($key, $value) = $line; //if ($domain == 'orders') print "Domain=$domain, found a string for $tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."
    "; //if ($key == 'Order') print "Domain=$domain, found a string for key=$key=$tab[0] with value $tab[1]. Currently in cache ".$this->tab_translate[$key]."
    "; - if (empty($this->tab_translate[$key])) + if (empty($this->tab_translate[$key])) { // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries) $value = preg_replace('/\\n/', "\n", $value); // Parse and render carriage returns if ($key == 'DIRECTION') { // This is to declare direction of language @@ -375,8 +375,8 @@ class Translate if (! empty($tmparray2[1])) $this->tab_translate[$tmparray2[0]]=$tmparray2[1]; } } - } - + } + // Check to be sure that SeparatorDecimal differs from SeparatorThousand if (! empty($this->tab_translate["SeparatorDecimal"]) && ! empty($this->tab_translate["SeparatorThousand"]) && $this->tab_translate["SeparatorDecimal"] == $this->tab_translate["SeparatorThousand"]) $this->tab_translate["SeparatorThousand"]=''; @@ -401,7 +401,7 @@ class Translate global $conf; $domain='database'; - + // Check parameters if (empty($db)) return 0; // Database handler can't be used @@ -418,7 +418,7 @@ class Translate } $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only. - + $fileread=0; $langofdir=(empty($forcelangdir)?$this->defaultlang:$forcelangdir); @@ -467,24 +467,24 @@ class Translate if (! $found && ! empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { // Overwrite translation with database read - $sql="SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."'"; + $sql="SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."'"; $resql=$db->query($sql); - + if ($resql) { $num = $db->num_rows($resql); if ($num) { if ($usecachekey) $tabtranslatedomain=array(); // To save lang content in cache - + $i = 0; while ($i < $num) // Ex: Need 225ms for all fgets on all lang file for Third party page. Same speed than file_get_contents { $obj=$db->fetch_object($resql); - + $key=$obj->transkey; $value=$obj->transvalue; - + //print "Domain=$domain, found a string for $tab[0] with value $tab[1]
    "; if (empty($this->tab_translate[$key])) // If translation was already found, we must not continue, even if MAIN_FORCELANGDIR is set (MAIN_FORCELANGDIR is to replace lang dir, not to overwrite entries) { @@ -493,12 +493,12 @@ class Translate $this->tab_translate[$key]=$value; if ($usecachekey) $tabtranslatedomain[$key]=$value; // To save lang content in cache } - + $i++; } - + $fileread=1; - + // TODO Move cache write out of loop on dirs // To save lang content for usecachekey into cache if ($usecachekey && count($tabtranslatedomain)) @@ -524,9 +524,9 @@ class Translate return 1; } - - - + + + /** * Return translated value of key for special keys ("Currency...", "Civility...", ...). * Search in lang file, then into database. Key must be any complete entry into lang file: CurrencyEUR, ... @@ -559,7 +559,7 @@ class Translate } elseif (preg_match('/^PaymentTypeShort([0-9A-Z]+)$/i',$key,$reg)) { - $newstr=$this->getLabelFromKey($db,$reg[1],'c_paiement','code','libelle'); + $newstr=$this->getLabelFromKey($db,$reg[1],'c_paiement','code','libelle','',1); } elseif (preg_match('/^OppStatusShort([0-9A-Z]+)$/i',$key,$reg)) { @@ -611,8 +611,8 @@ class Translate $str=preg_replace('/'.preg_quote($tmparray2[0]).'/',$tmparray2[1],$str); } } - - if (! preg_match('/^Format/',$key)) + + if (! preg_match('/^Format/',$key)) { //print $str; $str=sprintf($str,$param1,$param2,$param3,$param4); // Replace %s and %d except for FormatXXX strings. @@ -690,9 +690,9 @@ class Translate $tmparray2=explode(':',$tmp); $str=preg_replace('/'.preg_quote($tmparray2[0]).'/',$tmparray2[1],$str); } - } + } - if (! preg_match('/^Format/',$key)) + if (! preg_match('/^Format/',$key)) { //print $str; $str=sprintf($str,$param1,$param2,$param3,$param4); // Replace %s and %d except for FormatXXX strings. @@ -867,10 +867,11 @@ class Translate * @param string $fieldkey Field for key * @param string $fieldlabel Field for label * @param string $keyforselect Use another value than the translation key for the where into select + * @param int $filteronentity Use a filter on entity * @return string Label in UTF8 (but without entities) * @see dol_getIdFromCode */ - function getLabelFromKey($db,$key,$tablename,$fieldkey,$fieldlabel,$keyforselect='') + function getLabelFromKey($db,$key,$tablename,$fieldkey,$fieldlabel,$keyforselect='',$filteronentity=0) { // If key empty if ($key == '') return ''; @@ -893,6 +894,7 @@ class Translate $sql = "SELECT ".$fieldlabel." as label"; $sql.= " FROM ".MAIN_DB_PREFIX.$tablename; $sql.= " WHERE ".$fieldkey." = '".($keyforselect?$keyforselect:$key)."'"; + if ($filteronentity) $sql.= " AND entity IN (" . getEntity($tablename). ')'; dol_syslog(get_class($this).'::getLabelFromKey', LOG_DEBUG); $resql = $db->query($sql); if ($resql) @@ -930,7 +932,7 @@ class Translate } /** - * Return a currency code into its symbol. + * Return a currency code into its symbol. * If mb_convert_encoding is not available, return currency code. * * @param string $currency_code Currency code 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/js/datepicker.js.php b/htdocs/core/js/datepicker.js.php deleted file mode 100644 index 50c140f6f82..00000000000 --- a/htdocs/core/js/datepicker.js.php +++ /dev/null @@ -1,151 +0,0 @@ - - * Copyright (C) 2011 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 . - */ - -/** - * \file htdocs/core/js/datepicker.js.php - * \brief File that include javascript functions for datepickers - */ - -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled cause need to do translations -if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK',1); -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); -if (! defined('NOLOGIN')) define('NOLOGIN',1); -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); -if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML',1); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); - -session_cache_limiter(FALSE); - -require_once '../../main.inc.php'; - -// Define javascript type -top_httphead('text/javascript; charset=UTF-8'); -// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=3600, public, must-revalidate'); -else header('Cache-Control: no-cache'); - - -// Define tradMonths javascript array (we define this in datepicker AND in parent page to avoid errors with IE8) -$tradMonths=array( -dol_escape_js($langs->transnoentitiesnoconv("January")), -dol_escape_js($langs->transnoentitiesnoconv("February")), -dol_escape_js($langs->transnoentitiesnoconv("March")), -dol_escape_js($langs->transnoentitiesnoconv("April")), -dol_escape_js($langs->transnoentitiesnoconv("May")), -dol_escape_js($langs->transnoentitiesnoconv("June")), -dol_escape_js($langs->transnoentitiesnoconv("July")), -dol_escape_js($langs->transnoentitiesnoconv("August")), -dol_escape_js($langs->transnoentitiesnoconv("September")), -dol_escape_js($langs->transnoentitiesnoconv("October")), -dol_escape_js($langs->transnoentitiesnoconv("November")), -dol_escape_js($langs->transnoentitiesnoconv("December")) -); - -$tradMonthsShort=array( -$langs->trans("JanuaryMin"), -$langs->trans("FebruaryMin"), -$langs->trans("MarchMin"), -$langs->trans("AprilMin"), -$langs->trans("MayMin"), -$langs->trans("JuneMin"), -$langs->trans("JulyMin"), -$langs->trans("AugustMin"), -$langs->trans("SeptemberMin"), -$langs->trans("OctoberMin"), -$langs->trans("NovemberMin"), -$langs->trans("DecemberMin") -); - -$tradDays=array( -$langs->trans("Sunday"), -$langs->trans("Monday"), -$langs->trans("Tuesday"), -$langs->trans("Wednesday"), -$langs->trans("Thursday"), -$langs->trans("Friday"), -$langs->trans("Saturday") -); - -$tradDaysShort=array( -$langs->trans("ShortSunday"), -$langs->trans("ShortMonday"), -$langs->trans("ShortTuesday"), -$langs->trans("ShortWednesday"), -$langs->trans("ShortThursday"), -$langs->trans("ShortFriday"), -$langs->trans("ShortSaturday") -); - -$tradDaysMin=array( -$langs->trans("SundayMin"), -$langs->trans("MondayMin"), -$langs->trans("TuesdayMin"), -$langs->trans("WednesdayMin"), -$langs->trans("ThursdayMin"), -$langs->trans("FridayMin"), -$langs->trans("SaturdayMin") -); -?> - - -// For eldy and jQuery date picker -var tradMonths = ; -var tradMonthsShort = ; -var tradDays = ; -var tradDaysShort = ; -var tradDaysMin = ; - - -// For JQuery date picker -$(document).ready(function() { - $.datepicker.setDefaults({ - autoSize: true, - changeMonth: true, - changeYear: true, - altField: '#timestamp', - altFormat: '@' // Gives a timestamp dateformat - }); -}); - -jQuery(function($){ - $.datepicker.regional['defaultlang ?>'] = { - closeText: 'trans("Close2") ?>', - prevText: 'trans("Previous") ?>', - nextText: 'trans("Next") ?>', - currentText: 'trans("Now") ?>', - monthNames: tradMonths, - monthNamesShort: tradMonthsShort, - dayNames: tradDays, - dayNamesShort: tradDaysShort, - dayNamesMin: tradDaysMin, - weekHeader: 'trans("Week"); ?>', - dateFormat: 'trans("FormatDateShortJQuery"); ?>', - firstDay: global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'); ?>, - isRTL: trans("DIRECTION")=='rtl'?'true':'false'); ?>, - showMonthAfterYear: false, // TODO add specific to country - yearSuffix: '' // TODO add specific to country - }; - $.datepicker.setDefaults($.datepicker.regional['defaultlang ?>']); -}); - - -close(); diff --git a/htdocs/core/js/lib_batch.js b/htdocs/core/js/lib_batch.js deleted file mode 100644 index 54ddb8fa77d..00000000000 --- a/htdocs/core/js/lib_batch.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2014 Cedric GROSS -// -// 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 . -// or see http://www.gnu.org/ - -// -// \file htdocs/core/js/lib_batch.js -// \brief File that include javascript functions used when dispatching batch-enabled product -// - -/** - * addLineBatch - * @deprecated replaced by addDispatchLine and moved to module folder and file fourn/js/lib_dispatch.js - * - * @param index int number of produt. 0 = first product line - */ -function addLineBatch(index) -{ - var nme = 'dluo_0_'+index; - $row=$("tr[name='"+nme+"']").clone(true); - $row.find("input[name^='qty']").val(''); - var trs = $("tr[name^='dluo_'][name$='_"+index+"']"); /* trs.length = position of line for batch */ - var newrow=$row.html().replace(/_0_/g,"_"+(trs.length)+"_"); - $row.html(newrow); - //clear value - $row.find("input[name^='qty']").val(''); - //change name of row - $row.attr('name','dluo_'+trs.length+'_'+index); - $("tr[name^='dluo_'][name$='_"+index+"']:last").after($row); - - /* Suffix of lines are: _ trs.length _ index */ - jQuery("#lot_number_"+trs.length+"_"+index).focus(); - nb = jQuery("#qty_"+(trs.length - 1)+"_"+index).val(); - if (nb > 0) - { - jQuery("#qty_"+(trs.length - 1)+"_"+index).val(1); - jQuery("#qty_"+trs.length+"_"+index).val(nb - 1); - } -} diff --git a/htdocs/core/js/lib_head.js.php b/htdocs/core/js/lib_head.js.php index 7ed49d004d2..a68995e5eeb 100644 --- a/htdocs/core/js/lib_head.js.php +++ b/htdocs/core/js/lib_head.js.php @@ -43,9 +43,113 @@ top_httphead('text/javascript; charset=UTF-8'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. if (empty($dolibarr_nocache)) header('Cache-Control: max-age=3600, public, must-revalidate'); else header('Cache-Control: no-cache'); + + + +// Define tradMonths javascript array (we define this in datepicker AND in parent page to avoid errors with IE8) +$tradMonths=array( +dol_escape_js($langs->transnoentitiesnoconv("January")), +dol_escape_js($langs->transnoentitiesnoconv("February")), +dol_escape_js($langs->transnoentitiesnoconv("March")), +dol_escape_js($langs->transnoentitiesnoconv("April")), +dol_escape_js($langs->transnoentitiesnoconv("May")), +dol_escape_js($langs->transnoentitiesnoconv("June")), +dol_escape_js($langs->transnoentitiesnoconv("July")), +dol_escape_js($langs->transnoentitiesnoconv("August")), +dol_escape_js($langs->transnoentitiesnoconv("September")), +dol_escape_js($langs->transnoentitiesnoconv("October")), +dol_escape_js($langs->transnoentitiesnoconv("November")), +dol_escape_js($langs->transnoentitiesnoconv("December")) +); + +$tradMonthsShort=array( +$langs->trans("JanuaryMin"), +$langs->trans("FebruaryMin"), +$langs->trans("MarchMin"), +$langs->trans("AprilMin"), +$langs->trans("MayMin"), +$langs->trans("JuneMin"), +$langs->trans("JulyMin"), +$langs->trans("AugustMin"), +$langs->trans("SeptemberMin"), +$langs->trans("OctoberMin"), +$langs->trans("NovemberMin"), +$langs->trans("DecemberMin") +); + +$tradDays=array( +$langs->trans("Sunday"), +$langs->trans("Monday"), +$langs->trans("Tuesday"), +$langs->trans("Wednesday"), +$langs->trans("Thursday"), +$langs->trans("Friday"), +$langs->trans("Saturday") +); + +$tradDaysShort=array( +$langs->trans("ShortSunday"), +$langs->trans("ShortMonday"), +$langs->trans("ShortTuesday"), +$langs->trans("ShortWednesday"), +$langs->trans("ShortThursday"), +$langs->trans("ShortFriday"), +$langs->trans("ShortSaturday") +); + +$tradDaysMin=array( +$langs->trans("SundayMin"), +$langs->trans("MondayMin"), +$langs->trans("TuesdayMin"), +$langs->trans("WednesdayMin"), +$langs->trans("ThursdayMin"), +$langs->trans("FridayMin"), +$langs->trans("SaturdayMin") +); + ?> // Javascript libraries for Dolibarr ERP CRM (https://www.dolibarr.org) +// For jQuery date picker +var tradMonths = ; +var tradMonthsShort = ; +var tradDays = ; +var tradDaysShort = ; +var tradDaysMin = ; + +// For JQuery date picker +$(document).ready(function() { + $.datepicker.setDefaults({ + autoSize: true, + changeMonth: true, + changeYear: true, + altField: '#timestamp', + altFormat: '@' // Gives a timestamp dateformat + }); +}); + +jQuery(function($){ + $.datepicker.regional['defaultlang ?>'] = { + closeText: 'trans("Close2") ?>', + prevText: 'trans("Previous") ?>', + nextText: 'trans("Next") ?>', + currentText: 'trans("Now") ?>', + monthNames: tradMonths, + monthNamesShort: tradMonthsShort, + dayNames: tradDays, + dayNamesShort: tradDaysShort, + dayNamesMin: tradDaysMin, + weekHeader: 'trans("Week"); ?>', + dateFormat: 'trans("FormatDateShortJQuery"); ?>', /* Note dd/mm/yy means year on 4 digit in jquery format */ + firstDay: global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'); ?>, + isRTL: trans("DIRECTION")=='rtl'?'true':'false'); ?>, + showMonthAfterYear: false, /* TODO add specific to country */ + yearSuffix: '' /* TODO add specific to country */ + }; + $.datepicker.setDefaults($.datepicker.regional['defaultlang ?>']); +}); + + /** * Set select2 translations (if module was loaded). @@ -506,26 +610,26 @@ function getDateFromFormat(val,format) if (substr == "MM" ||substr == "M") { month=getIntegerInString(val,d,1,2); - d -= 2- month.length; + if (month) d -= 2- month.length; } if (substr == "dd") { day=getIntegerInString(val,d,1,2); - d -= 2- day.length; + if (day) d -= 2- day.length; } if (substr == "HH" ||substr == "hh" ) { hour=getIntegerInString(val,d,1,2); - d -= 2- hour.length; + if (dhouray) d -= 2- hour.length; } if (substr == "mm"){ minute=getIntegerInString(val,d,1,2); - d -= 2- minute.length; + if (minute) d -= 2- minute.length; } if (substr == "ss") { seconde=getIntegerInString(val,d,1,2); - d -= 2- seconde.length; + if (seconde) d -= 2- seconde.length; } i+=substr.length; diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index 5d46de321da..85bd46467fa 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -1527,3 +1527,50 @@ function phpinfo_array() return $info_arr; } +/** + * Return array head with list of tabs to view object informations. + * + * @return array head array with tabs + */ +function email_admin_prepare_head() +{ + global $langs, $conf, $user; + + $h = 0; + $head = array(); + + if ($user->admin && (empty($_SESSION['leftmenu']) || $_SESSION['leftmenu'] != 'email_templates')) + { + $head[$h][0] = DOL_URL_ROOT."/admin/mails.php"; + $head[$h][1] = $langs->trans("OutGoingEmailSetup"); + $head[$h][2] = 'common'; + $h++; + + if ($conf->mailing->enabled) + { + $head[$h][0] = DOL_URL_ROOT."/admin/mails_emailing.php"; + $head[$h][1] = $langs->trans("OutGoingEmailSetupForEmailing"); + $head[$h][2] = 'common_emailing'; + $h++; + } + } + + $head[$h][0] = DOL_URL_ROOT."/admin/mails_templates.php"; + $head[$h][1] = $langs->trans("DictionaryEMailTemplates"); + $head[$h][2] = 'templates'; + $h++; + + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) + { + $head[$h][0] = DOL_URL_ROOT."/admin/mails_senderprofile_list.php"; + $head[$h][1] = $langs->trans("EmailSenderProfiles"); + $head[$h][2] = 'senderprofiles'; + $h++; + } + + complete_head_from_modules($conf,$langs,null,$head,$h,'email_admin','remove'); + + return $head; +} + + diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index 3cc767c1592..500bbbb3ffb 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -63,18 +63,15 @@ function ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLengt var autoselect = '.$autoselect.'; var options = '.json_encode($ajaxoptions).'; - /* Remove product id before select another product use keyup instead of change to avoid loosing the product id. This is needed only for select of predefined product */ - /* TODO Check if we can remove this */ - $("input#search_'.$htmlname.'").keydown(function() { - $("#'.$htmlname.'").val(""); + /* Remove selected id as soon as we type or delete a char (it means old selection is wrong). Use keyup/down instead of change to avoid loosing the product id. This is needed only for select of predefined product */ + $("input#search_'.$htmlname.'").keydown(function(e) { + if (e.keyCode != 9) /* If not "Tab" key */ + { + console.log("Clear id previously selected for field '.$htmlname.'"); + $("#'.$htmlname.'").val(""); + } }); - /* I disable this. A call to trigger is already done later into the select action of the autocomplete code - $("input#search_'.$htmlname.'").change(function() { - console.log("Call the change trigger on input '.$htmlname.' because of a change on search_'.$htmlname.' was triggered"); - $("#'.$htmlname.'").trigger("change"); - });*/ - // Check options for secondary actions when keyup $("input#search_'.$htmlname.'").keyup(function() { if ($(this).val().length == 0) diff --git a/htdocs/core/lib/bank.lib.php b/htdocs/core/lib/bank.lib.php index c88a0b7afed..28f97bd1805 100644 --- a/htdocs/core/lib/bank.lib.php +++ b/htdocs/core/lib/bank.lib.php @@ -42,7 +42,7 @@ function bank_prepare_head(Account $object) $head[$h][2] = 'bankname'; $h++; - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/bankentries.php?id=" . $object->id; + $head[$h][0] = DOL_URL_ROOT . "/compta/bank/bankentries_list.php?id=" . $object->id; $head[$h][1] = $langs->trans("BankTransactions"); $head[$h][2] = 'journal'; $h++; @@ -95,7 +95,7 @@ function bank_prepare_head(Account $object) $head[$h][1] = $langs->trans("Info"); $head[$h][2] = 'info'; $h++;*/ - + complete_head_from_modules($conf, $langs, $object, $head, $h, 'bank', 'remove'); return $head; @@ -146,9 +146,9 @@ function bank_admin_prepare_head($object) * @return array Array of tabs to shoc */ function various_payment_prepare_head($object) { - + global $db, $langs, $conf; - + $h = 0; $head = array(); @@ -178,7 +178,7 @@ function various_payment_prepare_head($object) { $head[$h][1] = $langs->trans("Info"); $head[$h][2] = 'info'; $h++; - + complete_head_from_modules($conf,$langs,$object,$head,$h,'various_payment', 'remove'); return $head; @@ -247,7 +247,7 @@ function checkBanForAccount($account) $rib = strtr($rib, "abcdefghijklmnopqrstuvwxyz", "12345678912345678923456789"); // Separation du rib en 3 groupes de 7 + 1 groupe de 2. // Multiplication de chaque groupe par les coef du tableau - + for ($i = 0, $s = 0; $i < 3; $i++) { $code = substr($rib, 7 * $i, 7); $s += (0 + (int) $code) * $coef[$i]; diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 6a5f6e34a62..2e24fd3fee8 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -48,6 +48,28 @@ function societe_prepare_head(Societe $object) $head[$h][2] = 'card'; $h++; + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) + { + //$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external')); + $nbContact = 0; // TODO + + $sql = "SELECT COUNT(p.rowid) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p"; + $sql .= " WHERE p.fk_soc = ".$object->id; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + if ($obj) $nbContact = $obj->nb; + } + + $head[$h][0] = DOL_URL_ROOT.'/societe/contact.php?socid='.$object->id; + $head[$h][1] = $langs->trans('ContactsAddresses'); + if ($nbContact > 0) $head[$h][1].= ' '.$nbContact.''; + $head[$h][2] = 'contact'; + $h++; + } + if ($object->client==1 || $object->client==2 || $object->client==3) { $head[$h][0] = DOL_URL_ROOT.'/comm/card.php?socid='.$object->id; @@ -766,7 +788,7 @@ function show_contacts($conf,$langs,$db,$object,$backtopage='') print ''; - print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print "\n".''."\n"; $param="socid=".$object->id; @@ -1283,11 +1305,11 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon='', $noprint= } $out.=''; $out.=''; - $out.=''; - $out.=''; $out.=''; + $out.=''; + $out.=''; $out.=''; $out.=''; $out.=''; @@ -1312,9 +1334,9 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon='', $noprint= } $out.=getTitleFieldOfList($langs->trans("Ref"), 0, $_SERVER["PHP_SELF"], 'a.id', '', $param, '', $sortfield, $sortorder); $out.=getTitleFieldOfList($langs->trans("Owner")); + $out.=getTitleFieldOfList($langs->trans("Type")); $out.=getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder); $out.=getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep,a.id', '', $param, 'align="center"', $sortfield, $sortorder); - $out.=getTitleFieldOfList($langs->trans("Type")); $out.=getTitleFieldOfList(''); $out.=getTitleFieldOfList(''); $out.=getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], 'a.percent', '', $param, 'align="center"', $sortfield, $sortorder); @@ -1349,6 +1371,25 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon='', $noprint= $out.=$userstatic->getNomUrl(-1); $out.=''; + // Type + $out.=''; + // Title $out.='\n"; - // Type - $out.=''; - // Title of event //$out.=''; diff --git a/htdocs/core/lib/contact.lib.php b/htdocs/core/lib/contact.lib.php index f951439f0c5..f1d721b62e6 100644 --- a/htdocs/core/lib/contact.lib.php +++ b/htdocs/core/lib/contact.lib.php @@ -1,6 +1,6 @@ - * Copyright (C) 2010-2012 Regis Houssin + * Copyright (C) 2010-2017 Regis Houssin * Copyright (C) 2015 Frederic France * Copyright (C) 2015 Raphaël Doursenaud * @@ -42,7 +42,8 @@ function contact_prepare_head(Contact $object) $head[$tab][2] = 'card'; $tab++; - if (! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_CONTACT_ACTIVE)) + if ((! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_CONTACT_ACTIVE)) + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || ! empty($user->admin))) { $langs->load("ldap"); @@ -94,7 +95,7 @@ function contact_prepare_head(Contact $object) } $head[$tab][2] = 'agenda'; $tab++; - + // Log /* $head[$tab][0] = DOL_URL_ROOT.'/contact/info.php?id='.$object->id; diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index cdcebae7099..2f59c7e388c 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -34,7 +34,7 @@ */ function dol_basename($pathfile) { - return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/')); + return preg_replace('/^.*\/([^\/]+)$/','$1',rtrim($pathfile,'/')); } /** @@ -47,7 +47,7 @@ function dol_basename($pathfile) * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/' by doing preg_quote($var,'/'), since this char is used for preg_match function, * but must not contains the start and end '/'. Filter is checked into basename only. * @param array $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.')). Exclude is checked into fullpath. - * @param string $sortcriteria Sort criteria ("","fullname","relativename","name","date","size") + * @param string $sortcriteria Sort criteria ('','fullname','relativename','name','date','size') * @param string $sortorder Sort order (SORT_ASC, SORT_DESC) * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only * @param int $nohook Disable all hooks @@ -75,9 +75,9 @@ function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefil if (is_object($hookmanager) && ! $nohook) { - $hookmanager->resArray=array(); + $hookmanager->resArray=array(); - $hookmanager->initHooks(array('fileslib')); + $hookmanager->initHooks(array('fileslib')); $parameters=array( 'path' => $newpath, @@ -221,66 +221,66 @@ function dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefil */ function dol_dir_list_in_database($path, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0) { - global $conf, $db; + global $conf, $db; - $sql=" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m, acl, position"; - if ($mode) $sql.=", description"; - $sql.=" FROM ".MAIN_DB_PREFIX."ecm_files"; - $sql.=" WHERE filepath = '".$db->escape($path)."'"; - $sql.=" AND entity = ".$conf->entity; + $sql=" SELECT rowid, label, entity, filename, filepath, fullpath_orig, keywords, cover, gen_or_uploaded, extraparams, date_c, date_m, fk_user_c, fk_user_m, acl, position"; + if ($mode) $sql.=", description"; + $sql.=" FROM ".MAIN_DB_PREFIX."ecm_files"; + $sql.=" WHERE filepath = '".$db->escape($path)."'"; + $sql.=" AND entity = ".$conf->entity; - $resql = $db->query($sql); - if ($resql) - { - $file_list=array(); - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - if ($obj) - { - preg_match('/([^\/]+)\/[^\/]+$/',DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,$reg); - $level1name=(isset($reg[1])?$reg[1]:''); - $file_list[] = array( - "rowid" => $obj->rowid, - "label" => $obj->label, // md5 - "name" => $obj->filename, - "path" => DOL_DATA_ROOT.'/'.$obj->filepath, - "level1name" => $level1name, - "fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, - "fullpath_orig" => $obj->fullpath_orig, - "date_c" => $db->jdate($obj->date_c), - "date_m" => $db->jdate($obj->date_m), - "type" => 'file', - "keywords" => $obj->keywords, - "cover" => $obj->cover, - "position" => (int) $obj->position, - "acl" => $obj->acl - ); - } - $i++; - } + $resql = $db->query($sql); + if ($resql) + { + $file_list=array(); + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + if ($obj) + { + preg_match('/([^\/]+)\/[^\/]+$/',DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename,$reg); + $level1name=(isset($reg[1])?$reg[1]:''); + $file_list[] = array( + "rowid" => $obj->rowid, + "label" => $obj->label, // md5 + "name" => $obj->filename, + "path" => DOL_DATA_ROOT.'/'.$obj->filepath, + "level1name" => $level1name, + "fullname" => DOL_DATA_ROOT.'/'.$obj->filepath.'/'.$obj->filename, + "fullpath_orig" => $obj->fullpath_orig, + "date_c" => $db->jdate($obj->date_c), + "date_m" => $db->jdate($obj->date_m), + "type" => 'file', + "keywords" => $obj->keywords, + "cover" => $obj->cover, + "position" => (int) $obj->position, + "acl" => $obj->acl + ); + } + $i++; + } - // Obtain a list of columns - if (! empty($sortcriteria)) - { - $myarray=array(); - foreach ($file_list as $key => $row) - { - $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:''); - } - // Sort the data - if ($sortorder) array_multisort($myarray, $sortorder, $file_list); - } + // Obtain a list of columns + if (! empty($sortcriteria)) + { + $myarray=array(); + foreach ($file_list as $key => $row) + { + $myarray[$key] = (isset($row[$sortcriteria])?$row[$sortcriteria]:''); + } + // Sort the data + if ($sortorder) array_multisort($myarray, $sortorder, $file_list); + } - return $file_list; - } - else - { - dol_print_error($db); - return array(); - } + return $file_list; + } + else + { + dol_print_error($db); + return array(); + } } @@ -411,9 +411,9 @@ function dol_compare_file($a, $b) */ function dol_is_dir($folder) { - $newfolder=dol_osencode($folder); - if (is_dir($newfolder)) return true; - else return false; + $newfolder=dol_osencode($folder); + if (is_dir($newfolder)) return true; + else return false; } /** @@ -424,8 +424,8 @@ function dol_is_dir($folder) */ function dol_is_file($pathoffile) { - $newpathoffile=dol_osencode($pathoffile); - return is_file($newpathoffile); + $newpathoffile=dol_osencode($pathoffile); + return is_file($newpathoffile); } /** @@ -436,12 +436,12 @@ function dol_is_file($pathoffile) */ function dol_is_url($url) { - $tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect'); - foreach($tmpprot as $prot) - { - if (preg_match('/^'.$prot.':/i',$url)) return true; - } - return false; + $tmpprot=array('file','http','https','ftp','zlib','data','ssh','ssh2','ogg','expect'); + foreach($tmpprot as $prot) + { + if (preg_match('/^'.$prot.':/i',$url)) return true; + } + return false; } /** @@ -456,14 +456,14 @@ function dol_dir_is_emtpy($folder) if (is_dir($newfolder)) { $handle = opendir($newfolder); - $folder_content = ''; + $folder_content = ''; while ((gettype($name = readdir($handle)) != "boolean")) { $name_array[] = $name; } foreach($name_array as $temp) $folder_content .= $temp; - closedir($handle); + closedir($handle); if ($folder_content == "...") return true; else return false; @@ -491,7 +491,7 @@ function dol_count_nb_of_line($file) while (!feof($fp)) { $line=fgets($fp); - // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines. + // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines. if (! $line === false) $nb++; } fclose($fp); @@ -542,61 +542,61 @@ function dol_filemtime($pathoffile) */ function dolReplaceInFile($srcfile, $arrayreplacement, $destfile='', $newmask=0, $indexdatabase=0) { - global $conf; + global $conf; - dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase); + dol_syslog("files.lib.php::dolReplaceInFile srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." indexdatabase=".$indexdatabase); - if (empty($srcfile)) return -1; - if (empty($destfile)) $destfile=$srcfile; + if (empty($srcfile)) return -1; + if (empty($destfile)) $destfile=$srcfile; - $destexists=dol_is_file($destfile); - if (($destfile != $srcfile) && $destexists) return 0; + $destexists=dol_is_file($destfile); + if (($destfile != $srcfile) && $destexists) return 0; - $tmpdestfile=$destfile.'.tmp'; + $tmpdestfile=$destfile.'.tmp'; - $newpathofsrcfile=dol_osencode($srcfile); - $newpathoftmpdestfile=dol_osencode($tmpdestfile); - $newpathofdestfile=dol_osencode($destfile); - $newdirdestfile=dirname($newpathofdestfile); + $newpathofsrcfile=dol_osencode($srcfile); + $newpathoftmpdestfile=dol_osencode($tmpdestfile); + $newpathofdestfile=dol_osencode($destfile); + $newdirdestfile=dirname($newpathofdestfile); - if ($destexists && ! is_writable($newpathofdestfile)) - { - dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING); - return -1; - } - if (! is_writable($newdirdestfile)) - { - dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING); - return -2; - } + if ($destexists && ! is_writable($newpathofdestfile)) + { + dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to overwrite target file", LOG_WARNING); + return -1; + } + if (! is_writable($newdirdestfile)) + { + dol_syslog("files.lib.php::dolReplaceInFile failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING); + return -2; + } - dol_delete_file($tmpdestfile); + dol_delete_file($tmpdestfile); - // Create $newpathoftmpdestfile from $newpathofsrcfile - $content=file_get_contents($newpathofsrcfile, 'r'); + // Create $newpathoftmpdestfile from $newpathofsrcfile + $content=file_get_contents($newpathofsrcfile, 'r'); - $content = make_substitutions($content, $arrayreplacement, null); + $content = make_substitutions($content, $arrayreplacement, null); - file_put_contents($newpathoftmpdestfile, $content); - @chmod($newpathoftmpdestfile, octdec($newmask)); + file_put_contents($newpathoftmpdestfile, $content); + @chmod($newpathoftmpdestfile, octdec($newmask)); - // Rename - $result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase); - if (! $result) - { - dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING); - return -3; - } - if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; - if (empty($newmask)) // This should no happen - { - dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING); - $newmask='0664'; - } + // Rename + $result=dol_move($newpathoftmpdestfile, $newpathofdestfile, $newmask, (($destfile == $srcfile)?1:0), 0, $indexdatabase); + if (! $result) + { + dol_syslog("files.lib.php::dolReplaceInFile failed to move tmp file to final dest", LOG_WARNING); + return -3; + } + if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; + if (empty($newmask)) // This should no happen + { + dol_syslog("Warning: dolReplaceInFile called with empty value for newmask and no default value defined", LOG_WARNING); + $newmask='0664'; + } - @chmod($newpathofdestfile, octdec($newmask)); + @chmod($newpathofdestfile, octdec($newmask)); - return 1; + return 1; } /** @@ -638,26 +638,26 @@ function dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1) if (! $overwriteifexists && $destexists) return 0; $newpathofsrcfile=dol_osencode($srcfile); - $newpathofdestfile=dol_osencode($destfile); - $newdirdestfile=dirname($newpathofdestfile); + $newpathofdestfile=dol_osencode($destfile); + $newdirdestfile=dirname($newpathofdestfile); - if ($destexists && ! is_writable($newpathofdestfile)) - { - dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING); - return -1; - } - if (! is_writable($newdirdestfile)) - { - dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING); - return -2; - } - // Copy with overwriting if exists - $result=@copy($newpathofsrcfile, $newpathofdestfile); + if ($destexists && ! is_writable($newpathofdestfile)) + { + dol_syslog("files.lib.php::dol_copy failed Permission denied to overwrite target file", LOG_WARNING); + return -1; + } + if (! is_writable($newdirdestfile)) + { + dol_syslog("files.lib.php::dol_copy failed Permission denied to write into target directory ".$newdirdestfile, LOG_WARNING); + return -2; + } + // Copy with overwriting if exists + $result=@copy($newpathofsrcfile, $newpathofdestfile); //$result=copy($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ if (! $result) { - dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING); - return -3; + dol_syslog("files.lib.php::dol_copy failed to copy", LOG_WARNING); + return -3; } if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; if (empty($newmask)) // This should no happen @@ -695,33 +695,33 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep $destexists=dol_is_dir($destfile); //if (! $overwriteifexists && $destexists) return 0; // The overwriteifexists is for files only, so propagated to dol_copy only. - if (! $destexists) - { - // We must set mask just before creating dir, becaause it can be set differently by dol_copy - umask(0); - $dirmaskdec=octdec($newmask); - if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK); - $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files - dol_mkdir($destfile, '', decoct($dirmaskdec)); - } + if (! $destexists) + { + // We must set mask just before creating dir, becaause it can be set differently by dol_copy + umask(0); + $dirmaskdec=octdec($newmask); + if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK); + $dirmaskdec |= octdec('0200'); // Set w bit required to be able to create content for recursive subdirs files + dol_mkdir($destfile, '', decoct($dirmaskdec)); + } $ossrcfile=dol_osencode($srcfile); $osdestfile=dol_osencode($destfile); - // Recursive function to copy all subdirectories and contents: + // Recursive function to copy all subdirectories and contents: if (is_dir($ossrcfile)) { - $dir_handle=opendir($ossrcfile); - while ($file=readdir($dir_handle)) - { - if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file)) - { - if (is_dir($ossrcfile."/".$file)) - { - //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists"); - $tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement); - } - else + $dir_handle=opendir($ossrcfile); + while ($file=readdir($dir_handle)) + { + if ($file != "." && $file != ".." && ! is_link($ossrcfile."/".$file)) + { + if (is_dir($ossrcfile."/".$file)) + { + //var_dump("xxx dolCopyDir $srcfile/$file, $destfile/$file, $newmask, $overwriteifexists"); + $tmpresult=dolCopyDir($srcfile."/".$file, $destfile."/".$file, $newmask, $overwriteifexists, $arrayreplacement); + } + else { $newfile = $file; // Replace destination filename with a new one @@ -732,30 +732,30 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep $newfile = str_replace($key, $val, $newfile); } } - $tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists); - } - // Set result - if ($result > 0 && $tmpresult >= 0) - { - // Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass - } - else - { - $result=$tmpresult; - } - if ($result < 0) break; + $tmpresult=dol_copy($srcfile."/".$file, $destfile."/".$newfile, $newmask, $overwriteifexists); + } + // Set result + if ($result > 0 && $tmpresult >= 0) + { + // Do nothing, so we don't set result to 0 if tmpresult is 0 and result was success in a previous pass + } + else + { + $result=$tmpresult; + } + if ($result < 0) break; - } - } - closedir($dir_handle); - } - else + } + } + closedir($dir_handle); + } + else { // Source directory does not exists - $result = -2; - } + $result = -2; + } - return $result; + return $result; } @@ -777,123 +777,123 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep */ function dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1) { - global $user, $db, $conf; - $result=false; + global $user, $db, $conf; + $result=false; - dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists); - $srcexists=dol_is_file($srcfile); - $destexists=dol_is_file($destfile); + dol_syslog("files.lib.php::dol_move srcfile=".$srcfile." destfile=".$destfile." newmask=".$newmask." overwritifexists=".$overwriteifexists); + $srcexists=dol_is_file($srcfile); + $destexists=dol_is_file($destfile); - if (! $srcexists) - { - dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request."); - return false; - } + if (! $srcexists) + { + dol_syslog("files.lib.php::dol_move srcfile does not exists. we ignore the move request."); + return false; + } - if ($overwriteifexists || ! $destexists) - { - $newpathofsrcfile=dol_osencode($srcfile); - $newpathofdestfile=dol_osencode($destfile); + if ($overwriteifexists || ! $destexists) + { + $newpathofsrcfile=dol_osencode($srcfile); + $newpathofdestfile=dol_osencode($destfile); - // Check virus - $testvirusarray=array(); - if ($testvirus) - { - $testvirusarray=dolCheckVirus($newpathofsrcfile); - if (count($testvirusarray)) - { - dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING); - return false; - } - } + // Check virus + $testvirusarray=array(); + if ($testvirus) + { + $testvirusarray=dolCheckVirus($newpathofsrcfile); + if (count($testvirusarray)) + { + dol_syslog("files.lib.php::dol_move canceled because a virus was found into source file. we ignore the move request.", LOG_WARNING); + return false; + } + } - $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ - if (! $result) - { - if ($destexists) - { - dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING); - // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions. - dol_delete_file($destfile); - $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ - } - else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING); - } + $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ + if (! $result) + { + if ($destexists) + { + dol_syslog("files.lib.php::dol_move Failed. We try to delete target first and move after.", LOG_WARNING); + // We force delete and try again. Rename function sometimes fails to replace dest file with some windows NTFS partitions. + dol_delete_file($destfile); + $result=@rename($newpathofsrcfile, $newpathofdestfile); // To see errors, remove @ + } + else dol_syslog("files.lib.php::dol_move Failed.", LOG_WARNING); + } - // Move ok - if ($result && $indexdatabase) - { - // Rename entry into ecm database - $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $srcfile); - $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $destfile); - if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file - { - $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore); - $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter); - //var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter); + // Move ok + if ($result && $indexdatabase) + { + // Rename entry into ecm database + $rel_filetorenamebefore = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $srcfile); + $rel_filetorenameafter = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $destfile); + if (! preg_match('/([\\/]temp[\\/]|[\\/]thumbs|\.meta$)/', $rel_filetorenameafter)) // If not a tmp file + { + $rel_filetorenamebefore = preg_replace('/^[\\/]/', '', $rel_filetorenamebefore); + $rel_filetorenameafter = preg_replace('/^[\\/]/', '', $rel_filetorenameafter); + //var_dump($rel_filetorenamebefore.' - '.$rel_filetorenameafter); - dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG); - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + dol_syslog("Try to rename also entries in database for full relative path before = ".$rel_filetorenamebefore." after = ".$rel_filetorenameafter, LOG_DEBUG); + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfiletarget=new EcmFiles($db); - $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter); - if ($resultecmtarget > 0) // An entry for target name already exists for target, we delete it, a new one will be created. - { - $ecmfiletarget->delete($user); - } + $ecmfiletarget=new EcmFiles($db); + $resultecmtarget = $ecmfiletarget->fetch(0, '', $rel_filetorenameafter); + if ($resultecmtarget > 0) // An entry for target name already exists for target, we delete it, a new one will be created. + { + $ecmfiletarget->delete($user); + } - $ecmfile=new EcmFiles($db); - $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore); - if ($resultecm > 0) // If an entry was found for src file, we use it to move entry - { - $filename = basename($rel_filetorenameafter); - $rel_dir = dirname($rel_filetorenameafter); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + $ecmfile=new EcmFiles($db); + $resultecm = $ecmfile->fetch(0, '', $rel_filetorenamebefore); + if ($resultecm > 0) // If an entry was found for src file, we use it to move entry + { + $filename = basename($rel_filetorenameafter); + $rel_dir = dirname($rel_filetorenameafter); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $resultecm = $ecmfile->update($user); - } - elseif ($resultecm == 0) // If no entry were found for src files, create/update target file - { - $filename = basename($rel_filetorenameafter); - $rel_dir = dirname($rel_filetorenameafter); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $resultecm = $ecmfile->update($user); + } + elseif ($resultecm == 0) // If no entry were found for src files, create/update target file + { + $filename = basename($rel_filetorenameafter); + $rel_dir = dirname($rel_filetorenameafter); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file - $ecmfile->fullpath_orig = $srcfile; - $ecmfile->gen_or_uploaded = 'unknown'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $resultecm = $ecmfile->create($user); - if ($resultecm < 0) - { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } - elseif ($resultecm < 0) - { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfile)); // $destfile is a full path to file + $ecmfile->fullpath_orig = $srcfile; + $ecmfile->gen_or_uploaded = 'unknown'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $resultecm = $ecmfile->create($user); + if ($resultecm < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } + elseif ($resultecm < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } - if ($resultecm > 0) $result=true; - else $result = false; - } - } + if ($resultecm > 0) $result=true; + else $result = false; + } + } - if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK; - $newmaskdec=octdec($newmask); - // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too) - // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this - // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories - @chmod($newpathofdestfile, $newmaskdec); - } + if (empty($newmask)) $newmask=empty($conf->global->MAIN_UMASK)?'0755':$conf->global->MAIN_UMASK; + $newmaskdec=octdec($newmask); + // Currently method is restricted to files (dol_delete_files previously used is for files, and mask usage if for files too) + // to allow mask usage for dir, we shoul introduce a new param "isdir" to 1 to complete newmask like this + // if ($isdir) $newmaskdec |= octdec('0111'); // Set x bit required for directories + @chmod($newpathofdestfile, $newmaskdec); + } - return $result; + return $result; } /** @@ -920,22 +920,22 @@ function dol_unescapefile($filename) */ function dolCheckVirus($src_file) { - global $conf; + global $conf; - if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) - { - if (! class_exists('AntiVir')) { - require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php'; - } - $antivir=new AntiVir($db); - $result = $antivir->dol_avscan_file($src_file); - if ($result < 0) // If virus or error, we stop here - { - $reterrors=$antivir->errors; - return $reterrors; - } - } - return array(); + if (! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) + { + if (! class_exists('AntiVir')) { + require_once DOL_DOCUMENT_ROOT.'/core/class/antivir.class.php'; + } + $antivir=new AntiVir($db); + $result = $antivir->dol_avscan_file($src_file); + if ($result < 0) // If virus or error, we stop here + { + $reterrors=$antivir->errors; + return $reterrors; + } + } + return array(); } @@ -975,68 +975,68 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable if (empty($reshook)) { - // If an upload error has been reported - if ($uploaderrorcode) - { - switch($uploaderrorcode) - { - case UPLOAD_ERR_INI_SIZE: // 1 - return 'ErrorFileSizeTooLarge'; - break; - case UPLOAD_ERR_FORM_SIZE: // 2 - return 'ErrorFileSizeTooLarge'; - break; - case UPLOAD_ERR_PARTIAL: // 3 - return 'ErrorPartialFile'; - break; - case UPLOAD_ERR_NO_TMP_DIR: // - return 'ErrorNoTmpDir'; - break; - case UPLOAD_ERR_CANT_WRITE: - return 'ErrorFailedToWriteInDir'; - break; - case UPLOAD_ERR_EXTENSION: - return 'ErrorUploadBlockedByAddon'; - break; - default: - break; - } - } + // If an upload error has been reported + if ($uploaderrorcode) + { + switch($uploaderrorcode) + { + case UPLOAD_ERR_INI_SIZE: // 1 + return 'ErrorFileSizeTooLarge'; + break; + case UPLOAD_ERR_FORM_SIZE: // 2 + return 'ErrorFileSizeTooLarge'; + break; + case UPLOAD_ERR_PARTIAL: // 3 + return 'ErrorPartialFile'; + break; + case UPLOAD_ERR_NO_TMP_DIR: // + return 'ErrorNoTmpDir'; + break; + case UPLOAD_ERR_CANT_WRITE: + return 'ErrorFailedToWriteInDir'; + break; + case UPLOAD_ERR_EXTENSION: + return 'ErrorUploadBlockedByAddon'; + break; + default: + break; + } + } - // If we need to make a virus scan - if (empty($disablevirusscan) && file_exists($src_file)) - { - $checkvirusarray=dolCheckVirus($src_file); - if (count($checkvirusarray)) - { - dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$checkvirusarray), LOG_WARNING); - return 'ErrorFileIsInfectedWithAVirus: '.join(',',$checkvirusarray); - } - } + // If we need to make a virus scan + if (empty($disablevirusscan) && file_exists($src_file)) + { + $checkvirusarray=dolCheckVirus($src_file); + if (count($checkvirusarray)) + { + dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: result='.$result.' errors='.join(',',$checkvirusarray), LOG_WARNING); + return 'ErrorFileIsInfectedWithAVirus: '.join(',',$checkvirusarray); + } + } - // Security: - // Disallow file with some extensions. We rename them. - // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code. - if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) - { - $file_name.= '.noexe'; - } + // Security: + // Disallow file with some extensions. We rename them. + // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code. + if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) + { + $file_name.= '.noexe'; + } - // Security: - // We refuse cache files/dirs, upload using .. and pipes into filenames. - if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file)) - { - dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING); - return -1; - } + // Security: + // We refuse cache files/dirs, upload using .. and pipes into filenames. + if (preg_match('/^\./',$src_file) || preg_match('/\.\./',$src_file) || preg_match('/[<>|]/',$src_file)) + { + dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING); + return -1; + } - // Security: - // On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers. - if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file)) - { - dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING); - return -2; - } + // Security: + // On interdit fichiers caches, remontees de repertoire ainsi que les pipe dans les noms de fichiers. + if (preg_match('/^\./',$dest_file) || preg_match('/\.\./',$dest_file) || preg_match('/[<>|]/',$dest_file)) + { + dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING); + return -2; + } } if ($reshook < 0) // At least one blocking error returned by one hook @@ -1108,8 +1108,8 @@ function dol_delete_file($file,$disableglob=0,$nophperrors=0,$nohook=0,$object=n // We refuse transversal using .. and pipes into filenames. if (preg_match('/\.\./',$file) || preg_match('/[<>|]/',$file)) { - dol_syslog("Refused to delete file ".$file, LOG_WARNING); - return False; + dol_syslog("Refused to delete file ".$file, LOG_WARNING); + return False; } if (empty($nohook)) @@ -1150,27 +1150,27 @@ function dol_delete_file($file,$disableglob=0,$nophperrors=0,$nohook=0,$object=n else $ok=unlink($filename); if ($ok) { - dol_syslog("Removed file ".$filename, LOG_DEBUG); + dol_syslog("Removed file ".$filename, LOG_DEBUG); - // Delete entry into ecm database - $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filename); - if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) // If not a tmp file - { - $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete); + // Delete entry into ecm database + $rel_filetodelete = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $filename); + if (! preg_match('/(\/temp\/|\/thumbs\/|\.meta$)/', $rel_filetodelete)) // If not a tmp file + { + $rel_filetodelete = preg_replace('/^[\\/]/', '', $rel_filetodelete); - dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG); - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($db); - $result = $ecmfile->fetch(0, '', $rel_filetodelete); - if ($result >= 0 && $ecmfile->id > 0) - { - $result = $ecmfile->delete($user); - } - if ($result < 0) - { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } + dol_syslog("Try to remove also entries in database for full relative path = ".$rel_filetodelete, LOG_DEBUG); + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($db); + $result = $ecmfile->fetch(0, '', $rel_filetodelete); + if ($result >= 0 && $ecmfile->id > 0) + { + $result = $ecmfile->delete($user); + } + if ($result < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } } else dol_syslog("Failed to remove file ".$filename, LOG_WARNING); // TODO Failure to remove can be because file was already removed or because of permission @@ -1207,12 +1207,12 @@ function dol_delete_dir($dir,$nophperrors=0) // We refuse transversal using .. and pipes into filenames. if (preg_match('/\.\./',$dir) || preg_match('/[<>|]/',$dir)) { - dol_syslog("Refused to delete dir ".$dir, LOG_WARNING); - return False; + dol_syslog("Refused to delete dir ".$dir, LOG_WARNING); + return False; } - $dir_osencoded=dol_osencode($dir); - return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded)); + $dir_osencoded=dol_osencode($dir); + return ($nophperrors?@rmdir($dir_osencoded):rmdir($dir_osencoded)); } /** @@ -1227,42 +1227,42 @@ function dol_delete_dir($dir,$nophperrors=0) */ function dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0) { - dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG); - if (dol_is_dir($dir)) - { - $dir_osencoded=dol_osencode($dir); - if ($handle = opendir("$dir_osencoded")) - { - while (false !== ($item = readdir($handle))) - { - if (! utf8_check($item)) $item=utf8_encode($item); // should be useless + dol_syslog("functions.lib:dol_delete_dir_recursive ".$dir,LOG_DEBUG); + if (dol_is_dir($dir)) + { + $dir_osencoded=dol_osencode($dir); + if ($handle = opendir("$dir_osencoded")) + { + while (false !== ($item = readdir($handle))) + { + if (! utf8_check($item)) $item=utf8_encode($item); // should be useless - if ($item != "." && $item != "..") - { - if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item"))) - { - $count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted); - } - else - { - $result=dol_delete_file("$dir/$item", 1, $nophperrors); - $count++; - if ($result) $countdeleted++; - } - } - } - closedir($handle); + if ($item != "." && $item != "..") + { + if (is_dir(dol_osencode("$dir/$item")) && ! is_link(dol_osencode("$dir/$item"))) + { + $count=dol_delete_dir_recursive("$dir/$item", $count, $nophperrors, 0, $countdeleted); + } + else + { + $result=dol_delete_file("$dir/$item", 1, $nophperrors); + $count++; + if ($result) $countdeleted++; + } + } + } + closedir($handle); - if (empty($onlysub)) - { - $result=dol_delete_dir($dir, $nophperrors); - $count++; - if ($result) $countdeleted++; - } - } - } + if (empty($onlysub)) + { + $result=dol_delete_dir($dir, $nophperrors); + $count++; + if ($result) $countdeleted++; + } + } + } - return $count; + return $count; } @@ -1279,15 +1279,15 @@ function dol_delete_preview($object) // Define parent dir of elements $element = $object->element; - if ($object->element == 'order_supplier') $dir = $conf->fournisseur->dir_output.'/commande'; - elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->dir_output.'/facture'; - elseif ($object->element == 'project') $dir = $conf->projet->dir_output; - elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending'; - elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt'; - elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output; - else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output; + if ($object->element == 'order_supplier') $dir = $conf->fournisseur->commande->dir_output; + elseif ($object->element == 'invoice_supplier') $dir = $conf->fournisseur->facture->dir_output; + elseif ($object->element == 'project') $dir = $conf->projet->dir_output; + elseif ($object->element == 'shipping') $dir = $conf->expedition->dir_output.'/sending'; + elseif ($object->element == 'delivery') $dir = $conf->expedition->dir_output.'/receipt'; + elseif ($object->element == 'fichinter') $dir = $conf->ficheinter->dir_output; + else $dir=empty($conf->$element->dir_output)?'':$conf->$element->dir_output; - if (empty($dir)) return 'ErrorObjectNoSupportedByFunction'; + if (empty($dir)) return 'ErrorObjectNoSupportedByFunction'; $refsan = dol_sanitizeFileName($object->ref); $dir = $dir . "/" . $refsan ; @@ -1425,7 +1425,7 @@ function dol_init_file_process($pathtoscan='', $trackid='') $listofmimes[]=dol_mimetype($val['name']); } } - $keytoavoidconflict = empty($trackid)?'':'-'.$trackid; + $keytoavoidconflict = empty($trackid)?'':'-'.$trackid; $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths); $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames); $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes); @@ -1475,19 +1475,17 @@ function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesessio $destfull=$upload_dir . "/" . $TFile['name'][$i]; $destfile=$TFile['name'][$i]; - $savingdocmask = dol_sanitizeFileName($savingdocmask); - if ($savingdocmask) { $destfull=$upload_dir . "/" . preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask); $destfile=preg_replace('/__file__/',$TFile['name'][$i],$savingdocmask); } - // lowercase extension + // dol_sanitizeFileName the file name and lowercase extension $info = pathinfo($destfull); - $destfull = $info['dirname'].'/'.$info['filename'].'.'.strtolower($info['extension']); + $destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].'.'.strtolower($info['extension'])); $info = pathinfo($destfile); - $destfile = $info['filename'].'.'.strtolower($info['extension']); + $destfile = dol_sanitizeFileName($info['filename'].'.'.strtolower($info['extension'])); $resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles); @@ -1502,14 +1500,14 @@ function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesessio { if (image_format_supported($destfull) == 1) { - // Create thumbs - // We can't use $object->addThumbs here because there is no $object known + // Create thumbs + // We can't use $object->addThumbs here because there is no $object known - // Used on logon for example - $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs"); - // Create mini thumbs for image (Ratio is near 16/9) - // Used on menu or for setup page for example - $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs"); + // Used on logon for example + $imgThumbSmall = vignette($destfull, $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs"); + // Create mini thumbs for image (Ratio is near 16/9) + // Used on menu or for setup page for example + $imgThumbMini = vignette($destfull, $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs"); } } @@ -1525,29 +1523,29 @@ function dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesessio // Update table of files if ($donotupdatesession) { - $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); + $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); - if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir - { - $filename = basename($destfile); - $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); - $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); + if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) // If not a tmp dir + { + $filename = basename($destfile); + $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); + $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; - $ecmfile=new EcmFiles($db); - $ecmfile->filepath = $rel_dir; - $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); // MD5 of file content - $ecmfile->fullpath_orig = $TFile['name'][$i]; - $ecmfile->gen_or_uploaded = 'uploaded'; - $ecmfile->description = ''; // indexed content - $ecmfile->keyword = ''; // keyword content - $result = $ecmfile->create($user); - if ($result < 0) - { - setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); - } - } + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($db); + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // MD5 of file content + $ecmfile->fullpath_orig = $TFile['name'][$i]; + $ecmfile->gen_or_uploaded = 'uploaded'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $result = $ecmfile->create($user); + if ($result < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } } $res = 1; @@ -1618,7 +1616,7 @@ function dol_remove_file_process($filenb,$donotupdatesession=0,$donotdeletefile= $listofpaths=array(); $listofnames=array(); $listofmimes=array(); - $keytoavoidconflict = empty($trackid)?'':'-'.$trackid; + $keytoavoidconflict = empty($trackid)?'':'-'.$trackid; 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]); @@ -1708,48 +1706,48 @@ function dol_convert_file($fileinput, $ext='png', $fileoutput='') */ function dol_compress_file($inputfile, $outputfile, $mode="gz") { - $foundhandler=0; + $foundhandler=0; - try - { - $data = implode("", file(dol_osencode($inputfile))); - if ($mode == 'gz') { $foundhandler=1; $compressdata = gzencode($data, 9); } - elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); } - elseif ($mode == 'zip') - { - if (defined('ODTPHP_PATHTOPCLZIP')) - { - $foundhandler=1; + try + { + $data = implode("", file(dol_osencode($inputfile))); + if ($mode == 'gz') { $foundhandler=1; $compressdata = gzencode($data, 9); } + elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); } + elseif ($mode == 'zip') + { + if (defined('ODTPHP_PATHTOPCLZIP')) + { + $foundhandler=1; - include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; - $archive = new PclZip($outputfile); - $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile)); - //$archive->add($inputfile); - return 1; - } - } + include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; + $archive = new PclZip($outputfile); + $archive->add($inputfile, PCLZIP_OPT_REMOVE_PATH, dirname($inputfile)); + //$archive->add($inputfile); + return 1; + } + } - if ($foundhandler) - { - $fp = fopen($outputfile, "w"); - fwrite($fp, $compressdata); - fclose($fp); - return 1; - } - else - { - dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR); - return -2; - } - } - catch (Exception $e) - { - global $langs, $errormsg; - $langs->load("errors"); - dol_syslog("Failed to open file ".$outputfile,LOG_ERR); - $errormsg=$langs->trans("ErrorFailedToWriteInDir"); - return -1; - } + if ($foundhandler) + { + $fp = fopen($outputfile, "w"); + fwrite($fp, $compressdata); + fclose($fp); + return 1; + } + else + { + dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR); + return -2; + } + } + catch (Exception $e) + { + global $langs, $errormsg; + $langs->load("errors"); + dol_syslog("Failed to open file ".$outputfile,LOG_ERR); + $errormsg=$langs->trans("ErrorFailedToWriteInDir"); + return -1; + } } /** @@ -1761,17 +1759,17 @@ function dol_compress_file($inputfile, $outputfile, $mode="gz") */ function dol_uncompress($inputfile,$outputdir) { - global $langs; + global $langs; - if (defined('ODTPHP_PATHTOPCLZIP')) - { - dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir); - include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; - $archive = new PclZip($inputfile); - $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir); - //var_dump($result); - if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true)); - else + if (defined('ODTPHP_PATHTOPCLZIP')) + { + dol_syslog("Constant ODTPHP_PATHTOPCLZIP for pclzip library is set to ".ODTPHP_PATHTOPCLZIP.", so we use Pclzip to unzip into ".$outputdir); + include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php'; + $archive = new PclZip($inputfile); + $result=$archive->extract(PCLZIP_OPT_PATH, $outputdir); + //var_dump($result); + if (! is_array($result) && $result <= 0) return array('error'=>$archive->errorInfo(true)); + else { $ok=1; $errmsg=''; // Loop on each file to check result for unzipping file @@ -1789,26 +1787,26 @@ function dol_uncompress($inputfile,$outputdir) if ($ok) return array(); else return array('error'=>$errmsg); } - } + } - if (class_exists('ZipArchive')) - { - dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir); - $zip = new ZipArchive; - $res = $zip->open($inputfile); - if ($res === TRUE) - { - $zip->extractTo($outputdir.'/'); - $zip->close(); - return array(); - } - else - { - return array('error'=>'ErrUnzipFails'); - } - } + if (class_exists('ZipArchive')) + { + dol_syslog("Class ZipArchive is set so we unzip using ZipArchive to unzip into ".$outputdir); + $zip = new ZipArchive; + $res = $zip->open($inputfile); + if ($res === TRUE) + { + $zip->extractTo($outputdir.'/'); + $zip->close(); + return array(); + } + else + { + return array('error'=>'ErrUnzipFails'); + } + } - return array('error'=>'ErrNoZipEngine'); + return array('error'=>'ErrNoZipEngine'); } @@ -1822,25 +1820,25 @@ function dol_uncompress($inputfile,$outputdir) */ function dol_compress_dir($inputdir, $outputfile, $mode="zip") { - $foundhandler=0; + $foundhandler=0; - dol_syslog("Try to zip dir ".$inputdir." into ".$outputdir." mode=".$mode); + dol_syslog("Try to zip dir ".$inputdir." into ".$outputdir." mode=".$mode); - if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile))) - { - global $langs, $errormsg; - $langs->load("errors"); - $errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile); + if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile))) + { + global $langs, $errormsg; + $langs->load("errors"); + $errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile); return -3; - } + } - try - { - if ($mode == 'gz') { $foundhandler=0; } - elseif ($mode == 'bz') { $foundhandler=0; } - elseif ($mode == 'zip') - { - /*if (defined('ODTPHP_PATHTOPCLZIP')) + try + { + if ($mode == 'gz') { $foundhandler=0; } + elseif ($mode == 'bz') { $foundhandler=0; } + elseif ($mode == 'zip') + { + /*if (defined('ODTPHP_PATHTOPCLZIP')) { $foundhandler=0; // TODO implement this @@ -1851,61 +1849,61 @@ function dol_compress_dir($inputdir, $outputfile, $mode="zip") return 1; } else*/ - if (class_exists('ZipArchive')) - { - $foundhandler=1; + if (class_exists('ZipArchive')) + { + $foundhandler=1; - // Initialize archive object - $zip = new ZipArchive(); - $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE); + // Initialize archive object + $zip = new ZipArchive(); + $result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE); - // Create recursive directory iterator - /** @var SplFileInfo[] $files */ - $files = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($inputdir), - RecursiveIteratorIterator::LEAVES_ONLY - ); + // Create recursive directory iterator + /** @var SplFileInfo[] $files */ + $files = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($inputdir), + RecursiveIteratorIterator::LEAVES_ONLY + ); - foreach ($files as $name => $file) - { - // Skip directories (they would be added automatically) - if (!$file->isDir()) - { - // Get real and relative path for current file - $filePath = $file->getRealPath(); - $relativePath = substr($filePath, strlen($inputdir) + 1); + foreach ($files as $name => $file) + { + // Skip directories (they would be added automatically) + if (!$file->isDir()) + { + // Get real and relative path for current file + $filePath = $file->getRealPath(); + $relativePath = substr($filePath, strlen($inputdir) + 1); - // Add current file to archive - $zip->addFile($filePath, $relativePath); - } - } + // Add current file to archive + $zip->addFile($filePath, $relativePath); + } + } - // Zip archive will be created only after closing object - $zip->close(); + // Zip archive will be created only after closing object + $zip->close(); - return 1; - } - } + return 1; + } + } - if (! $foundhandler) - { - dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR); - return -2; - } - else - { - return 0; - } - } - catch (Exception $e) - { - global $langs, $errormsg; - $langs->load("errors"); - dol_syslog("Failed to open file ".$outputfile, LOG_ERR); - dol_syslog($e->getMessage(), LOG_ERR); - $errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile); - return -1; - } + if (! $foundhandler) + { + dol_syslog("Try to zip with format ".$mode." with no handler for this format",LOG_ERR); + return -2; + } + else + { + return 0; + } + } + catch (Exception $e) + { + global $langs, $errormsg; + $langs->load("errors"); + dol_syslog("Failed to open file ".$outputfile, LOG_ERR); + dol_syslog($e->getMessage(), LOG_ERR); + $errormsg=$langs->trans("ErrorFailedToWriteInDir",$outputfile); + return -1; + } } @@ -1922,8 +1920,8 @@ function dol_compress_dir($inputdir, $outputfile, $mode="zip") */ function dol_most_recent_file($dir,$regexfilter='',$excludefilter=array('(\.meta|_preview.*\.png)$','^\.'),$nohook=false,$mode='') { - $tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,$mode,$nohook); - return $tmparray[0]; + $tmparray=dol_dir_list($dir,'files',0,$regexfilter,$excludefilter,'date',SORT_DESC,$mode,$nohook); + return $tmparray[0]; } /** @@ -1953,7 +1951,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, $sqlprotectagainstexternals=''; $ret=array(); - // Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10' + // Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10' if (empty($refname)) $refname=basename(dirname($original_file)."/"); $relative_original_file = $original_file; @@ -1962,20 +1960,20 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, $lire='lire'; $read='read'; $download='download'; if ($mode == 'write') { - $lire='creer'; $read='write'; $download='upload'; + $lire='creer'; $read='write'; $download='upload'; } // Wrapping for miscellaneous medias files if ($modulepart == 'medias' && !empty($dolibarr_main_data_root)) { - $accessallowed=1; - $original_file=$conf->medias->multidir_output[$entity].'/'.$original_file; + $accessallowed=1; + $original_file=$conf->medias->multidir_output[$entity].'/'.$original_file; } // Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root)) { - $accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file))); - $original_file=$dolibarr_main_data_root.'/'.$original_file; + $accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file))); + $original_file=$dolibarr_main_data_root.'/'.$original_file; } // Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root)) @@ -1984,8 +1982,8 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, $tmp=explode(',', $dolibarr_main_document_root_alt); $dirins = $tmp[0]; - $accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file))); - $original_file=$dirins.'/'.$original_file; + $accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file))); + $original_file=$dirins.'/'.$original_file; } // Wrapping for some images elseif (($modulepart == 'mycompany' || $modulepart == 'companylogo') && !empty($conf->mycompany->dir_output)) @@ -2026,38 +2024,38 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, // Wrapping pour les apercu intervention elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output)) { - if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1; - $original_file=$conf->ficheinter->dir_output.'/'.$original_file; + if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1; + $original_file=$conf->ficheinter->dir_output.'/'.$original_file; } // Wrapping pour les apercu conat elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output)) { - if ($fuser->rights->contrat->{$lire}) $accessallowed=1; - $original_file=$conf->contrat->dir_output.'/'.$original_file; + if ($fuser->rights->contrat->{$lire}) $accessallowed=1; + $original_file=$conf->contrat->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier proposal elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output)) { - if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1; - $original_file=$conf->supplier_proposal->dir_output.'/'.$original_file; + if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1; + $original_file=$conf->supplier_proposal->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier order elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output)) { - if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file; + if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1; + $original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier invoice elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output)) { - if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file; + if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1; + $original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file; } // Wrapping pour les apercu supplier invoice elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output)) { - if ($fuser->rights->expensereport->{$lire}) $accessallowed=1; - $original_file=$conf->expensereport->dir_output.'/'.$original_file; + if ($fuser->rights->expensereport->{$lire}) $accessallowed=1; + $original_file=$conf->expensereport->dir_output.'/'.$original_file; } // Wrapping pour les images des stats propales elseif ($modulepart == 'propalstats' && !empty($conf->propal->dir_temp)) @@ -2085,7 +2083,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output)) { if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1; - $original_file=$conf->fournisseur->dir_output.'/facture/temp/'.$original_file; + $original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file; } // Wrapping pour les images des stats expeditions elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp)) @@ -2183,13 +2181,13 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, // Wrapping for users else if ($modulepart == 'user' && !empty($conf->user->dir_output)) { - $canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire}); - if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card - if ($canreaduser || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->user->dir_output.'/'.$original_file; + $canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire}); + if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card + if ($canreaduser || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->user->dir_output.'/'.$original_file; } // Wrapping for third parties @@ -2226,67 +2224,67 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, // Wrapping for mass actions else if ($modulepart == 'massfilesarea_proposals' && !empty($conf->propal->dir_output)) { - if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->propal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->propal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_orders') { - if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_invoices') { - if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_expensereport') { - if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_interventions') { - if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->propal->dir_output)) { - if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_supplier_order') { - if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_supplier_invoice') { - if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file)) - { - $accessallowed=1; - } - $original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; + if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file; } else if ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output)) { @@ -2579,15 +2577,15 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, $original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file; } - // GENERIC Wrapping - // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser - // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp - // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser - // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart - else + // GENERIC Wrapping + // If modulepart=module_user_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp/iduser + // If modulepart=module_temp Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/temp + // If modulepart=module_user Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart/iduser + // If modulepart=module Allows any module to open a file if file is in directory called DOL_DATA_ROOT/modulepart + else { - if (preg_match('/^specimen/i',$original_file)) $accessallowed=1; // If link to a file called specimen. Test must be done before changing $original_file int full path. - if ($fuser->admin) $accessallowed=1; // If user is admin + if (preg_match('/^specimen/i',$original_file)) $accessallowed=1; // If link to a file called specimen. Test must be done before changing $original_file int full path. + if ($fuser->admin) $accessallowed=1; // If user is admin // Define $accessallowed if (preg_match('/^([a-z]+)_user_temp$/i',$modulepart,$reg)) @@ -2597,7 +2595,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')'); exit; } - if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; + if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; $original_file=$conf->{$reg[1]}->dir_temp.'/'.$fuser->id.'/'.$original_file; } else if (preg_match('/^([a-z]+)_temp$/i',$modulepart,$reg)) @@ -2607,7 +2605,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')'); exit; } - if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; + if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; $original_file=$conf->{$reg[1]}->dir_temp.'/'.$original_file; } else if (preg_match('/^([a-z]+)_user$/i',$modulepart,$reg)) @@ -2617,7 +2615,7 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, dol_print_error('','Error call dol_check_secure_access_document with not supported value for modulepart parameter ('.$modulepart.')'); exit; } - if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; + if ($fuser->rights->{$reg[1]}->{$lire} || $fuser->rights->{$reg[1]}->{$read} || ($fuser->rights->{$reg[1]}->{$download})) $accessallowed=1; $original_file=$conf->{$reg[1]}->dir_output.'/'.$fuser->id.'/'.$original_file; } else @@ -2681,10 +2679,10 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, */ function dol_filecache($directory, $filename, $object) { - if (! dol_is_dir($directory)) dol_mkdir($directory); - $cachefile = $directory . $filename; - file_put_contents($cachefile, serialize($object), LOCK_EX); - @chmod($cachefile, 0644); + if (! dol_is_dir($directory)) dol_mkdir($directory); + $cachefile = $directory . $filename; + file_put_contents($cachefile, serialize($object), LOCK_EX); + @chmod($cachefile, 0644); } /** @@ -2697,10 +2695,10 @@ function dol_filecache($directory, $filename, $object) */ function dol_cache_refresh($directory, $filename, $cachetime) { - $now = dol_now(); - $cachefile = $directory . $filename; - $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile); - return $refresh; + $now = dol_now(); + $cachefile = $directory . $filename; + $refresh = !file_exists($cachefile) || ($now-$cachetime) > dol_filemtime($cachefile); + return $refresh; } /** @@ -2712,7 +2710,7 @@ function dol_cache_refresh($directory, $filename, $cachetime) */ function dol_readcachefile($directory, $filename) { - $cachefile = $directory . $filename; - $object = unserialize(file_get_contents($cachefile)); - return $object; + $cachefile = $directory . $filename; + $object = unserialize(file_get_contents($cachefile)); + return $object; } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index f5b4b755b8d..2626e917460 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -102,18 +102,21 @@ function getDoliDBInstance($type, $host, $user, $pass, $name, $port) /** * Get list of entity id to use. * - * @param string $element Current element - * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource', - * 'product', 'productprice', 'stock', - * 'propal', 'supplier_proposal', 'facture', 'facture_fourn', - * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user', - * 'commande', 'commande_fournisseur', 'expedition', 'intervention', 'survey', - * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project', - * 'email_template', 'event', - * @param int $shared 1=Return id of current entity + shared entities (default), 0=Return id of current entity only + * @param string $element Current element + * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource', + * 'product', 'productprice', 'stock', + * 'propal', 'supplier_proposal', 'facture', 'facture_fourn', + * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user', + * 'commande', 'commande_fournisseur', 'expedition', 'intervention', 'survey', + * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project', + * 'email_template', 'event', + * 'c_paiement', ... + * @param int $shared 0=Return id of current entity only, + * 1=Return id of current entity + shared entities (default) + * @param int $forceentity Entity id * @return mixed Entity id(s) to use */ -function getEntity($element, $shared=1) +function getEntity($element, $shared=1, $forceentity=null) { global $conf, $mc; @@ -124,7 +127,7 @@ function getEntity($element, $shared=1) if (is_object($mc)) { - return $mc->getEntity($element, $shared); + return $mc->getEntity($element, $shared, $forceentity); } else { @@ -237,6 +240,16 @@ function dol_shutdown() dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_INFO)); } +/** + * Return true if we are in a context of submitting a parameter + * + * @param string $paramname Name or parameter to test + * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty) + */ +function GETPOSTISSET($paramname) +{ + return (isset($_POST[$paramname]) || isset($_GET[$paramname])); +} /** * Return value of a param into GET or POST supervariable. @@ -262,17 +275,17 @@ function dol_shutdown() */ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=NULL) { - global $mysoc,$user,$conf; + global $mysoc,$user,$conf; - if (empty($paramname)) return 'BadFirstParameterForGETPOST'; - if (empty($check)) - { - dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING); - // Enable this line to know who call the GETPOST with '' $check parameter. - //var_dump(debug_backtrace()[0]); - } + if (empty($paramname)) return 'BadFirstParameterForGETPOST'; + if (empty($check)) + { + dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING); + // Enable this line to know who call the GETPOST with '' $check parameter. + //var_dump(debug_backtrace()[0]); + } - if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:''); + if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:''); elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:''; elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:''; elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:''); @@ -282,257 +295,272 @@ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=N if (empty($method) || $method == 3 || $method == 4) { - $relativepathstring = $_SERVER["PHP_SELF"]; - // Clean $relativepathstring - if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring); - $relativepathstring = preg_replace('/^\//', '', $relativepathstring); - $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); + $relativepathstring = $_SERVER["PHP_SELF"]; + // Clean $relativepathstring + if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring); + $relativepathstring = preg_replace('/^\//', '', $relativepathstring); + $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); //var_dump($relativepathstring); //var_dump($user->default_values); - // Code for search criteria persistence. - // Retrieve values if restore_lastsearch_values is set and there is saved values - if (! empty($_GET['restore_lastsearch_values']) && ! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // Keep $_GET here - { - $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true); - if (is_array($tmp)) - { - foreach($tmp as $key => $val) - { - if ($key == $paramname) - { - $out=$val; - break; - } - } - } - } - // Else, retreive default values if we are not doing a sort - elseif (! isset($_GET['sortfield']) && ! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set - { - if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - { - if (! empty($user->default_values)) // $user->default_values defined from menu default values - { - $qualified=1; - if (isset($user->default_values[$relativepathstring]['createform_queries'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] - { - $tmpqueryarraytohave=explode('&', $user->default_values[$relativepathstring]['createform_queries']); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - foreach($tmpqueryarraytohave as $tmpquerytohave) - { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $qualified=0; - } - } - if ($qualified) + // Code for search criteria persistence. + // Retrieve values if restore_lastsearch_values is set and there is saved values + if (! empty($_GET['restore_lastsearch_values']) && ! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // Keep $_GET here + { + $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true); + if (is_array($tmp)) + { + foreach($tmp as $key => $val) + { + if ($key == $paramname) { - //var_dump($user->default_values[$relativepathstring]['createform']); - if (isset($user->default_values[$relativepathstring]['createform'][$paramname])) $out = $user->default_values[$relativepathstring]['createform'][$paramname]; + $out=$val; + break; } - } - } - // Management of default search_filters and sort order - //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) - { - if (! empty($user->default_values)) // $user->default_values defined from menu default values - { - //var_dump($user->default_values[$relativepathstring]); - if ($paramname == 'sortfield') // Sorted on which fields ? - { - $qualified=1; - if (isset($user->default_values[$relativepathstring]['sortorder_queries'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] - { - $tmpqueryarraytohave=explode('&', $user->default_values[$relativepathstring]['sortorder_queries']); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - foreach($tmpqueryarraytohave as $tmpquerytohave) - { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $qualified=0; - } - } - if ($qualified) + } + } + } + // Else, retreive default values if we are not doing a sort + elseif (! isset($_GET['sortfield']) && ! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set + { + if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + { + if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + { + if (isset($user->default_values[$relativepathstring]['createform'])) + { + foreach($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) { - if (isset($user->default_values[$relativepathstring]['sortorder'])) // We will use the key of $user->default_values[path][sortorder] - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val) - { - if ($out) $out.=', '; - $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace); - } - } + $qualified = 0; + if ($defkey != '_noquery_') + { + $tmpqueryarraytohave=explode('&', $defkey); + $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru=0; + foreach($tmpqueryarraytohave as $tmpquerytohave) + { + if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + } + if (! $foundintru) $qualified=1; + //var_dump($defkey.'-'.$qualified); + } + else $qualified = 1; + + if ($qualified) + { + //var_dump($user->default_values[$relativepathstring][$defkey]['createform']); + if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) + { + $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname]; + break; + } + } } - } - elseif ($paramname == 'sortorder') // ASC or DESC ? - { - $qualified=1; - if (isset($user->default_values[$relativepathstring]['sortorder_queries'])) - { - $tmpqueryarraytohave=explode('&', $user->default_values[$relativepathstring]['sortorder_queries']); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - foreach($tmpqueryarraytohave as $tmpquerytohave) - { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $qualified=0; - } - } - if ($qualified) + } + } + } + // Management of default search_filters and sort order + //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname])) + { + if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values' + { + //var_dump($user->default_values[$relativepathstring]); + if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ? + { + if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...'] { - if (isset($user->default_values[$relativepathstring]['sortorder'])) // We will use the val of $user->default_values[path][sortorder] - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val) - { - if ($out) $out.=', '; - $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace); - } - } + foreach($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) + { + $qualified = 0; + if ($defkey != '_noquery_') + { + $tmpqueryarraytohave=explode('&', $defkey); + $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru=0; + foreach($tmpqueryarraytohave as $tmpquerytohave) + { + if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + } + if (! $foundintru) $qualified=1; + //var_dump($defkey.'-'.$qualified); + } + else $qualified = 1; + + if ($qualified) + { + $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + foreach($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) + { + if ($out) $out.=', '; + if ($paramname == 'sortfield') + { + $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace); + } + if ($paramname == 'sortorder') + { + $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace); + } + } + //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?) + } + } } - } - elseif (isset($user->default_values[$relativepathstring]['filters'][$paramname])) - { - $qualified=1; - if (isset($user->default_values[$relativepathstring]['filters_queries'])) - { - $tmpqueryarraytohave=explode('&', $user->default_values[$relativepathstring]['filters_queries']); - $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); - foreach($tmpqueryarraytohave as $tmpquerytohave) - { - if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $qualified=0; - } - } - if ($qualified) + } + elseif (isset($user->default_values[$relativepathstring]['filters'])) + { + foreach($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { - if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) - { - // We made a search from quick search menu, do we still use default filter ? - if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$paramname], '', $forbidden_chars_to_replace); - } - } - else - { - $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , - $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$paramname], '', $forbidden_chars_to_replace); - } + $qualified = 0; + if ($defkey != '_noquery_') + { + $tmpqueryarraytohave=explode('&', $defkey); + $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING'])); + $foundintru=0; + foreach($tmpqueryarraytohave as $tmpquerytohave) + { + if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1; + } + if (! $foundintru) $qualified=1; + //var_dump($defkey.'-'.$qualified); + } + else $qualified = 1; + + if ($qualified) + { + if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) + { + // We made a search from quick search menu, do we still use default filter ? + if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) + { + $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); + } + } + else + { + $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and , + $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace); + } + break; + } } - } - } - } - } + } + } + } + } } - // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable paramaters) - // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOUNTRYID__, __USERID__, __ENTITYID__, ... - // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text. - if (! is_array($out) && empty($_POST[$paramname])) - { - $maxloop=20; $loopnb=0; // Protection against infinite loop - while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. - { - $loopnb++; $newout = ''; + // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable paramaters) + // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOUNTRYID__, __USERID__, __ENTITYID__, ... + // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text. + if (! is_array($out) && empty($_POST[$paramname])) + { + $maxloop=20; $loopnb=0; // Protection against infinite loop + while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side. + { + $loopnb++; $newout = ''; - if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; } - elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; } - elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; } - elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } - elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } - elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } - elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } - elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } - elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } - elseif ($reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') - { - $newout = $mysoc->country_id; - } - elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') - { - $newout = $user->id; - } - elseif ($reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') - { - $newout = $user->fk_user; - } - elseif ($reg[1] == 'ENTITYID') - { - $newout = $conf->entity; - } - else $newout = ''; // Key not found, we replace with empty string - //var_dump('__'.$reg[1].'__ -> '.$newout); - $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out); - } - } + if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; } + elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; } + elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; } + elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); } + elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; } + elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; } + elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); } + elseif ($reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') + { + $newout = $mysoc->country_id; + } + elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') + { + $newout = $user->id; + } + elseif ($reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') + { + $newout = $user->fk_user; + } + elseif ($reg[1] == 'ENTITYID') + { + $newout = $conf->entity; + } + else $newout = ''; // Key not found, we replace with empty string + //var_dump('__'.$reg[1].'__ -> '.$newout); + $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out); + } + } - // Check is done after replacement - switch ($check) - { - case 'none': - break; - case 'int': // Check param is a numeric value (integer but also float or hexadecimal) - if (! is_numeric($out)) { $out=''; } - break; - case 'intcomma': - if (preg_match('/[^0-9,]+/i',$out)) $out=''; - break; - case 'alpha': - $out=trim($out); - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' is dangerous because it allows dir transversals - if (preg_match('/"/',$out)) $out=''; - else if (preg_match('/\.\.\//',$out)) $out=''; - break; - case 'san_alpha': - $out=filter_var($out,FILTER_SANITIZE_STRING); - break; - case 'aZ': - $out=trim($out); - if (preg_match('/[^a-z]+/i',$out)) $out=''; - break; - case 'aZ09': - $out=trim($out); - if (preg_match('/[^a-z0-9_\-\.]+/i',$out)) $out=''; - break; - case 'array': - if (! is_array($out) || empty($out)) $out=array(); - break; - case 'nohtml': - $out=dol_string_nohtmltag($out); - break; - case 'alphanohtml': // Recommended for search params - $out=trim($out); - // '"' is dangerous because param in url can close the href= or src= and add javascript functions. - // '../' is dangerous because it allows dir transversals - if (preg_match('/"/',$out)) $out=''; - else if (preg_match('/\.\.\//',$out)) $out=''; - $out=dol_string_nohtmltag($out); - break; - case 'custom': - if (empty($filter)) return 'BadFourthParameterForGETPOST'; - $out=filter_var($out, $filter, $options); - break; - } + // Check is done after replacement + switch ($check) + { + case 'none': + break; + case 'int': // Check param is a numeric value (integer but also float or hexadecimal) + if (! is_numeric($out)) { $out=''; } + break; + case 'intcomma': + if (preg_match('/[^0-9,]+/i',$out)) $out=''; + break; + case 'alpha': + $out=trim($out); + // '"' is dangerous because param in url can close the href= or src= and add javascript functions. + // '../' is dangerous because it allows dir transversals + if (preg_match('/"/',$out)) $out=''; + else if (preg_match('/\.\.\//',$out)) $out=''; + break; + case 'san_alpha': + $out=filter_var($out,FILTER_SANITIZE_STRING); + break; + case 'aZ': + $out=trim($out); + if (preg_match('/[^a-z]+/i',$out)) $out=''; + break; + case 'aZ09': + $out=trim($out); + if (preg_match('/[^a-z0-9_\-\.]+/i',$out)) $out=''; + break; + case 'array': + if (! is_array($out) || empty($out)) $out=array(); + break; + case 'nohtml': + $out=dol_string_nohtmltag($out); + break; + case 'alphanohtml': // Recommended for search params + $out=trim($out); + // '"' is dangerous because param in url can close the href= or src= and add javascript functions. + // '../' is dangerous because it allows dir transversals + if (preg_match('/"/',$out)) $out=''; + else if (preg_match('/\.\.\//',$out)) $out=''; + $out=dol_string_nohtmltag($out); + break; + case 'custom': + if (empty($filter)) return 'BadFourthParameterForGETPOST'; + $out=filter_var($out, $filter, $options); + break; + } - // Code for search criteria persistence. + // Code for search criteria persistence. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year' if (empty($method) || $method == 3 || $method == 4) { - //if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield", 'smonth', 'syear', 'month', 'year'))) - if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield'))) - { - //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); + //if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield", 'smonth', 'syear', 'month', 'year'))) + if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield'))) + { + //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]); - // We save search key only if: - // - not empty, or - // - if value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). + // We save search key only if: + // - not empty, or + // - if value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not). - //if (! empty($out) || ! empty($user->default_values[$relativepathstring]['filters'][$paramname])) - if (! empty($out)) - { - $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out; - } - } + //if (! empty($out) || ! empty($user->default_values[$relativepathstring]['filters'][$paramname])) + if (! empty($out)) + { + $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out; + } + } } return $out; @@ -549,14 +577,14 @@ function GETPOST($paramname, $check='alpha', $method=0, $filter=NULL, $options=N */ function dol_getprefix($mode='') { - global $conf; + global $conf; - // If MAIL_PREFIX_FOR_EMAIL_ID is set and prefix is for email - if ($mode == 'email' && ! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) - { - if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; - else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"]; - } + // If MAIL_PREFIX_FOR_EMAIL_ID is set and prefix is for email + if ($mode == 'email' && ! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) + { + if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID; + else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"]; + } if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) { @@ -642,18 +670,18 @@ function dol_buildpath($path, $type=0, $returnemptyifnotfound=0) { if ($key == 'main') { - if ($type == 3) - { - global $dolibarr_main_url_root; + if ($type == 3) + { + global $dolibarr_main_url_root; - // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + // Define $urlwithroot + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax - } - continue; + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax + } + continue; } preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?' if (! empty($regs[1])) @@ -667,18 +695,18 @@ function dol_buildpath($path, $type=0, $returnemptyifnotfound=0) } if ($type == 2) { - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path; } if ($type == 3) { - global $dolibarr_main_url_root; + global $dolibarr_main_url_root; - // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + // Define $urlwithroot + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax } break; } @@ -745,7 +773,7 @@ function dol_size($size,$type='') */ function dol_sanitizeFileName($str,$newstr='_',$unaccent=1) { - $filesystem_forbidden_chars = array('<','>',':','/','\\','?','*','|','"','°'); + $filesystem_forbidden_chars = array('<','>','/','\\','?','*','|','"','°'); return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); } @@ -761,8 +789,8 @@ function dol_sanitizeFileName($str,$newstr='_',$unaccent=1) */ function dol_sanitizePathName($str,$newstr='_',$unaccent=1) { - $filesystem_forbidden_chars = array('<','>','?','*','|','"','°'); - return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); + $filesystem_forbidden_chars = array('<','>','?','*','|','"','°'); + return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); } /** @@ -882,16 +910,15 @@ function dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0) * @param int $keepb 1=Preserve b tags (otherwise, remove them) * @param int $keepn 1=Preserve \r\n strings (otherwise, remove them) * @return string Escaped string - * * @see dol_string_nohtmltag */ function dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0) { // escape quotes and backslashes, newlines, etc. - $tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8'); + $tmp=html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html form content if (! $keepb) $tmp=strtr($tmp, array(""=>'',''=>'')); if (! $keepn) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n')); - return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8'); + return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html form content } @@ -947,54 +974,54 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename=' if (! empty($message)) { - // Test log level - $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG); - if (!in_array($level, $logLevels, true)) - { - throw new Exception('Incorrect log level'); - } - if ($level > $conf->global->SYSLOG_LEVEL) return; + // Test log level + $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG); + if (!in_array($level, $logLevels, true)) + { + throw new Exception('Incorrect log level'); + } + if ($level > $conf->global->SYSLOG_LEVEL) return; - // If adding log inside HTML page is required - if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility - { - $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message; - } + // If adding log inside HTML page is required + if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility + { + $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message; + } - //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output - // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments - if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"])) - { - print "\n\n\n"; - } + //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output + // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments + if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"])) + { + print "\n\n\n"; + } - $data = array( - 'message' => $message, - 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false), - 'level' => $level, - 'user' => ((is_object($user) && $user->id) ? $user->login : false), - 'ip' => false - ); + $data = array( + 'message' => $message, + 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false), + 'level' => $level, + 'user' => ((is_object($user) && $user->id) ? $user->login : false), + 'ip' => false + ); - // This is when server run behind a reverse proxy - if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']); - // This is when server run normally on a server - else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR']; - // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache) - else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR']; - // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it). - else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); - // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it). - else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME']; - // Loop on each log handler and send output - foreach ($conf->loghandlers as $loghandlerinstance) - { - if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue; - $loghandlerinstance->export($data,$suffixinfilename); - } - unset($data); + // This is when server run behind a reverse proxy + if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']); + // This is when server run normally on a server + else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR']; + // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache) + else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR']; + // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it). + else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']); + // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it). + else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME']; + // Loop on each log handler and send output + foreach ($conf->loghandlers as $loghandlerinstance) + { + if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue; + $loghandlerinstance->export($data,$suffixinfilename); + } + unset($data); } if (! empty($ident)) @@ -1072,7 +1099,7 @@ function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $pi $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD); $displaytab=0; $nbintab=0; - $popuptab=0; $outmore=''; + $popuptab=0; $outmore=''; for ($i = 0 ; $i <= $maxkey ; $i++) { if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2])) @@ -1123,13 +1150,13 @@ function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $pi } else { - // The popup with the other tabs + // The popup with the other tabs if (! $popuptab) { - $popuptab=1; - $outmore.='
    '; + $popuptab=1; + $outmore.='
    '; } - $outmore.='
    '; + $outmore.='
    '; if (isset($links[$i][2]) && $links[$i][2] == 'image') { if (!empty($links[$i][0])) @@ -1215,7 +1242,7 @@ function dol_get_fiche_end($notab=0) * @param int $nodbprefix Do not include DB prefix to forge table name * @param string $morehtmlleft More html code to show before ref * @param string $morehtmlstatus More html code to show under navigation arrows - * @param int $onlybanner Put this to 1, if the card will contains only a banner (add css 'arearefnobottom' on div) + * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div) * @param string $morehtmlright More html code to show before navigation arrows * @return void */ @@ -1239,26 +1266,26 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r if (class_exists("Imagick")) { - if ($object->element == 'propal') $modulepart='propal'; + if ($object->element == 'propal') $modulepart='propal'; if ($object->element == 'commande') $modulepart='commande'; if ($object->element == 'facture') $modulepart='facture'; if ($object->element == 'fichinter') $modulepart='ficheinter'; if ($object->element == 'contrat') $modulepart='contract'; - if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal'; + if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal'; if ($object->element == 'order_supplier') $modulepart='supplier_order'; - if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice'; + if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice'; if ($object->element == 'expensereport') $modulepart='expensereport'; } if ($object->element == 'product') { - $width=80; $cssclass='photoref'; - $showimage=$object->is_photo_available($conf->product->multidir_output[$object->entity]); - $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5); + $width=80; $cssclass='photoref'; + $showimage=$object->is_photo_available($conf->product->multidir_output[$object->entity]); + $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5); if ($conf->browser->phone) $maxvisiblephotos=1; if ($showimage) $morehtmlleft.='
    '.$object->show_photos($conf->product->multidir_output[$object->entity],'small',$maxvisiblephotos,0,0,0,$width,0).'
    '; - else - { + else + { if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) { $nophoto=''; $morehtmlleft.='
    '; @@ -1267,153 +1294,153 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r $nophoto='/public/theme/common/nophoto.png'; $morehtmlleft.='
    No photo
    '; //} - } + } } else { if ($showimage) - { - if ($modulepart != 'unknown') - { - $phototoshow=''; - // Check if a preview file is available - if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) - { - $objectref = dol_sanitizeFileName($object->ref); - $dir_output = $conf->$modulepart->dir_output . "/"; - if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) - { - $subdir = get_exdir($object->id, 2, 0, 0, $object, $modulepart).$objectref; - } - else - { - $subdir = get_exdir($object->id, 0, 0, 0, $object, $modulepart).$objectref; - } - $filepath = $dir_output . $subdir . "/"; - $file = $filepath . $objectref . ".pdf"; - $relativepath = $subdir.'/'.$objectref.'.pdf'; + { + if ($modulepart != 'unknown') + { + $phototoshow=''; + // Check if a preview file is available + if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) + { + $objectref = dol_sanitizeFileName($object->ref); + $dir_output = $conf->$modulepart->dir_output . "/"; + if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) + { + $subdir = get_exdir($object->id, 2, 0, 0, $object, $modulepart).$objectref; + } + else + { + $subdir = get_exdir($object->id, 0, 0, 0, $object, $modulepart).$objectref; + } + $filepath = $dir_output . $subdir . "/"; + $file = $filepath . $objectref . ".pdf"; + $relativepath = $subdir.'/'.$objectref.'.pdf'; - // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png") - $fileimage = $file.'_preview.png'; // If PDF has 1 page - $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page - $relativepathimage = $relativepath.'_preview.png'; + // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png") + $fileimage = $file.'_preview.png'; // If PDF has 1 page + $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page + $relativepathimage = $relativepath.'_preview.png'; - // Si fichier PDF existe - if (file_exists($file)) - { - $encfile = urlencode($file); - // Conversion du PDF en image png si fichier png non existant - if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file))) - && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file))) - ) - { - if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here. - { - $ret = dol_convert_file($file, 'png', $fileimage); - if ($ret < 0) $error++; - } - } + // Si fichier PDF existe + if (file_exists($file)) + { + $encfile = urlencode($file); + // Conversion du PDF en image png si fichier png non existant + if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file))) + && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file))) + ) + { + if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here. + { + $ret = dol_convert_file($file, 'png', $fileimage); + if ($ret < 0) $error++; + } + } - $heightforphotref=70; - if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60; - // Si fichier png PDF d'1 page trouve - if (file_exists($fileimage)) - { - $phototoshow = '
    '; - $phototoshow.= ''; - $phototoshow.= '
    '; - } - // Si fichier png PDF de plus d'1 page trouve - elseif (file_exists($fileimagebis)) - { - $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png"; - $phototoshow = '
    '; - $phototoshow.= '

    '; - $phototoshow.= '

    '; - } - } - } - else if (! $phototoshow) - { - $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); - } + $heightforphotref=70; + if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60; + // Si fichier png PDF d'1 page trouve + if (file_exists($fileimage)) + { + $phototoshow = '
    '; + $phototoshow.= ''; + $phototoshow.= '
    '; + } + // Si fichier png PDF de plus d'1 page trouve + elseif (file_exists($fileimagebis)) + { + $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png"; + $phototoshow = '
    '; + $phototoshow.= '

    '; + $phototoshow.= '

    '; + } + } + } + else if (! $phototoshow) + { + $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); + } - if ($phototoshow) - { - $morehtmlleft.='
    '; - $morehtmlleft.=$phototoshow; - $morehtmlleft.='
    '; - } - } + if ($phototoshow) + { + $morehtmlleft.='
    '; + $morehtmlleft.=$phototoshow; + $morehtmlleft.='
    '; + } + } - if (! $phototoshow) // Show No photo link (picto of pbject) - { - $morehtmlleft.='
    '; - if ($object->element == 'action') - { - $width=80; - $cssclass='photorefcenter'; - $nophoto=img_picto('', 'title_agenda', '', false, 1); - } - else - { - $width=14; $cssclass='photorefcenter'; - $picto = $object->picto; - if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub - $nophoto=img_picto('', 'object_'.$picto, '', false, 1); - } - $morehtmlleft.=''; - $morehtmlleft.='
    No photo
    '; + if (! $phototoshow) // Show No photo link (picto of pbject) + { + $morehtmlleft.='
    '; + if ($object->element == 'action') + { + $width=80; + $cssclass='photorefcenter'; + $nophoto=img_picto('', 'title_agenda', '', false, 1); + } + else + { + $width=14; $cssclass='photorefcenter'; + $picto = $object->picto; + if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub + $nophoto=img_picto('', 'object_'.$picto, '', false, 1); + } + $morehtmlleft.=''; + $morehtmlleft.='
    No photo
    '; - $morehtmlleft.='
    '; - } - } + $morehtmlleft.='
    '; + } + } } if ($showbarcode) $morehtmlleft.='
    '.$form->showbarcode($object).'
    '; if ($object->element == 'societe') { - if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) - { - $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); - } + if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) + { + $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased'); + } } elseif ($object->element == 'product') { - //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') '; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); - } else { - $morehtmlstatus.=''.$object->getLibStatut(5,0).''; - } - $morehtmlstatus.='   '; - //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') '; - if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { - $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); - } else { - $morehtmlstatus.=''.$object->getLibStatut(5,1).''; - } + //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') '; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); + } else { + $morehtmlstatus.=''.$object->getLibStatut(5,0).''; + } + $morehtmlstatus.='   '; + //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') '; + if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { + $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); + } else { + $morehtmlstatus.=''.$object->getLibStatut(5,1).''; + } } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) { - $tmptxt=$object->getLibStatut(6, $object->totalpaye); - if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye); + $tmptxt=$object->getLibStatut(6, $object->totalpaye); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye); $morehtmlstatus.=$tmptxt; } elseif ($object->element == 'contrat' || $object->element == 'contract') { - if ($object->statut==0) $morehtmlstatus.=$object->getLibStatut(2); - else $morehtmlstatus.=$object->getLibStatut(4); + if ($object->statut==0) $morehtmlstatus.=$object->getLibStatut(2); + else $morehtmlstatus.=$object->getLibStatut(4); } elseif ($object->element == 'facturerec') { - if ($object->frequency==0) $morehtmlstatus.=$object->getLibStatut(2); - else $morehtmlstatus.=$object->getLibStatut(4); + if ($object->frequency==0) $morehtmlstatus.=$object->getLibStatut(2); + else $morehtmlstatus.=$object->getLibStatut(4); } else { // Generic case - $tmptxt=$object->getLibStatut(6); - if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5); + $tmptxt=$object->getLibStatut(6); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5); $morehtmlstatus.=$tmptxt; } if (! empty($object->name_alias)) $morehtmlref.='
    '.$object->name_alias.'
    '; // For thirdparty @@ -1426,9 +1453,9 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r if ($object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories') { - $morehtmlref.='
    '; - $morehtmlref.=$object->getBannerAddress('refaddress',$object); - $morehtmlref.='
    '; + $morehtmlref.='
    '; + $morehtmlref.=$object->getBannerAddress('refaddress',$object); + $morehtmlref.='
    '; } if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product'))) { @@ -1572,7 +1599,7 @@ function dol_strftime($fmt, $ts=false, $is_gmt=false) * @param string $tzoutput true or 'gmt' => string is for Greenwich location * false or 'tzserver' => output string is for local PHP server TZ usage * 'tzuser' => output string is for user TZ (current browser TZ with current dst) - * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) + * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet) * @param Translate $outputlangs Object lang that contains language for text translation. * @param boolean $encodetooutput false=no convert into output pagecode * @return string Formated date or '' if time is null @@ -1598,7 +1625,7 @@ function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$e $offsettz=0; $offsetdst=0; } - elseif ($tzoutput == 'tzuser') + elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') { $to_gmt=true; $offsettzstring=(empty($_SESSION['dol_tz_string'])?'UTC':$_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion' @@ -1671,14 +1698,14 @@ function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$e $ssec = (! empty($reg[6]) ? $reg[6] : ''); $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true); - $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt); + $ret=adodb_strftime($format, $time+$offsettz+$offsetdst, $to_gmt); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. } else { // Date is a timestamps if ($time < 100000000000) // Protection against bad date values { - $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. + $ret=adodb_strftime($format, $time+$offsettz+$offsetdst, $to_gmt); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. } else $ret='Bad value '.$time.' for date'; } @@ -1686,8 +1713,8 @@ function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$e if (preg_match('/__b__/i',$format)) { // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs. - $month=adodb_strftime('%m',$time+$offsettz+$offsetdst); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. - $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'. + $month=adodb_strftime('%m', $time+$offsettz+$offsetdst); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. + $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'. if ($encodetooutput) { $monthtext=$outputlangs->transnoentities('Month'.$month); @@ -1706,7 +1733,7 @@ function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$e } if (preg_match('/__a__/i',$format)) { - $w=adodb_strftime('%w',$time+$offsettz+$offsetdst); // TODO Remove this + $w=adodb_strftime('%w', $time+$offsettz+$offsetdst); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w); $ret=str_replace('__A__',$dayweek,$ret); $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret); @@ -1871,7 +1898,7 @@ function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1) */ function dol_now($mode='gmt') { - $ret=''; + $ret=''; // Note that gmmktime and mktime return same value (GMT) when used without parameters //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead if ($mode == 'gmt') $ret=time(); // Time for now at greenwich. @@ -2114,9 +2141,9 @@ function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$sep if (strtoupper($countrycode) == "CA") { - if (dol_strlen($phone) == 10) { - $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4); - } + if (dol_strlen($phone) == 10) { + $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4); + } } if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set) @@ -2167,9 +2194,21 @@ function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$sep $titlealt=($withpicto=='fax'?$langs->trans("Fax"):$langs->trans("Phone")); } $rep=''; + $picto = ''; + if($withpicto){ + if($withpicto=='fax'){ + $picto = 'phoning_fax'; + }elseif($withpicto=='phone'){ + $picto = 'phoning'; + }elseif($withpicto=='mobile'){ + $picto = 'phoning_mobile'; + }else{ + $picto = ''; + } + } if ($adddivfloat) $rep.='
    '; else $rep.=''; - $rep.=($withpicto?img_picto($titlealt, 'object_'.($withpicto=='fax'?'phoning_fax':'phoning').'.png').' ':'').$newphone; + $rep.=($withpicto?img_picto($titlealt, 'object_'.$picto.'.png').' ':'').$newphone; if ($adddivfloat) $rep.='
    '; else $rep.=''; return $rep; @@ -2260,37 +2299,37 @@ function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl if ($address) { - if ($hookmanager) { - $parameters = array('element' => $mode, 'id' => $id); - $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address); - $out.=$hookmanager->resPrint; - } - if (empty($reshook)) - { - if (empty($charfornl)) $out.=nl2br($address); - else $out.=preg_replace('/[\r\n]+/', $charfornl, $address); + if ($hookmanager) { + $parameters = array('element' => $mode, 'id' => $id); + $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address); + $out.=$hookmanager->resPrint; + } + if (empty($reshook)) + { + if (empty($charfornl)) $out.=nl2br($address); + else $out.=preg_replace('/[\r\n]+/', $charfornl, $address); - $showgmap=$showomap=0; + $showgmap=$showomap=0; - // TODO Add a hook here - if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1; - if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1; - if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1; - if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1; - if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1; - if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1; + // TODO Add a hook here + if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1; + if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1; + if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1; + if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1; + if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1; + if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1; - if ($showgmap) - { - $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1); - $out.=' '; - } - if ($showomap) - { - $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1); - $out.=' '; - } - } + if ($showgmap) + { + $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1); + $out.=' '; + } + if ($showomap) + { + $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1); + $out.=' '; + } + } } if ($noprint) return $out; else print $out; @@ -2393,9 +2432,9 @@ function dol_print_graph($htmlid,$width,$height,$data,$showlegend=0,$type='pie', if ($shownographyet) { - print '
    '; - print '
    '.$langs->trans("NotEnoughDataYet").'
    '; - return; + print '
    '; + print '
    '.$langs->trans("NotEnoughDataYet").'
    '; + return; } if (empty($conf->use_javascript_ajax)) return; @@ -2889,9 +2928,9 @@ function img_delete($titlealt = 'default', $other = 'class="pictodelete"') */ function img_printer($titlealt = "default", $other='') { - global $conf,$langs; - if ($titlealt=="default") $titlealt=$langs->trans("Print"); - return img_picto($titlealt,'printer.png',$other); + global $conf,$langs; + if ($titlealt=="default") $titlealt=$langs->trans("Print"); + return img_picto($titlealt,'printer.png',$other); } /** @@ -2982,7 +3021,7 @@ function img_error($titlealt = 'default') * * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"') - * @return string Return img tag + * @return string Return img tag */ function img_next($titlealt = 'default', $moreatt='') { @@ -3281,8 +3320,8 @@ function dol_print_error($db='',$error='',$errors=null) } else // Mode CLI { - // No dol_escape_htmltag for output, we are in CLI mode - $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; + // No dol_escape_htmltag for output, we are in CLI mode + $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n"; $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n"; $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n"; $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n"; @@ -3400,7 +3439,7 @@ function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $m $sortorder=strtoupper($sortorder); $out=''; - $sortimg=''; + $sortimg=''; $tag='th'; if ($thead==2) $tag='div'; @@ -3425,13 +3464,13 @@ function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $m if ($field1 != $sortfield1) // We are on another field { - if (preg_match('/^DESC/', $sortorder)) $out.= ''; - else $out.= ''; + if (preg_match('/^DESC/', $sortorder)) $out.= ''; + else $out.= ''; } else // We are of first sorting criteria { - if (preg_match('/^ASC/', $sortorder)) $out.= ''; - else $out.= ''; + if (preg_match('/^ASC/', $sortorder)) $out.= ''; + else $out.= ''; } } @@ -3523,10 +3562,11 @@ function print_fiche_titre($title, $mesg='', $picto='title_generic.png', $pictoi * @param int $pictoisfullpath 1=Icon name is a full absolute url of image * @param int $id To force an id on html objects * @param string $morecssontable More css on table + * @param string $morehtmlcenter Added message to show on center * @return string * @see print_barre_liste */ -function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id=0, $morecssontable='') +function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id=0, $morecssontable='', $morehtmlcenter='') { global $conf; @@ -3541,6 +3581,10 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $return.= '
    '; + if (dol_strlen($morehtmlcenter)) + { + $return.= ''; + } if (dol_strlen($morehtmlright)) { $return.= ''; @@ -3568,15 +3612,16 @@ function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', * @param string $morecss More css to the table * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit). * @param int $hideselectlimit Force to hide select limit + * @param int $hidenavigation Force to hide all navigation tools * @return void */ -function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines='', $picto='title_generic.png', $pictoisfullpath=0, $morehtml='', $morecss='', $limit=-1, $hideselectlimit=0) +function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines='', $picto='title_generic.png', $pictoisfullpath=0, $morehtml='', $morecss='', $limit=-1, $hideselectlimit=0, $hidenavigation=0) { global $conf,$langs; $savlimit = $limit; - $savtotalnboflines = $totalnboflines; - $totalnboflines=abs($totalnboflines); + $savtotalnboflines = $totalnboflines; + $totalnboflines=abs($totalnboflines); if ($picto == 'setup') $picto='title_setup.png'; if (($conf->browser->name == 'ie') && $picto=='title_generic.png') $picto='title.gif'; @@ -3689,40 +3734,40 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee print ''; $plannedworkloadoutputformat='allhourmin'; @@ -519,9 +531,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if ($level >= 0) // Call sublevels { - $level++; - if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick); - $level--; + $level++; + if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick); + $level--; } $total_projectlinesa_spent += $lines[$i]->duration; @@ -593,13 +605,15 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // Create a smaller array with sublevels only to be used later. This increase dramatically performances. if ($parent == 0) // Always and only if at first level { - for ($i = 0 ; $i < $numlines ; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i]; - } + for ($i = 0 ; $i < $numlines ; $i++) + { + if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i]; + } } - //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); + $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_BREAK_ON_PROJECT)?0:-1); // 0 to start break , -1 no break + + //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); for ($i = 0 ; $i < $numlines ; $i++) { if ($parent == 0) $level = 0; @@ -609,26 +623,26 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // If we want all or we have a role on task, we show it if (empty($mine) || ! empty($tasksrole[$lines[$i]->id])) { - //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); + //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { - $lastprojectid=$lines[$i]->fk_project; - if ($preselectedday) - { - $projectstatic->id = $lines[$i]->fk_project; - } - } + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) + { + $lastprojectid=$lines[$i]->fk_project; + if ($preselectedday) + { + $projectstatic->id = $lines[$i]->fk_project; + } + } - if (empty($workloadforid[$projectstatic->id])) - { - if ($preselectedday) - { - $projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - $workloadforid[$projectstatic->id]=1; - } - } + if (empty($workloadforid[$projectstatic->id])) + { + if ($preselectedday) + { + $projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week + $workloadforid[$projectstatic->id]=1; + } + } $projectstatic->id=$lines[$i]->fk_project; $projectstatic->ref=$lines[$i]->projectref; @@ -636,6 +650,31 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $projectstatic->public=$lines[$i]->public; $taskstatic->id=$lines[$i]->id; + $taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id); + $taskstatic->id=$lines[$i]->id; + $taskstatic->label=$lines[$i]->label; + $taskstatic->date_start=$lines[$i]->date_start; + $taskstatic->date_end=$lines[$i]->date_end; + + $thirdpartystatic->id=$lines[$i]->socid; + $thirdpartystatic->name=$lines[$i]->thirdparty_name; + $thirdpartystatic->email=$lines[$i]->thirdparty_email; + + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) + { + print ''."\n"; + print ''; + print ''; + } + + if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; print ''."\n"; @@ -648,33 +687,23 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // Project print ""; + // Thirdparty + print ''; + // Ref print ''; - - if (! empty($conf->global->PROJECT_LINES_PERDAY_SHOW_THIRDPARTY)) - { - // Thirdparty - print ''; - } - - // Label task - print "'; - print ''; @@ -788,8 +818,8 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $level++; if ($lines[$i]->id > 0) { - if ($parent == 0) projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable); - else projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable); + if ($parent == 0) projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable); + else projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable); } $level--; } @@ -833,13 +863,15 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Create a smaller array with sublevels only to be used later. This increase dramatically performances. if ($parent == 0) // Always and only if at first level { - for ($i = 0 ; $i < $numlines ; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i]; - } + for ($i = 0 ; $i < $numlines ; $i++) + { + if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i]; + } } - //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); + //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); + + $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_BREAK_ON_PROJECT)?0:-1); // 0 = start break, -1 = never break for ($i = 0 ; $i < $numlines ; $i++) { @@ -850,20 +882,20 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // If we want all or we have a role on task, we show it if (empty($mine) || ! empty($tasksrole[$lines[$i]->id])) { - //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); + //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); - // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { - $lastprojectid=$lines[$i]->fk_project; - $projectstatic->id = $lines[$i]->fk_project; - } + // Break on a new project + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) + { + $lastprojectid=$lines[$i]->fk_project; + $projectstatic->id = $lines[$i]->fk_project; + } - if (empty($workloadforid[$projectstatic->id])) - { - $projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - $workloadforid[$projectstatic->id]=1; - } + if (empty($workloadforid[$projectstatic->id])) + { + $projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week + $workloadforid[$projectstatic->id]=1; + } $projectstatic->id=$lines[$i]->fk_project; $projectstatic->ref=$lines[$i]->projectref; @@ -871,6 +903,33 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $projectstatic->public=$lines[$i]->public; $projectstatic->thirdparty_name=$lines[$i]->thirdparty_name; + $taskstatic->id=$lines[$i]->id; + $taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id); + $taskstatic->id=$lines[$i]->id; + $taskstatic->label=$lines[$i]->label; + $taskstatic->date_start=$lines[$i]->date_start; + $taskstatic->date_end=$lines[$i]->date_end; + + $thirdpartystatic->id=$lines[$i]->thirdparty_id; + $thirdpartystatic->name=$lines[$i]->thirdparty_name; + $thirdpartystatic->email=$lines[$i]->thirdparty_email; + + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) + { + print ''."\n"; + print ''; + print ''; + } + + if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + print ''."\n"; // User @@ -882,35 +941,24 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Project print '"; - if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) - { - // Thirdparty - print ''; - } + // Thirdparty + print ''; // Ref print ''; - - // Label task - print "'; - print $tableCell; - } + $tableCell =''; + print $tableCell; + } - // Warning + // Warning print ''; - print "\n"; + print "\n"; } // Call to show task with a lower level (task under the current task) @@ -1017,8 +1065,8 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $level++; if ($lines[$i]->id > 0) { - if ($parent == 0) projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable); - else projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable); + if ($parent == 0) projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable); + else projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable); } $level--; } @@ -1088,7 +1136,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $projectstatic=new Project($db); - $thirdpartystatic=new Societe($db); + $thirdpartystatic=new Societe($db); $sortfield=''; $sortorder=''; @@ -1149,12 +1197,12 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= $resql = $db->query($sql1); if ($resql) { - $i=0; + $i=0; $num = $db->num_rows($resql); while ($i < $num) { $objp = $db->fetch_object($resql); - $arrayidofprojects[$objp->projectid]=$objp->projectid; + $arrayidofprojects[$objp->projectid]=$objp->projectid; $i++; } } @@ -1182,22 +1230,22 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= $num = $db->num_rows($resql); $i = 0; - print ''; - print_liste_field_titre($title.' '.$num.'',$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { - print_liste_field_titre("OpportunityAmount","","","","",'align="right"',$sortfield,$sortorder); - print_liste_field_titre("OpportunityStatus","","","","",'align="right"',$sortfield,$sortorder); - } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { - print_liste_field_titre("Tasks","","","","",'align="right"',$sortfield,$sortorder); - if (! in_array('plannedworkload', $hiddenfields)) print_liste_field_titre("PlannedWorkload","","","","",'align="right"',$sortfield,$sortorder); - if (! in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared","","","","",'align="right"',$sortfield,$sortorder); - } - print_liste_field_titre("Status","","","","",'align="right"',$sortfield,$sortorder); - print "\n"; + print ''; + print_liste_field_titre($title.' '.$num.'',$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); + print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder); + if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + { + print_liste_field_titre("OpportunityAmount","","","","",'align="right"',$sortfield,$sortorder); + print_liste_field_titre("OpportunityStatus","","","","",'align="right"',$sortfield,$sortorder); + } + if (empty($conf->global->PROJECT_HIDE_TASKS)) + { + print_liste_field_titre("Tasks","","","","",'align="right"',$sortfield,$sortorder); + if (! in_array('plannedworkload', $hiddenfields)) print_liste_field_titre("PlannedWorkload","","","","",'align="right"',$sortfield,$sortorder); + if (! in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared","","","","",'align="right"',$sortfield,$sortorder); + } + print_liste_field_titre("Status","","","","",'align="right"',$sortfield,$sortorder); + print "\n"; while ($i < $num) { @@ -1211,11 +1259,11 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= $userAccess = $projectstatic->restrictedProjectArea($user); if ($userAccess >= 0) { - $projectstatic->ref=$objp->ref; - $projectstatic->statut = $objp->status; - $projectstatic->title = $objp->title; - $projectstatic->datee = $db->jdate($objp->datee); - $projectstatic->dateo = $db->jdate($objp->dateo); + $projectstatic->ref=$objp->ref; + $projectstatic->statut = $objp->status; + $projectstatic->title = $objp->title; + $projectstatic->datee = $db->jdate($objp->datee); + $projectstatic->dateo = $db->jdate($objp->dateo); print ''; @@ -1226,41 +1274,41 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= print ''; if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { print ''; print ''; } if (empty($conf->global->PROJECT_HIDE_TASKS)) { - print ''; + print ''; - $plannedworkload=$objp->planned_workload; - $total_plannedworkload+=$plannedworkload; - if (! in_array('plannedworkload', $hiddenfields)) - { - print ''; - } - if (! in_array('declaredprogress', $hiddenfields)) - { - $declaredprogressworkload=$objp->declared_progess_workload; - $total_declaredprogressworkload+=$declaredprogressworkload; - print ''; - } + $plannedworkload=$objp->planned_workload; + $total_plannedworkload+=$plannedworkload; + if (! in_array('plannedworkload', $hiddenfields)) + { + print ''; + } + if (! in_array('declaredprogress', $hiddenfields)) + { + $declaredprogressworkload=$objp->declared_progess_workload; + $total_declaredprogressworkload+=$declaredprogressworkload; + print ''; + } } print ''; @@ -1283,12 +1331,12 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= } if (empty($conf->global->PROJECT_HIDE_TASKS)) { - print ''; - if (! in_array('plannedworkload', $hiddenfields)) print ''; - if (! in_array('declaredprogress', $hiddenfields)) print ''; + print ''; + if (! in_array('plannedworkload', $hiddenfields)) print ''; + if (! in_array('declaredprogress', $hiddenfields)) print ''; } print ''; - print ''; + print ''; $db->free($resql); } diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php index 581c324674a..11232f37ea7 100644 --- a/htdocs/core/lib/security.lib.php +++ b/htdocs/core/lib/security.lib.php @@ -87,7 +87,7 @@ function dol_hash($chain,$type=0) if ($type == 1) return sha1($chain); else if ($type == 2) return sha1(md5($chain)); else if ($type == 3) return md5($chain); - else if ($type == 4) return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 + else if ($type == 4) return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base) else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain); else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain)); @@ -252,7 +252,8 @@ function restrictedArea($user, $features, $objectid=0, $tableandshare='', $featu { //print '
    feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write; if (empty($user->rights->$feature->creer) - && empty($user->rights->$feature->write)) { $createok=0; $nbko++; } + && empty($user->rights->$feature->write) + && empty($user->rights->$feature->create)) { $createok=0; $nbko++; } } } @@ -307,6 +308,10 @@ function restrictedArea($user, $features, $objectid=0, $tableandshare='', $featu { if (! $user->rights->ftp->write) $deleteok=0; } + else if ($feature == 'salaries') + { + if (! $user->rights->salaries->delete) $deleteok=0; + } else if (! empty($feature2)) // This should be used for future changes { foreach($feature2 as $subfeature) diff --git a/htdocs/core/lib/usergroups.lib.php b/htdocs/core/lib/usergroups.lib.php index f39e6ecd628..8f73678a532 100644 --- a/htdocs/core/lib/usergroups.lib.php +++ b/htdocs/core/lib/usergroups.lib.php @@ -45,24 +45,25 @@ function user_prepare_head($object) $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/user/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("UserCard"); - $head[$h][2] = 'user'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("UserCard"); + $head[$h][2] = 'user'; + $h++; - if (! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_SYNCHRO_ACTIVE)) + if ((! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_SYNCHRO_ACTIVE)) + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || ! empty($user->admin))) { $langs->load("ldap"); - $head[$h][0] = DOL_URL_ROOT.'/user/ldap.php?id='.$object->id; - $head[$h][1] = $langs->trans("LDAPCard"); - $head[$h][2] = 'ldap'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/ldap.php?id='.$object->id; + $head[$h][1] = $langs->trans("LDAPCard"); + $head[$h][2] = 'ldap'; + $h++; } - $head[$h][0] = DOL_URL_ROOT.'/user/param_ihm.php?id='.$object->id; - $head[$h][1] = $langs->trans("UserGUISetup"); - $head[$h][2] = 'guisetup'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/param_ihm.php?id='.$object->id; + $head[$h][1] = $langs->trans("UserGUISetup"); + $head[$h][2] = 'guisetup'; + $h++; if ($canreadperms) { @@ -72,116 +73,116 @@ function user_prepare_head($object) $h++; } - if (! empty($conf->agenda->enabled)) - { - if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5; - $MAXAGENDA=$conf->global->AGENDA_EXT_NB; + if (! empty($conf->agenda->enabled)) + { + if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5; + $MAXAGENDA=$conf->global->AGENDA_EXT_NB; - $i=1; - $nbagenda = 0; - while ($i <= $MAXAGENDA) - { - $key=$i; - $name='AGENDA_EXT_NAME_'.$object->id.'_'.$key; - $src='AGENDA_EXT_SRC_'.$object->id.'_'.$key; - $offsettz='AGENDA_EXT_OFFSETTZ_'.$object->id.'_'.$key; - $color='AGENDA_EXT_COLOR_'.$object->id.'_'.$key; - $i++; + $i=1; + $nbagenda = 0; + while ($i <= $MAXAGENDA) + { + $key=$i; + $name='AGENDA_EXT_NAME_'.$object->id.'_'.$key; + $src='AGENDA_EXT_SRC_'.$object->id.'_'.$key; + $offsettz='AGENDA_EXT_OFFSETTZ_'.$object->id.'_'.$key; + $color='AGENDA_EXT_COLOR_'.$object->id.'_'.$key; + $i++; - if (! empty($object->conf->$name)) $nbagenda++; - } + if (! empty($object->conf->$name)) $nbagenda++; + } - $head[$h][0] = DOL_URL_ROOT.'/user/agenda_extsites.php?id='.$object->id; - $head[$h][1] = $langs->trans("ExtSites").($nbagenda ? ' '.$nbagenda.'' : ''); - $head[$h][2] = 'extsites'; - $h++; - } - - if (! empty($conf->clicktodial->enabled)) - { - $head[$h][0] = DOL_URL_ROOT.'/user/clicktodial.php?id='.$object->id; - $head[$h][1] = $langs->trans("ClickToDial"); - $head[$h][2] = 'clicktodial'; - $h++; - } - - // Notifications - if ($user->societe_id == 0 && ! empty($conf->notification->enabled)) - { - $nbNote = 0; - $sql = "SELECT COUNT(n.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n"; - $sql.= " WHERE fk_user = ".$object->id; - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $nbNote=$obj->nb; - $i++; - } - } - else { - dol_print_error($db); - } - - $head[$h][0] = DOL_URL_ROOT.'/user/notify/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("Notifications"); - if ($nbNote > 0) $head[$h][1].= ' '.$nbNote.''; - $head[$h][2] = 'notify'; - $h++; - } - - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf,$langs,$object,$head,$h,'user'); - - if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) - || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) - { - // Bank - $head[$h][0] = DOL_URL_ROOT.'/user/bank.php?id='.$object->id; - $head[$h][1] = $langs->trans("HRAndBank"); - $head[$h][2] = 'bank'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/agenda_extsites.php?id='.$object->id; + $head[$h][1] = $langs->trans("ExtSites").($nbagenda ? ' '.$nbagenda.'' : ''); + $head[$h][2] = 'extsites'; + $h++; } - // Such info on users is visible only by internal user - if (empty($user->societe_id)) - { - // Notes - $nbNote = 0; - if(!empty($object->note)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/user/note.php?id='.$object->id; - $head[$h][1] = $langs->trans("Note"); + if (! empty($conf->clicktodial->enabled)) + { + $head[$h][0] = DOL_URL_ROOT.'/user/clicktodial.php?id='.$object->id; + $head[$h][1] = $langs->trans("ClickToDial"); + $head[$h][2] = 'clicktodial'; + $h++; + } + + // Notifications + if ($user->societe_id == 0 && ! empty($conf->notification->enabled)) + { + $nbNote = 0; + $sql = "SELECT COUNT(n.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."notify_def as n"; + $sql.= " WHERE fk_user = ".$object->id; + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $nbNote=$obj->nb; + $i++; + } + } + else { + dol_print_error($db); + } + + $head[$h][0] = DOL_URL_ROOT.'/user/notify/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("Notifications"); if ($nbNote > 0) $head[$h][1].= ' '.$nbNote.''; - $head[$h][2] = 'note'; - $h++; + $head[$h][2] = 'notify'; + $h++; + } - // Attached files - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->user->dir_output . "/" . $object->id; - $nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$')); - $nbLinks=Link::count($db, $object->element, $object->id); - $head[$h][0] = DOL_URL_ROOT.'/user/document.php?userid='.$object->id; - $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' '.($nbFiles+$nbLinks).''; - $head[$h][2] = 'document'; - $h++; + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf,$langs,$object,$head,$h,'user'); - $head[$h][0] = DOL_URL_ROOT.'/user/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; - } + if ((! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) + || (! empty($conf->hrm->enabled) && ! empty($user->rights->hrm->employee->read))) + { + // Bank + $head[$h][0] = DOL_URL_ROOT.'/user/bank.php?id='.$object->id; + $head[$h][1] = $langs->trans("HRAndBank"); + $head[$h][2] = 'bank'; + $h++; + } - complete_head_from_modules($conf,$langs,$object,$head,$h,'user','remove'); + // Such info on users is visible only by internal user + if (empty($user->societe_id)) + { + // Notes + $nbNote = 0; + if(!empty($object->note)) $nbNote++; + $head[$h][0] = DOL_URL_ROOT.'/user/note.php?id='.$object->id; + $head[$h][1] = $langs->trans("Note"); + if ($nbNote > 0) $head[$h][1].= ' '.$nbNote.''; + $head[$h][2] = 'note'; + $h++; + + // Attached files + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->user->dir_output . "/" . $object->id; + $nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$')); + $nbLinks=Link::count($db, $object->element, $object->id); + $head[$h][0] = DOL_URL_ROOT.'/user/document.php?userid='.$object->id; + $head[$h][1] = $langs->trans("Documents"); + if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' '.($nbFiles+$nbLinks).''; + $head[$h][2] = 'document'; + $h++; + + $head[$h][0] = DOL_URL_ROOT.'/user/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; + } + + complete_head_from_modules($conf,$langs,$object,$head,$h,'user','remove'); return $head; } @@ -205,18 +206,19 @@ function group_prepare_head($object) $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/user/group/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("GroupCard"); - $head[$h][2] = 'group'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/group/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("GroupCard"); + $head[$h][2] = 'group'; + $h++; - if (! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_SYNCHRO_ACTIVE)) + if ((! empty($conf->ldap->enabled) && ! empty($conf->global->LDAP_SYNCHRO_ACTIVE)) + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || ! empty($user->admin))) { $langs->load("ldap"); - $head[$h][0] = DOL_URL_ROOT.'/user/group/ldap.php?id='.$object->id; - $head[$h][1] = $langs->trans("LDAPCard"); - $head[$h][2] = 'ldap'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/group/ldap.php?id='.$object->id; + $head[$h][1] = $langs->trans("LDAPCard"); + $head[$h][2] = 'ldap'; + $h++; } if ($canreadperms) @@ -227,15 +229,15 @@ function group_prepare_head($object) $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf,$langs,$object,$head,$h,'group'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf,$langs,$object,$head,$h,'group'); - complete_head_from_modules($conf,$langs,$object,$head,$h,'group','remove'); + complete_head_from_modules($conf,$langs,$object,$head,$h,'group','remove'); - return $head; + return $head; } /** @@ -250,25 +252,25 @@ function user_admin_prepare_head() $langs->load("users"); $h=0; - $head[$h][0] = DOL_URL_ROOT.'/admin/user.php'; - $head[$h][1] = $langs->trans("Parameters"); - $head[$h][2] = 'card'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/user.php'; + $head[$h][1] = $langs->trans("Parameters"); + $head[$h][2] = 'card'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/admin/usergroup.php'; - $head[$h][1] = $langs->trans("Group"); - $head[$h][2] = 'usergroupcard'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/usergroup.php'; + $head[$h][1] = $langs->trans("Group"); + $head[$h][2] = 'usergroupcard'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/user/admin/user_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFields"); - $head[$h][2] = 'attributes'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/user/admin/user_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'attributes'; + $h++; $head[$h][0] = DOL_URL_ROOT.'/user/admin/group_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFields")." ".$langs->trans("Groups"); - $head[$h][2] = 'attributes_group'; - $h++; + $head[$h][1] = $langs->trans("ExtraFields")." ".$langs->trans("Groups"); + $head[$h][2] = 'attributes_group'; + $h++; // Show more tabs from modules // Entries must be declared in modules descriptor with line @@ -291,138 +293,138 @@ function user_admin_prepare_head() */ function show_theme($fuser,$edit=0,$foruserprofile=false) { - global $conf,$langs,$db,$form; - global $bc; + global $conf,$langs,$db,$form; + global $bc; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; - $formother = new FormOther($db); + $formother = new FormOther($db); - $dirthemes=array('/theme'); - if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application - { - foreach($conf->modules_parts['theme'] as $reldir) - { - $dirthemes=array_merge($dirthemes,(array) ($reldir.'theme')); - } - } - $dirthemes=array_unique($dirthemes); + $dirthemes=array('/theme'); + if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application + { + foreach($conf->modules_parts['theme'] as $reldir) + { + $dirthemes=array_merge($dirthemes,(array) ($reldir.'theme')); + } + } + $dirthemes=array_unique($dirthemes); // Now dir_themes=array('/themes') or dir_themes=array('/theme','/mymodule/theme') - $selected_theme=''; - if (empty($foruserprofile)) $selected_theme=$conf->global->MAIN_THEME; - else $selected_theme=((is_object($fuser) && ! empty($fuser->conf->MAIN_THEME))?$fuser->conf->MAIN_THEME:''); + $selected_theme=''; + if (empty($foruserprofile)) $selected_theme=$conf->global->MAIN_THEME; + else $selected_theme=((is_object($fuser) && ! empty($fuser->conf->MAIN_THEME))?$fuser->conf->MAIN_THEME:''); $hoverdisabled=''; - if (empty($foruserprofile)) $hoverdisabled=(isset($conf->global->THEME_ELDY_USE_HOVER) && $conf->global->THEME_ELDY_USE_HOVER == '0'); - else $hoverdisabled=(is_object($fuser)?(empty($fuser->conf->THEME_ELDY_USE_HOVER) || $fuser->conf->THEME_ELDY_USE_HOVER == '0'):''); + if (empty($foruserprofile)) $hoverdisabled=(isset($conf->global->THEME_ELDY_USE_HOVER) && $conf->global->THEME_ELDY_USE_HOVER == '0'); + else $hoverdisabled=(is_object($fuser)?(empty($fuser->conf->THEME_ELDY_USE_HOVER) || $fuser->conf->THEME_ELDY_USE_HOVER == '0'):''); - $colspan=2; - if ($foruserprofile) $colspan=4; + $colspan=2; + if ($foruserprofile) $colspan=4; - $thumbsbyrow=6; - print '
    '; $out.=$formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:-1, 0, 0, 1); $out.=''; + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + { + if ($histo[$key]['apicto']) $out.=img_picto('', $histo[$key]['apicto']); + else { + if ($histo[$key]['acode'] == 'AC_TEL') $out.=img_picto('', 'object_phoning').' '; + if ($histo[$key]['acode'] == 'AC_FAX') $out.=img_picto('', 'object_phoning_fax').' '; + if ($histo[$key]['acode'] == 'AC_EMAIL') $out.=img_picto('', 'object_email').' '; + } + $out.=$actionstatic->type; + } + else { + $typelabel = $actionstatic->type; + if ($histo[$key]['acode'] != 'AC_OTH_AUTO') $typelabel = $langs->trans("ActionAC_MANUAL"); + $out.=$typelabel; + } + $out.=''; if (isset($histo[$key]['type']) && $histo[$key]['type']=='action') @@ -1388,25 +1429,6 @@ function show_actions_done($conf, $langs, $db, $filterobj, $objcon='', $noprint= if ($late) $out.=img_warning($langs->trans("Late")).' '; $out.="'; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($histo[$key]['apicto']) $out.=img_picto('', $histo[$key]['apicto']); - else { - if ($histo[$key]['acode'] == 'AC_TEL') $out.=img_picto('', 'object_phoning').' '; - if ($histo[$key]['acode'] == 'AC_FAX') $out.=img_picto('', 'object_phoning_fax').' '; - if ($histo[$key]['acode'] == 'AC_EMAIL') $out.=img_picto('', 'object_email').' '; - } - $out.=$actionstatic->type; - } - else { - $typelabel = $actionstatic->type; - if ($histo[$key]['acode'] != 'AC_OTH_AUTO') $typelabel = $langs->trans("ActionAC_MANUAL"); - $out.=$typelabel; - } - $out.=''.dol_trunc($histo[$key]['note'], 40).''; $return.= '
    '.$titre.'
    '; $return.= '
    '.$morehtmlcenter.''.$morehtmlright.''; $taskstatic->projectstatus = $lines[$i]->projectstatus; - $taskstatic->progress = $lines[$i]->progress; - $taskstatic->fk_statut = $lines[$i]->status; - $taskstatic->datee = $lines[$i]->date_end; - print dol_print_date($lines[$i]->date_end,'dayhour'); - if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late")); + $taskstatic->progress = $lines[$i]->progress; + $taskstatic->fk_statut = $lines[$i]->status; + $taskstatic->datee = $lines[$i]->date_end; + print dol_print_date($lines[$i]->date_end,'dayhour'); + if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late")); print '
    '; + print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($projectstatic->title) + { + print ' - '; + print $projectstatic->title; + } + print '
    "; - print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); print "'; + if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); + print ''; - $taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id); - print $taskstatic->getNomUrl(1,'withproject'); - print ''; - $thirdpartystatic->id=$lines[$i]->socid; - $thirdpartystatic->name=$lines[$i]->thirdparty_name; - print $thirdpartystatic->getNomUrl(1, 'project', 10); - print '"; + print ''; for ($k = 0 ; $k < $level ; $k++) print "   "; - $taskstatic->id=$lines[$i]->id; - $taskstatic->ref=$lines[$i]->label; - $taskstatic->date_start=$lines[$i]->date_start; - $taskstatic->date_end=$lines[$i]->date_end; - print $taskstatic->getNomUrl(0,'withproject'); + print $taskstatic->getNomUrl(1, 'withproject', 'time'); + // Label task + print '
    '; + for ($k = 0 ; $k < $level ; $k++) print "   "; + print $taskstatic->label; //print "
    "; //for ($k = 0 ; $k < $level ; $k++) print "   "; //print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0); @@ -741,14 +770,14 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr print '
    '; $dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$preselectedday][$lines[$i]->id]; - $alreadyspent=''; - if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin'); + $alreadyspent=''; + if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin'); - $idw = 0; + $idw = 0; $tableCell=''; $tableCell.=''; - $tableCell.=' + '; + $tableCell.=' + '; //$tableCell.='   '; $tableCell.=$form->select_duration($lines[$i]->id.'duration','',$disabledtask,'text',0,1); //$tableCell.=' '; @@ -764,7 +793,8 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr print ''; + // Note + print ''; print ''; print '
    '; + print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($projectstatic->title) + { + print ' - '; + print $projectstatic->title; + } + print '
    '; - print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); print "'; - $thirdpartystatic->id=$lines[$i]->thirdparty_id; - $thirdpartystatic->name=$lines[$i]->thirdparty_name; - print $thirdpartystatic->getNomUrl(1, 'project'); - print ''; + if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project'); + print ''; - $taskstatic->id=$lines[$i]->id; - $taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id); - print $taskstatic->getNomUrl(1, 'withproject', 'time'); - print '"; print ''; for ($k = 0 ; $k < $level ; $k++) print "   "; - $taskstatic->id=$lines[$i]->id; - $taskstatic->ref=$lines[$i]->label; - $taskstatic->date_start=$lines[$i]->date_start; - $taskstatic->date_end=$lines[$i]->date_end; - print $taskstatic->getNomUrl(0, 'withproject', 'time'); + print $taskstatic->getNomUrl(1, 'withproject', 'time'); + // Label task + print '
    '; + for ($k = 0 ; $k < $level ; $k++) print "   "; + //print $taskstatic->getNomUrl(0, 'withproject', 'time'); + print $taskstatic->label; //print "
    "; //for ($k = 0 ; $k < $level ; $k++) print "   "; //print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0); @@ -967,7 +1015,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Fields to show current time $tableCell=''; $modeinput='hours'; for ($idw = 0; $idw < 7; $idw++) - { + { $tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $cssonholiday=''; @@ -976,28 +1024,28 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ elseif (! $isavailable[$tmpday]['afternoon']) $cssonholiday.='onholidayafternoon '; $tmparray=dol_getdate($tmpday); - $dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$tmpday][$lines[$i]->id]; - $alreadyspent=''; - if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin'); - $alttitle=$langs->trans("AddHereTimeSpentForDay",$tmparray['day'],$tmparray['mon']); + $dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$tmpday][$lines[$i]->id]; + $alreadyspent=''; + if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin'); + $alttitle=$langs->trans("AddHereTimeSpentForDay",$tmparray['day'],$tmparray['mon']); - $tableCell ='
    '; - if ($alreadyspent) - { - $tableCell.=''; - //$placeholder=' placeholder="00:00"'; - $placeholder=''; - //$tableCell.='+'; - } - $tableCell.=''; - $tableCell.=''; + if ($alreadyspent) + { + $tableCell.=''; + //$placeholder=' placeholder="00:00"'; + $placeholder=''; + //$tableCell.='+'; + } + $tableCell.=''; + $tableCell.=''; if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("UserIsNotContactOfProject")); else if ($disabledtask) @@ -1009,7 +1057,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ } print '
    '; if ($objp->fk_soc > 0) { - $thirdpartystatic->id=$objp->fk_soc; - $thirdpartystatic->ref=$objp->socname; - $thirdpartystatic->name=$objp->socname; - print $thirdpartystatic->getNomUrl(1); + $thirdpartystatic->id=$objp->fk_soc; + $thirdpartystatic->ref=$objp->socname; + $thirdpartystatic->name=$objp->socname; + print $thirdpartystatic->getNomUrl(1); } print ''; - if ($objp->opp_amount) print price($objp->opp_amount, 0, '', 1, -1, -1, $conf->currency); + if ($objp->opp_amount) print price($objp->opp_amount, 0, '', 1, -1, -1, $conf->currency); print ''; $code = dol_getIdFromCode($db, $objp->opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); + if ($code) print $langs->trans("OppStatus".$code); print ''.$objp->nb.''.$objp->nb.''.($plannedworkload?convertSecondToTime($plannedworkload):'').''; - //print $objp->planned_workload.'-'.$objp->declared_progess_workload."
    "; - print ($plannedworkload?round(100*$declaredprogressworkload/$plannedworkload,0).'%':''); - print '
    '.($plannedworkload?convertSecondToTime($plannedworkload):'').''; + //print $objp->planned_workload.'-'.$objp->declared_progess_workload."
    "; + print ($plannedworkload?round(100*$declaredprogressworkload/$plannedworkload,0).'%':''); + print '
    '.$projectstatic->getLibStatut(3).''.$total_task.''.($total_plannedworkload?convertSecondToTime($total_plannedworkload):'').''.($total_plannedworkload?round(100*$total_declaredprogressworkload/$total_plannedworkload,0).'%':'').''.$total_task.''.($total_plannedworkload?convertSecondToTime($total_plannedworkload):'').''.($total_plannedworkload?round(100*$total_declaredprogressworkload/$total_plannedworkload,0).'%':'').'
    '; + $thumbsbyrow=6; + print '
    '; - // Title - if ($foruserprofile) - { - print ''; - print ''; - print ''; + // Title + if ($foruserprofile) + { + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - else - { - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + else + { + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; + } - print ''; + print ''; - // TopMenuDisableImages - if ($foruserprofile) - { - /* + // TopMenuDisableImages + if ($foruserprofile) + { + /* print ''; print ''; print ''; - print ''; print '';*/ - } - else - { - $default=$langs->trans('No'); - print ''; - print ''; - print ''; - } + } + else + { + $default=$langs->trans('No'); + print ''; + print ''; + print ''; + } // Background color THEME_ELDY_BACKBODY - if ($foruserprofile) + if ($foruserprofile) { - /* + /* print ''; print ''; print ''; @@ -484,29 +486,29 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - print ''; - print ''; - print ''; + print ''; + print ''; + print '   ('.$langs->trans("Default").': ffffff) '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print ''; } // TopMenuBackgroundColor - if ($foruserprofile) + if ($foruserprofile) { - /* + /* print ''; print ''; print ''; @@ -529,25 +531,72 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - $default='5a6482'; - if ($conf->theme == 'md') $default='5a3278'; + $default='5a6482'; + if ($conf->theme == 'md') $default='5a3278'; - print ''; - print ''; - print ''; + print ''; + print ''; + print '   ('.$langs->trans("Default").': '.$default.') '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print ''; + } + + // LeftMenuBackgroundColor + if ($foruserprofile) + { + /* + print ''; + print ''; + print ''; + print ''; + print '';*/ + } + else + { + $default='ffffff'; + if ($conf->theme == 'md') $default='ffffff'; + + print ''; + print ''; + print ''; } // BackgroundTableTitleColor @@ -558,22 +607,22 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - print ''; - print ''; - print ''; + print ''; + print ''; + print '   ('.$langs->trans("Default").': f0f0f0) '; // $colorbacktitle1 in CSS + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print ''; - print ''; + print ''; } // BackgroundTableLineOddColor @@ -583,25 +632,25 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - $default='ffffff'; - if ($conf->theme == 'md') $default='ffffff'; + $default='ffffff'; + if ($conf->theme == 'md') $default='ffffff'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // BackgroundTableLineEvenColor @@ -611,25 +660,25 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - $default='f8f8f8'; - if ($conf->theme == 'md') $default='f8f8f8'; + $default='f8f8f8'; + if ($conf->theme == 'md') $default='f8f8f8'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // TextTitleColor @@ -640,43 +689,43 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - print ''; + print ''; } // Text LinkColor if ($foruserprofile) { - /* + /* print ''; print ''; - print ''; - print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // Use Hover if ($foruserprofile) { - /* Must first change option to choose color of highlight instead of yes or no. + /* Must first change option to choose color of highlight instead of yes or no. print ''; print ''; print ''; @@ -724,33 +773,33 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; } - print '
    '.$langs->trans("Parameter").''.$langs->trans("DefaultValue").' 
    '.$langs->trans("Parameter").''.$langs->trans("DefaultValue").' 
    '.$langs->trans("DefaultSkin").''.$conf->global->MAIN_THEME.' '.$langs->trans("UsePersonalValue").' 
    '.$langs->trans("DefaultSkin").''; - $url='https://www.dolistore.com/lang-en/4-skins'; - if (preg_match('/fr/i',$langs->defaultlang)) $url='https://www.dolistore.com/fr/4-themes'; - //if (preg_match('/es/i',$langs->defaultlang)) $url='http://www.dolistore.com/lang-es/4-themes'; - print ''; - print $langs->trans('DownloadMoreSkins'); - print ''; - print '
    '.$langs->trans("DefaultSkin").''.$conf->global->MAIN_THEME.' '.$langs->trans("UsePersonalValue").' 
    '.$langs->trans("DefaultSkin").''; + $url='https://www.dolistore.com/lang-en/4-skins'; + if (preg_match('/fr/i',$langs->defaultlang)) $url='https://www.dolistore.com/fr/4-themes'; + //if (preg_match('/es/i',$langs->defaultlang)) $url='http://www.dolistore.com/lang-es/4-themes'; + print ''; + print $langs->trans('DownloadMoreSkins'); + print ''; + print '
    '.$langs->trans("ThemeDir").''; - foreach($dirthemes as $dirtheme) - { - echo '"'.$dirtheme.'" '; - } - print '
    '.$langs->trans("ThemeDir").''; + foreach($dirthemes as $dirtheme) + { + echo '"'.$dirtheme.'" '; + } + print '
    '; + print '
    '; - print '
    '; + print '
    '; - $i=0; - foreach($dirthemes as $dir) - { - //print $dirroot.$dir;exit; - $dirtheme=dol_buildpath($dir,0); // This include loop on $conf->file->dol_document_root - $urltheme=dol_buildpath($dir,1); + $i=0; + foreach($dirthemes as $dir) + { + //print $dirroot.$dir;exit; + $dirtheme=dol_buildpath($dir,0); // This include loop on $conf->file->dol_document_root + $urltheme=dol_buildpath($dir,1); - if (is_dir($dirtheme)) - { - $handle=opendir($dirtheme); - if (is_resource($handle)) - { - while (($subdir = readdir($handle))!==false) - { - if (is_dir($dirtheme."/".$subdir) && substr($subdir, 0, 1) <> '.' - && substr($subdir, 0, 3) <> 'CVS' && ! preg_match('/common|phones/i',$subdir)) - { - // Disable not stable themes (dir ends with _exp or _dev) - if ($conf->global->MAIN_FEATURES_LEVEL < 2 && preg_match('/_dev$/i',$subdir)) continue; - if ($conf->global->MAIN_FEATURES_LEVEL < 1 && preg_match('/_exp$/i',$subdir)) continue; + if (is_dir($dirtheme)) + { + $handle=opendir($dirtheme); + if (is_resource($handle)) + { + while (($subdir = readdir($handle))!==false) + { + if (is_dir($dirtheme."/".$subdir) && substr($subdir, 0, 1) <> '.' + && substr($subdir, 0, 3) <> 'CVS' && ! preg_match('/common|phones/i',$subdir)) + { + // Disable not stable themes (dir ends with _exp or _dev) + if ($conf->global->MAIN_FEATURES_LEVEL < 2 && preg_match('/_dev$/i',$subdir)) continue; + if ($conf->global->MAIN_FEATURES_LEVEL < 1 && preg_match('/_exp$/i',$subdir)) continue; - print '
    '; - $file=$dirtheme."/".$subdir."/thumb.png"; - $url=$urltheme."/".$subdir."/thumb.png"; - if (! file_exists($file)) $url=DOL_URL_ROOT.'/public/theme/common/nophoto.png'; - print 'id:'').'" style="font-weight: normal;" alt="'.$langs->trans("Preview").'">'; - if ($subdir == $conf->global->MAIN_THEME) $title=$langs->trans("ThemeCurrentlyActive"); - else $title=$langs->trans("ShowPreview"); - print ''.$title.''; - print '
    '; - if ($subdir == $selected_theme) - { - print ' '.$subdir.''; - } - else - { - print ' '.$subdir; - } + print '
    '; + $file=$dirtheme."/".$subdir."/thumb.png"; + $url=$urltheme."/".$subdir."/thumb.png"; + if (! file_exists($file)) $url=DOL_URL_ROOT.'/public/theme/common/nophoto.png'; + print 'id:'').'" style="font-weight: normal;" alt="'.$langs->trans("Preview").'">'; + if ($subdir == $conf->global->MAIN_THEME) $title=$langs->trans("ThemeCurrentlyActive"); + else $title=$langs->trans("ShowPreview"); + print ''.$title.''; + print '
    '; + if ($subdir == $selected_theme) + { + print ' '.$subdir.''; + } + else + { + print ' '.$subdir; + } print '
    '; - $i++; - } - } - } - } - } + $i++; + } + } + } + } + } - print '
    '; + print '
    '; - print '
    '.$langs->trans("TopMenuDisableImages").''.($conf->global->THEME_TOPMENU_DISABLE_IMAGE?$conf->global->THEME_TOPMENU_DISABLE_IMAGE:$langs->trans("Default")).'conf->THEME_ELDY_TOPMENU_BACK1)?" checked":""); + print 'conf->THEME_ELDY_TEXTLINK)?" checked":""); print (empty($dolibarr_main_demo) && $edit)?'':' disabled="disabled"'; // Disabled for demo print '> '.$langs->trans("UsePersonalValue").''; @@ -438,30 +440,30 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } if ($edit) print '
    ('.$langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis").')'; print '
    '.$langs->trans("TopMenuDisableImages").''; - if ($edit) - { - print $form->selectyesno('THEME_TOPMENU_DISABLE_IMAGE', $conf->global->THEME_TOPMENU_DISABLE_IMAGE, 1); - } - else - { - print yn($conf->global->THEME_TOPMENU_DISABLE_IMAGE); - } - print '   ('.$langs->trans("Default").': '.$default.') '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("TopMenuDisableImages").''; + if ($edit) + { + print $form->selectyesno('THEME_TOPMENU_DISABLE_IMAGE', $conf->global->THEME_TOPMENU_DISABLE_IMAGE, 1); + } + else + { + print yn($conf->global->THEME_TOPMENU_DISABLE_IMAGE); + } + print '   ('.$langs->trans("Default").': '.$default.') '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '.$langs->trans("TopMenuBackgroundColor").''.($conf->global->THEME_ELDY_TOPMENU_BACK1?$conf->global->THEME_ELDY_TOPMENU_BACK1:$langs->trans("Default")).'
    '.$langs->trans("BackgroundColor").''; - //var_dump($conf->global->THEME_ELDY_BACKBODY); - if ($edit) - { + print '
    '.$langs->trans("BackgroundColor").''; + //var_dump($conf->global->THEME_ELDY_BACKBODY); + if ($edit) + { print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKBODY,array()),''),'THEME_ELDY_BACKBODY','formcolor',1).' '; - } + } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKBODY,array()),''); if ($color) print ''; else print $langs->trans("Default"); } - print '   ('.$langs->trans("Default").': ffffff) '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("TopMenuBackgroundColor").''.($conf->global->THEME_ELDY_TOPMENU_BACK1?$conf->global->THEME_ELDY_TOPMENU_BACK1:$langs->trans("Default")).'
    '.$langs->trans("TopMenuBackgroundColor").''; - if ($edit) - { + print '
    '.$langs->trans("TopMenuBackgroundColor").''; + if ($edit) + { print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1,array()),''),'THEME_ELDY_TOPMENU_BACK1','formcolor',1).' '; - } + } else { $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1,array()),''); if ($color) print ''; else print $langs->trans("Default"); } - print '   ('.$langs->trans("Default").': '.$default.') '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("TopMenuBackgroundColor").''.($conf->global->THEME_ELDY_TOPMENU_BACK1?$conf->global->THEME_ELDY_VERMENU_BACK1:$langs->trans("Default")).'conf->THEME_ELDY_TOPMENU_BACK1)?" checked":""); + print (empty($dolibarr_main_demo) && $edit)?'':' disabled="disabled"'; // Disabled for demo + print '> '.$langs->trans("UsePersonalValue").''; + if ($edit) + { + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1,array()),''),'THEME_ELDY_VERMENU_BACK1','formcolor',1).' '; + } + else + { + $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1,array()),''); + if ($color) print ''; + else print ''; + } + if ($edit) print '
    ('.$langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis").')'; + print '
    '.$langs->trans("LeftMenuBackgroundColor").''; + if ($edit) + { + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1,array()),''),'THEME_ELDY_VERMENU_BACK1','formcolor',1).' '; + } + else + { + $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_VERMENU_BACK1,array()),''); + if ($color) print ''; + else print $langs->trans("Default"); + } + print '   ('.$langs->trans("Default").': '.$default.') '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '.$langs->trans("BackgroundTableTitleColor").''; - if ($edit) - { + print '
    '.$langs->trans("BackgroundTableTitleColor").''; + if ($edit) + { print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_BACKTITLE1,array()),''),'THEME_ELDY_BACKTITLE1','formcolor',1).' '; - } + } else { print $formother->showColor($conf->global->THEME_ELDY_BACKTITLE1, $langs->trans("Default")); } - print '   ('.$langs->trans("Default").': f0f0f0) '; // $colorbacktitle1 in CSS - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("BackgroundTableLineOddColor").''; - if ($edit) - { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1,array()),''),'THEME_ELDY_LINEIMPAIR1','formcolor',1).' '; - } - else - { - $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1,array()),''); - if ($color) print ''; - else print $langs->trans("Default"); - } - print '   ('.$langs->trans("Default").': '.$default.') '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("BackgroundTableLineOddColor").''; + if ($edit) + { + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1,array()),''),'THEME_ELDY_LINEIMPAIR1','formcolor',1).' '; + } + else + { + $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEIMPAIR1,array()),''); + if ($color) print ''; + else print $langs->trans("Default"); + } + print '   ('.$langs->trans("Default").': '.$default.') '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '.$langs->trans("BackgroundTableLineEvenColor").''; - if ($edit) - { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1,array()),''),'THEME_ELDY_LINEPAIR1','formcolor',1).' '; - } - else - { - $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1,array()),''); - if ($color) print ''; - else print $langs->trans("Default"); - } - print '   ('.$langs->trans("Default").': '.$default.') '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("BackgroundTableLineEvenColor").''; + if ($edit) + { + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1,array()),''),'THEME_ELDY_LINEPAIR1','formcolor',1).' '; + } + else + { + $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_LINEPAIR1,array()),''); + if ($color) print ''; + else print $langs->trans("Default"); + } + print '   ('.$langs->trans("Default").': '.$default.') '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '.$langs->trans("TextTitleColor").''; - if ($edit) - { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLENOTAB,array()),''),'THEME_ELDY_TEXTTITLENOTAB','formcolor',1).' '; - } - else - { - print $formother->showColor($conf->global->THEME_ELDY_TEXTTITLENOTAB, $langs->trans("Default")); - } - print '   ('.$langs->trans("Default").': 3c3c14) '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '.$langs->trans("TextTitleColor").''; + if ($edit) + { + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTTITLENOTAB,array()),''),'THEME_ELDY_TEXTTITLENOTAB','formcolor',1).' '; + } + else + { + print $formother->showColor($conf->global->THEME_ELDY_TEXTTITLENOTAB, $langs->trans("Default")); + } + print '   ('.$langs->trans("Default").': 3c3c14) '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("TopMenuBackgroundColor").''.($conf->global->THEME_ELDY_TOPMENU_BACK1?$conf->global->THEME_ELDY_TOPMENU_BACK1:$langs->trans("Default")).'conf->THEME_ELDY_TOPMENU_BACK1)?" checked":""); + print ''.($conf->global->THEME_ELDY_TOPMENU_BACK1?$conf->global->THEME_ELDY_TEXTLINK:$langs->trans("Default")).'conf->THEME_ELDY_TEXTLINK)?" checked":""); print (empty($dolibarr_main_demo) && $edit)?'':' disabled="disabled"'; // Disabled for demo print '> '.$langs->trans("UsePersonalValue").''; if ($edit) { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1,array()),''),'THEME_ELDY_TOPMENU_BACK1','formcolor',1).' '; + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),''),'THEME_ELDY_TEXTLINK','formcolor',1).' '; } else { - $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TOPMENU_BACK1,array()),''); + $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),''); if ($color) print ''; else print ''; } @@ -685,33 +734,33 @@ function show_theme($fuser,$edit=0,$foruserprofile=false) } else { - print '
    '.$langs->trans("LinkColor").''; - if ($edit) - { - print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),''),'THEME_ELDY_TEXTLINK','formcolor',1).' '; - } - else - { - $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),''); - if ($color) print ''; - else - { - //print ''; - //print ''.$langs->trans("Default").''; - print $langs->trans("Default"); - } - } - print '   ('.$langs->trans("Default").': 000078) '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("LinkColor").''; + if ($edit) + { + print $formother->selectColor(colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),''),'THEME_ELDY_TEXTLINK','formcolor',1).' '; + } + else + { + $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_TEXTLINK,array()),''); + if ($color) print ''; + else + { + //print ''; + //print ''.$langs->trans("Default").''; + print $langs->trans("Default"); + } + } + print '   ('.$langs->trans("Default").': 000078) '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '.$langs->trans("HighlightLinesOnMouseHover").'global->THEME_ELDY_USE_HOVER?" checked":"").'>
    '.$langs->trans("HighlightLinesColor").''; - //print ''; - //print '   ('.$langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis").')'; - if ($edit) - { - if ($conf->global->THEME_ELDY_USE_HOVER == '1') $color='edf4fb'; - else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_HOVER,array()),''); - print $formother->selectColor($color,'THEME_ELDY_USE_HOVER','formcolor',1).' '; - } - else - { - if ($conf->global->THEME_ELDY_USE_HOVER == '1') $color='edf4fb'; - else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_HOVER,array()),''); - if ($color) - { - if ($color != 'edf4fb') print ''; - else print $langs->trans("Default"); - } - else print $langs->trans("None"); - } - print '   ('.$langs->trans("Default").': edf4fb) '; - print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); - print '
    '.$langs->trans("HighlightLinesColor").''; + //print ''; + //print '   ('.$langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis").')'; + if ($edit) + { + if ($conf->global->THEME_ELDY_USE_HOVER == '1') $color='edf4fb'; + else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_HOVER,array()),''); + print $formother->selectColor($color,'THEME_ELDY_USE_HOVER','formcolor',1).' '; + } + else + { + if ($conf->global->THEME_ELDY_USE_HOVER == '1') $color='edf4fb'; + else $color = colorArrayToHex(colorStringToArray($conf->global->THEME_ELDY_USE_HOVER,array()),''); + if ($color) + { + if ($color != 'edf4fb') print ''; + else print $langs->trans("Default"); + } + else print $langs->trans("None"); + } + print '   ('.$langs->trans("Default").': edf4fb) '; + print $form->textwithpicto('', $langs->trans("NotSupportedByAllThemes").', '.$langs->trans("PressF5AfterChangingThis")); + print '
    '; + print ''; } diff --git a/htdocs/core/lib/website.lib.php b/htdocs/core/lib/website.lib.php index 122c3a6aa7d..806d5d7a640 100644 --- a/htdocs/core/lib/website.lib.php +++ b/htdocs/core/lib/website.lib.php @@ -31,59 +31,59 @@ */ function dolWebsiteOutput($content) { - global $db, $langs, $conf, $user; - global $dolibarr_main_url_root, $dolibarr_main_data_root; + global $db, $langs, $conf, $user; + global $dolibarr_main_url_root, $dolibarr_main_data_root; - dol_syslog("dolWebsiteOutput start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')'); + dol_syslog("dolWebsiteOutput start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')'); - // Define $urlwithroot - $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); - $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + // Define $urlwithroot + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - // Note: This seems never called when page is output inside the website editor (search 'REPLACEMENT OF LINKS When page called by website editor') + // Note: This seems never called when page is output inside the website editor (search 'REPLACEMENT OF LINKS When page called by website editor') - if (! defined('USEDOLIBARRSERVER')) // REPLACEMENT OF LINKS When page called from virtual host - { - $symlinktomediaexists=1; + if (! defined('USEDOLIBARRSERVER')) // REPLACEMENT OF LINKS When page called from virtual host + { + $symlinktomediaexists=1; // Make a change into HTML code to allow to include images from medias directory correct with direct link for virtual server // // become // - $nbrep=0; - if (! $symlinktomediaexists) - { - $content=preg_replace('/()/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep); - $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep); - } - else - { - $content=preg_replace('/()/', '\1medias/\4\5', $content, -1, $nbrep); - $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1medias/\4\5', $content, -1, $nbrep); - } - } - else // REPLACEMENT OF LINKS When page called from dolibarr server - { - global $website; + $nbrep=0; + if (! $symlinktomediaexists) + { + $content=preg_replace('/(]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/?>)/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep); + $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep); + } + else + { + $content=preg_replace('/(]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/?>)/', '\1medias/\4\5', $content, -1, $nbrep); + $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1medias/\4\5', $content, -1, $nbrep); + } + } + else // REPLACEMENT OF LINKS When page called from dolibarr server + { + global $website; - // Replace relative link / with dolibarr URL: ...href="/"... - $content=preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep); - // Replace relative link /xxx.php with dolibarr URL: ...href="....php" - $content=preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); + // Replace relative link / with dolibarr URL: ...href="/"... + $content=preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep); + // Replace relative link /xxx.php with dolibarr URL: ...href="....php" + $content=preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); - // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: ...href="/document.php?modulepart=" - $content=preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); - // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: ...href="/viewimage.php?modulepart=" - $content=preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); + // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: ...href="/document.php?modulepart=" + $content=preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); + // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: ...href="/viewimage.php?modulepart=" + $content=preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); - // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/ - $content=preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); - } + // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/ + $content=preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); + } - dol_syslog("dolWebsiteOutput end"); + dol_syslog("dolWebsiteOutput end"); - print $content; + print $content; } @@ -108,7 +108,7 @@ function dolWebsiteReplacementOfLinks($website, $content) $content = preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); // ]*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); return $content; } @@ -277,3 +277,142 @@ function exportWebSite($website) return $filename; } + +/** + * Download all images found into page content $tmp. + * If $modifylinks is set, links to images will be replace with a link to viewimage wrapper. + * + * @param Website $object Object website + * @param WebsitePage $objectpage Object website page + * @param string $urltograb URL to grab (exemple: http://www.nltechno.com/ or http://www.nltechno.com/dir1/ or http://www.nltechno.com/dir1/mapage1) + * @param string $tmp Content to parse + * @param string $action Var $action + * @param string $modifylinks 0=Do not modify content, 1=Replace links with a link to viewimage + * @return void + */ +function getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks=0) +{ + global $conf; + + $error=0; + + $alreadygrabbed=array(); + + if (preg_match('/\/$/', $urltograb)) $urltograb.='.'; + $urltograb = dirname($urltograb); // So urltograb is now http://www.nltechno.com or http://www.nltechno.com/dir1 + + preg_match_all('/]*)>/i', $tmp, $regs); + + foreach ($regs[0] as $key => $val) + { + if (preg_match('/^data:image/i', $regs[2][$key])) continue; // We do nothing for such images + + $urltograbbis = $urltograb.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + $linkwithoutdomain = $regs[2][$key]; + $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + if (preg_match('/^http/', $regs[2][$key])) + { + $urltograbbis = $regs[2][$key]; + $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); + $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + } + + $filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + + // Clean the aa/bb/../cc into aa/cc + $filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave); + $filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename); + + //var_dump($filetosave); + //var_dump($filename); + //exit; + + if (empty($alreadygrabbed[$urltograbbis])) + { + $tmpgeturl = getURLContent($urltograbbis); + if ($tmpgeturl['curl_error_no']) + { + $error++; + setEventMessages($tmpgeturl['curl_error_msg'], null, 'errors'); + $action='create'; + } + else + { + $alreadygrabbed[$urltograbbis]=1; // Track that file was alreay grabbed. + + dol_mkdir(dirname($filetosave)); + + $fp = fopen($filetosave, "w"); + fputs($fp, $tmpgeturl['content']); + fclose($fp); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filetosave, octdec($conf->global->MAIN_UMASK)); + } + } + + if ($modifylinks) + { + $tmp = preg_replace('/'.preg_quote($regs[0][$key],'/').'/i', '', $tmp); + } + } + + // Search X in "background...url(X)" + preg_match_all('/background([^\.\/\(;]+)url\([\"\']?([^\)\"\']*)[\"\']?\)/i', $tmp, $regs); + + foreach ($regs[0] as $key => $val) + { + if (preg_match('/^data:image/i', $regs[2][$key])) continue; // We do nothing for such images + + $urltograbbis = $urltograb.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + + $linkwithoutdomain = $regs[2][$key]; + $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; + + if (preg_match('/^http/', $regs[2][$key])) + { + $urltograbbis = $regs[2][$key]; + $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); + $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + } + + $filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; + + // Clean the aa/bb/../cc into aa/cc + $filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave); + $filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename); + + //var_dump($filetosave); + //var_dump($filename); + //exit; + + if (empty($alreadygrabbed[$urltograbbis])) + { + $tmpgeturl = getURLContent($urltograbbis); + if ($tmpgeturl['curl_error_no']) + { + $error++; + setEventMessages($tmpgeturl['curl_error_msg'], null, 'errors'); + $action='create'; + } + else + { + $alreadygrabbed[$urltograbbis]=1; // Track that file was alreay grabbed. + + dol_mkdir(dirname($filetosave)); + + $fp = fopen($filetosave, "w"); + fputs($fp, $tmpgeturl['content']); + fclose($fp); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filetosave, octdec($conf->global->MAIN_UMASK)); + } + } + + if ($modifylinks) + { + $tmp = preg_replace('/'.preg_quote($regs[0][$key],'/').'/i', 'background'.$regs[1][$key].'url("'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file='.$filename.'")', $tmp); + } + } + +} + diff --git a/htdocs/core/login/functions_ldap.php b/htdocs/core/login/functions_ldap.php index 129bbcedf38..d468c882b2d 100644 --- a/htdocs/core/login/functions_ldap.php +++ b/htdocs/core/login/functions_ldap.php @@ -98,12 +98,12 @@ function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest) $resultFetchLdapUser=0; // Define $userSearchFilter - $userSearchFilter = ""; - if (empty($dolibarr_main_auth_ldap_filter)) { - $userSearchFilter = "(" . $ldapuserattr . "=" . $usertotest . ")"; - } else { - $userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter); - } + $userSearchFilter = ""; + if (empty($dolibarr_main_auth_ldap_filter)) { + $userSearchFilter = "(" . $ldapuserattr . "=" . $usertotest . ")"; + } else { + $userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter); + } // If admin login provided // Code to get user in LDAP from an admin connection (may differ from user connection, done later) @@ -127,7 +127,7 @@ function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest) } else { - if ($ldapdebug) print "DEBUG: ".$ldap->error."
    \n"; + if ($ldapdebug) print "DEBUG: ".$ldap->error."
    \n"; } $ldap->close(); } @@ -135,15 +135,15 @@ function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest) // Forge LDAP user and password to test with them // If LDAP need a dn with login like "uid=jbloggs,ou=People,dc=foo,dc=com", default dn may work even if previous code with // admin login no exectued. - $ldap->searchUser=$ldapuserattr."=".$usertotest.",".$ldapdn; // Default dn (will work if LDAP accept a dn with login value inside) + $ldap->searchUser=$ldapuserattr."=".$usertotest.",".$ldapdn; // Default dn (will work if LDAP accept a dn with login value inside) // But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have // dn detected into ldapUserDN. - if ($resultFetchLdapUser AND !empty($ldap->ldapUserDN)) $ldap->searchUser = $ldap->ldapUserDN; - $ldap->searchPassword=$passwordtotest; + if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) $ldap->searchUser = $ldap->ldapUserDN; + $ldap->searchPassword=$passwordtotest; // Test with this->seachUser and this->searchPassword - //print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit; - $result=$ldap->connect_bind(); + //print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit; + $result=$ldap->connect_bind(); if ($result > 0) { if ($result == 2) // Connection is ok for user/pass into LDAP @@ -214,7 +214,7 @@ function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest) } else { - /* Login failed. Return false, together with the error code and text from + /* Login failed. Return false, together with the error code and text from ** the LDAP server. The common error codes and reasons are listed below : ** (for iPlanet, other servers may differ) ** 19 - Account locked out (too many invalid login attempts) @@ -222,13 +222,13 @@ function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest) ** 49 - Wrong password ** 53 - Account inactive (manually locked out by administrator) */ - dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP for '".$usertotest."'"); - if (is_resource($ldap->connection)) // If connection ok but bind ko - { - $ldap->ldapErrorCode = ldap_errno($ldap->connection); - $ldap->ldapErrorText = ldap_error($ldap->connection); - dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText); - } + dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP for '".$usertotest."'"); + if (is_resource($ldap->connection)) // If connection ok but bind ko + { + $ldap->ldapErrorCode = ldap_errno($ldap->connection); + $ldap->ldapErrorText = ldap_error($ldap->connection); + dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText); + } sleep(2); // Anti brut force protection $langs->load('main'); $langs->load('other'); diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql index 6a02f67c6d4..33039b390fd 100644 --- a/htdocs/core/menus/init_menu_auguria.sql +++ b/htdocs/core/menus/init_menu_auguria.sql @@ -14,7 +14,7 @@ insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, left insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('propal|commande|fournisseur|contrat|ficheinter', '$conf->propal->enabled || $conf->commande->enabled || $conf->supplier_order->enabled || $conf->contrat->enabled || $conf->ficheinter->enabled', 5__+MAX_llx_menu__, __HANDLER__, 'top', 'commercial', '', 0, '/comm/index.php?mainmenu=commercial&leftmenu=', 'Commercial', -1, 'commercial', '$user->rights->societe->lire || $user->rights->societe->contact->lire', '', 2, 40, __ENTITY__); insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('facture|don|tax|salaries|loan|banque', '$conf->comptabilite->enabled || $conf->accounting->enabled || $conf->facture->enabled || $conf->don->enabled || $conf->tax->enabled || $conf->salaries->enabled || $conf->supplier_invoice->enabled || $conf->loan->enabled || $conf->banque->enabled', 6__+MAX_llx_menu__, __HANDLER__, 'top', 'billing', '', 0, '/compta/index.php?mainmenu=billing&leftmenu=', 'MenuFinancial', -1, 'compta', '$user->rights->facture->lire|| $user->rights->don->lire || $user->rights->tax->charges->lire || $user->rights->salaries->read || $user->rights->loan->read || $user->rights->banque->lire', '', 2, 50, __ENTITY__); insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('comptabilite|accounting', '$conf->comptabilite->enabled || $conf->accounting->enabled || $conf->facture->enabled || $conf->don->enabled || $conf->tax->enabled || $conf->salaries->enabled || $conf->supplier_invoice->enabled || $conf->loan->enabled || $conf->banque->enabled', 9__+MAX_llx_menu__, __HANDLER__, 'top', 'accountancy', '', 0, '/compta/index.php?mainmenu=accountancy&leftmenu=accountancy', 'Accountancy', -1, 'compta', '$user->rights->compta->resultat->lire || $user->rights->accounting->mouvements->lire', '', 2, 51, __ENTITY__); -insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('banque|prelevement', '$conf->banque->enabled || $conf->prelevement->enabled', 14__+MAX_llx_menu__, __HANDLER__, 'top', 'bank', '', 0, '/compta/bank/index.php?mainmenu=bank&leftmenu=bank', 'MenuBankCash', -1, 'banks', '$user->rights->banque->lire || $user->rights->prelevement->bons->lire', '', 0, 60, __ENTITY__); +insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('banque|prelevement', '$conf->banque->enabled || $conf->prelevement->enabled', 14__+MAX_llx_menu__, __HANDLER__, 'top', 'bank', '', 0, '/compta/bank/list.php?mainmenu=bank&leftmenu=bank', 'MenuBankCash', -1, 'banks', '$user->rights->banque->lire || $user->rights->prelevement->bons->lire', '', 0, 60, __ENTITY__); insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('projet', '$conf->projet->enabled', 7__+MAX_llx_menu__, __HANDLER__, 'top', 'project', '', 0, '/projet/index.php?mainmenu=project&leftmenu=', 'Projects', -1, 'projects', '$user->rights->projet->lire', '', 2, 70, __ENTITY__); insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '', 8__+MAX_llx_menu__, __HANDLER__, 'top', 'tools', '', 0, '/core/tools.php?mainmenu=tools&leftmenu=', 'Tools', -1, 'other', '', '', 2, 90, __ENTITY__); insert into llx_menu (module, enabled, rowid, menu_handler, type, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('adherent', '$conf->adherent->enabled', 13__+MAX_llx_menu__, __HANDLER__, 'top', 'members', '', 0, '/adherents/index.php?mainmenu=members&leftmenu=', 'Members', -1, 'members', '$user->rights->adherent->lire', '', 2, 110, __ENTITY__); @@ -224,7 +224,7 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2457__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_chart_group', 2451__+MAX_llx_menu__, '/accountancy/admin/categories_list.php?id=32&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingCategory', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 41, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2458__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_default', 2451__+MAX_llx_menu__, '/accountancy/admin/defaultaccounts.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuDefaultAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 50, __ENTITY__); - insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2459__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_vat', 2451__+MAX_llx_menu__, '/compta/bank/index.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuBankAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 51, __ENTITY__); + insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2459__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_vat', 2451__+MAX_llx_menu__, '/compta/bank/list.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuBankAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 51, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2460__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_vat', 2451__+MAX_llx_menu__, '/admin/dict.php?id=10&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuVatAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 52, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2461__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_tax', 2451__+MAX_llx_menu__, '/admin/dict.php?id=7&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuTaxAccounts', 2, 'accountancy', '$user->rights->accounting->chartofaccount', '', 0, 53, __ENTITY__); @@ -283,10 +283,10 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->prelevement->enabled && $leftmenu=="withdraw"', __HANDLER__, 'left', 2506__+MAX_llx_menu__, 'accountancy', '', 2500__+MAX_llx_menu__, '/compta/prelevement/rejets.php?leftmenu=withdraw', 'Rejects', 1, 'withdrawals', '$user->rights->prelevement->bons->lire', '', 2, 5, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->prelevement->enabled && $leftmenu=="withdraw"', __HANDLER__, 'left', 2507__+MAX_llx_menu__, 'accountancy', '', 2500__+MAX_llx_menu__, '/compta/prelevement/stats.php?leftmenu=withdraw', 'Statistics', 1, 'withdrawals', '$user->rights->prelevement->bons->lire', '', 2, 6, __ENTITY__); -- Bank -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled', __HANDLER__, 'left', 2600__+MAX_llx_menu__, 'accountancy', 'bank', 14__+MAX_llx_menu__, '/compta/bank/index.php?leftmenu=bank&mainmenu=bank', 'MenuBankCash', 0, 'banks', '$user->rights->banque->lire', '', 0, 1, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled', __HANDLER__, 'left', 2600__+MAX_llx_menu__, 'accountancy', 'bank', 14__+MAX_llx_menu__, '/compta/bank/list.php?leftmenu=bank&mainmenu=bank', 'MenuBankCash', 0, 'banks', '$user->rights->banque->lire', '', 0, 1, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && ($leftmenu=="bank" || $leftmenu=="checks" || $leftmenu=="withdraw")', __HANDLER__, 'left', 2601__+MAX_llx_menu__, 'accountancy', '', 2600__+MAX_llx_menu__, '/compta/bank/card.php?action=create&leftmenu=bank', 'MenuNewFinancialAccount', 1, 'banks', '$user->rights->banque->configurer', '', 0, 0, __ENTITY__); -- insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && ($leftmenu=="bank" || $leftmenu=="checks" || $leftmenu=="withdraw")', __HANDLER__, 'left', 2602__+MAX_llx_menu__, 'accountancy', '', 2600__+MAX_llx_menu__, '/compta/bank/categ.php?leftmenu=bank', 'Rubriques', 1, 'categories', '$user->rights->banque->configurer', '', 0, 1, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && ($leftmenu=="bank" || $leftmenu=="checks" || $leftmenu=="withdraw")', __HANDLER__, 'left', 2603__+MAX_llx_menu__, 'accountancy', '', 2600__+MAX_llx_menu__, '/compta/bank/bankentries.php?leftmenu=bank', 'ListTransactions', 1, 'banks', '$user->rights->banque->lire', '', 0, 2, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && ($leftmenu=="bank" || $leftmenu=="checks" || $leftmenu=="withdraw")', __HANDLER__, 'left', 2603__+MAX_llx_menu__, 'accountancy', '', 2600__+MAX_llx_menu__, '/compta/bank/bankentries_list.php?leftmenu=bank', 'ListTransactions', 1, 'banks', '$user->rights->banque->lire', '', 0, 2, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && ($leftmenu=="bank" || $leftmenu=="checks" || $leftmenu=="withdraw")', __HANDLER__, 'left', 2604__+MAX_llx_menu__, 'accountancy', '', 2600__+MAX_llx_menu__, '/compta/bank/budget.php?leftmenu=bank', 'ListTransactionsByCategory', 1, 'banks', '$user->rights->banque->lire', '', 0, 3, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && ($leftmenu=="bank" || $leftmenu=="checks" || $leftmenu=="withdraw")', __HANDLER__, 'left', 2606__+MAX_llx_menu__, 'accountancy', '', 2600__+MAX_llx_menu__, '/compta/bank/transfer.php?leftmenu=bank', 'BankTransfers', 1, 'banks', '$user->rights->banque->transfer', '', 0, 5, __ENTITY__); -- Bank - Categories diff --git a/htdocs/core/menus/standard/auguria.lib.php b/htdocs/core/menus/standard/auguria.lib.php index 9119afc7696..ebd64b36a3c 100644 --- a/htdocs/core/menus/standard/auguria.lib.php +++ b/htdocs/core/menus/standard/auguria.lib.php @@ -339,7 +339,7 @@ function print_left_auguria_menu($db,$menu_array_before,$menu_array_after,&$tabM $numr = $db->num_rows($resql); $i = 0; - if ($numr > 0) $newmenu->add('/compta/bank/index.php',$langs->trans("BankAccounts"),0,$user->rights->banque->lire); + if ($numr > 0) $newmenu->add('/compta/bank/list.php',$langs->trans("BankAccounts"),0,$user->rights->banque->lire); while ($i < $numr) { @@ -347,7 +347,7 @@ function print_left_auguria_menu($db,$menu_array_before,$menu_array_after,&$tabM $newmenu->add('/compta/bank/card.php?id='.$objp->rowid,$objp->label,1,$user->rights->banque->lire); if ($objp->rappro && $objp->courant != Account::TYPE_CASH && empty($objp->clos)) // If not cash account and not closed and can be reconciliate { - $newmenu->add('/compta/bank/bankentries.php?id='.$objp->rowid,$langs->trans("Conciliate"),2,$user->rights->banque->consolidate); + $newmenu->add('/compta/bank/bankentries_list.php?id='.$objp->rowid,$langs->trans("Conciliate"),2,$user->rights->banque->consolidate); } $i++; } diff --git a/htdocs/core/menus/standard/auguria_menu.php b/htdocs/core/menus/standard/auguria_menu.php index bd762083d2f..55941fe7c10 100644 --- a/htdocs/core/menus/standard/auguria_menu.php +++ b/htdocs/core/menus/standard/auguria_menu.php @@ -163,13 +163,13 @@ class MenuManager $canonurl=preg_replace('/\?.*$/','',$val['url']); print '
    '; - + // Add font-awesome if ($val['level'] == 0 && $val['mainmenu'] == 'home') print ''; - + print $val['titre']; print ''."\n"; - + // Search submenu fot this mainmenu entry $tmpmainmenu=$val['mainmenu']; $tmpleftmenu='all'; @@ -183,7 +183,7 @@ class MenuManager //var_dump($canonnexturl); print '
      '."\n"; if (($canonrelurl != $canonnexturl && ! in_array($val['mainmenu'],array('tools'))) - || (strpos($canonrelurl,'/product/index.php') !== false || strpos($canonrelurl,'/compta/bank/index.php') !== false)) + || (strpos($canonrelurl,'/product/index.php') !== false || strpos($canonrelurl,'/compta/bank/list.php') !== false)) { // We add sub entry print str_pad('',1).'
    • '; // ui-btn to highlight on clic diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 013b6ea74ae..3af93cbcbf6 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -182,7 +182,7 @@ function print_eldy_menu($db,$atarget,$type_user,&$tabMenu,&$menu,$noout=0,$mode else $classname = 'class="tmenu"'; $idsel='accountancy'; - $menu->add('/accountancy/index.php?mainmenu=accountancy&leftmenu=', $langs->trans("Accountancy"), 0, $showmode, $atarget, "accountancy", '', 50, $id, $idsel, $classname); + $menu->add('/accountancy/index.php?mainmenu=accountancy&leftmenu=', $langs->trans("Accountancy"), 0, $showmode, $atarget, "accountancy", '', 52, $id, $idsel, $classname); } @@ -201,7 +201,7 @@ function print_eldy_menu($db,$atarget,$type_user,&$tabMenu,&$menu,$noout=0,$mode else $classname = 'class="tmenu"'; $idsel='bank'; - $menu->add('/compta/bank/index.php?mainmenu=bank&leftmenu=', $langs->trans("MenuBankCash"), 0, $showmode, $atarget, "bank", '', 60, $id, $idsel, $classname); + $menu->add('/compta/bank/list.php?mainmenu=bank&leftmenu=', $langs->trans("MenuBankCash"), 0, $showmode, $atarget, "bank", '', 60, $id, $idsel, $classname); } // Projects @@ -977,7 +977,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/accountancy/admin/defaultaccounts.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuDefaultAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50); if (! empty($conf->banque->enabled)) { - if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/compta/bank/index.php?mainmenu=accountancy&leftmenu=accountancy_admin&search_status=-1", $langs->trans("MenuBankAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_bank', 51); + if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/',$leftmenu)) $newmenu->add("/compta/bank/list.php?mainmenu=accountancy&leftmenu=accountancy_admin&search_status=-1", $langs->trans("MenuBankAccounts"),2, $user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_bank', 51); } if (! empty($conf->facture->enabled) || ! empty($conf->fournisseur->enabled)) { @@ -1146,11 +1146,11 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu // Bank-Caisse if (! empty($conf->banque->enabled)) { - $newmenu->add("/compta/bank/index.php?leftmenu=bank&mainmenu=bank",$langs->trans("MenuBankCash"),0,$user->rights->banque->lire, '', $mainmenu, 'bank'); + $newmenu->add("/compta/bank/list.php?leftmenu=bank&mainmenu=bank",$langs->trans("MenuBankCash"),0,$user->rights->banque->lire, '', $mainmenu, 'bank'); $newmenu->add("/compta/bank/card.php?action=create",$langs->trans("MenuNewFinancialAccount"),1,$user->rights->banque->configurer); - $newmenu->add("/compta/bank/index.php?leftmenu=bank&mainmenu=bank",$langs->trans("List"),1,$user->rights->banque->lire, '', $mainmenu, 'bank'); - $newmenu->add("/compta/bank/bankentries.php",$langs->trans("ListTransactions"),1,$user->rights->banque->lire); + $newmenu->add("/compta/bank/list.php?leftmenu=bank&mainmenu=bank",$langs->trans("List"),1,$user->rights->banque->lire, '', $mainmenu, 'bank'); + $newmenu->add("/compta/bank/bankentries_list.php",$langs->trans("ListTransactions"),1,$user->rights->banque->lire); $newmenu->add("/compta/bank/budget.php",$langs->trans("ListTransactionsByCategory"),1,$user->rights->banque->lire); $newmenu->add("/compta/bank/transfer.php",$langs->trans("MenuBankInternalTransfer"),1,$user->rights->banque->transfer); @@ -1498,7 +1498,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu $numr = $db->num_rows($resql); $i = 0; - if ($numr > 0) $newmenu->add('/compta/bank/index.php',$langs->trans("BankAccounts"),0,$user->rights->banque->lire); + if ($numr > 0) $newmenu->add('/compta/bank/list.php',$langs->trans("BankAccounts"),0,$user->rights->banque->lire); while ($i < $numr) { @@ -1506,7 +1506,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu $newmenu->add('/compta/bank/card.php?id='.$objp->rowid,$objp->label,1,$user->rights->banque->lire); if ($objp->rappro && $objp->courant != Account::TYPE_CASH && empty($objp->clos)) // If not cash account and not closed and can be reconciliate { - $newmenu->add('/compta/bank/bankentries.php?action=reconcile&contextpage=banktransactionlist-'.$objp->rowid.'&account='.$objp->rowid.'&id='.$objp->rowid.'&search_conciliated=0',$langs->trans("Conciliate"),2,$user->rights->banque->consolidate); + $newmenu->add('/compta/bank/bankentries_list.php?action=reconcile&contextpage=banktransactionlist-'.$objp->rowid.'&account='.$objp->rowid.'&id='.$objp->rowid.'&search_conciliated=0',$langs->trans("Conciliate"),2,$user->rights->banque->consolidate); } $i++; } diff --git a/htdocs/core/menus/standard/eldy_menu.php b/htdocs/core/menus/standard/eldy_menu.php index d8f90cb912f..51442d54e51 100644 --- a/htdocs/core/menus/standard/eldy_menu.php +++ b/htdocs/core/menus/standard/eldy_menu.php @@ -177,7 +177,7 @@ class MenuManager print $val['titre']; print ''."\n"; - + // Search submenu fot this mainmenu entry $tmpmainmenu=$val['mainmenu']; $tmpleftmenu='all'; @@ -193,7 +193,7 @@ class MenuManager //var_dump($canonnexturl); print '
        '."\n"; if (($canonrelurl != $canonnexturl && ! in_array($val['mainmenu'],array('tools'))) - || (strpos($canonrelurl,'/product/index.php') !== false || strpos($canonrelurl,'/compta/bank/index.php') !== false)) + || (strpos($canonrelurl,'/product/index.php') !== false || strpos($canonrelurl,'/compta/bank/list.php') !== false)) { // We add sub entry print str_pad('',1).'
      • '; // ui-btn to highlight on clic diff --git a/htdocs/core/menus/standard/empty.php b/htdocs/core/menus/standard/empty.php index dafc0486145..9de1ee345c2 100644 --- a/htdocs/core/menus/standard/empty.php +++ b/htdocs/core/menus/standard/empty.php @@ -199,7 +199,7 @@ class MenuManager //var_dump($canonnexturl); print '
          '."\n"; if (($canonrelurl != $canonnexturl && ! in_array($val['mainmenu'],array('tools'))) - || (strpos($canonrelurl,'/product/index.php') !== false || strpos($canonrelurl,'/compta/bank/index.php') !== false)) + || (strpos($canonrelurl,'/product/index.php') !== false || strpos($canonrelurl,'/compta/bank/list.php') !== false)) { // We add sub entry print str_pad('',1).'
        • '; // ui-btn to highlight on clic diff --git a/htdocs/core/modules/DolibarrModules.class.php b/htdocs/core/modules/DolibarrModules.class.php index bdf8effe23c..c42fabcc937 100644 --- a/htdocs/core/modules/DolibarrModules.class.php +++ b/htdocs/core/modules/DolibarrModules.class.php @@ -34,245 +34,245 @@ */ class DolibarrModules // Can not be abstract, because we need to instantiate it into unActivateModule to be able to disable a module whose files were removed. { - /** - * @var DoliDb Database handler - */ - public $db; + /** + * @var DoliDb Database handler + */ + public $db; - /** - * @var int Module unique ID - * @see https://wiki.dolibarr.org/index.php/List_of_modules_id - */ - public $numero; + /** + * @var int Module unique ID + * @see https://wiki.dolibarr.org/index.php/List_of_modules_id + */ + public $numero; - /** - * @var string Publisher name - * @since 4.0.0 - */ - public $editor_name; + /** + * @var string Publisher name + * @since 4.0.0 + */ + public $editor_name; - /** - * @var string URL of module at publisher site - * @since 4.0.0 - */ - public $editor_url; + /** + * @var string URL of module at publisher site + * @since 4.0.0 + */ + public $editor_url; - /** - * @var string Family - * @see familyinfo - * - * Native values: 'crm', 'financial', 'hr', 'projects', 'products', 'ecm', 'technic', 'other'. - * Use familyinfo to declare a custom value. - */ - public $family; + /** + * @var string Family + * @see familyinfo + * + * Native values: 'crm', 'financial', 'hr', 'projects', 'products', 'ecm', 'technic', 'other'. + * Use familyinfo to declare a custom value. + */ + public $family; - /** - * @var array Custom family informations - * @see family - * - * e.g.: - * array( - * 'myownfamily' => array( - * 'position' => '001', - * 'label' => $langs->trans("MyOwnFamily") - * ) - * ); - * - */ - public $familyinfo; + /** + * @var array Custom family informations + * @see family + * + * e.g.: + * array( + * 'myownfamily' => array( + * 'position' => '001', + * 'label' => $langs->trans("MyOwnFamily") + * ) + * ); + * + */ + public $familyinfo; - /** - * @var int Module position - * @since 3.9.0 - */ - public $module_position=500; + /** + * @var int Module position + * @since 3.9.0 + */ + public $module_position=500; - /** - * @var string Module name - * - * Only used if Module[ID]Name translation string is not found. - * - * You can use the following code to automatically derive it from your module's class name: - * preg_replace('/^mod/i', '', get_class($this)) - */ - public $name; + /** + * @var string Module name + * + * Only used if Module[ID]Name translation string is not found. + * + * You can use the following code to automatically derive it from your module's class name: + * preg_replace('/^mod/i', '', get_class($this)) + */ + public $name; - /** - * @var string[] Paths to create when module is activated - * - * e.g.: array('/mymodule/temp') - */ - public $dirs = array(); + /** + * @var string[] Paths to create when module is activated + * + * e.g.: array('/mymodule/temp') + */ + public $dirs = array(); - /** - * @var array Module boxes - */ - public $boxes = array(); + /** + * @var array Module boxes + */ + public $boxes = array(); - /** - * @var array Module constants - */ - public $const = array(); + /** + * @var array Module constants + */ + public $const = array(); - /** - * @var array Module cron jobs entries - */ - public $cronjobs = array(); + /** + * @var array Module cron jobs entries + */ + public $cronjobs = array(); - /** - * @var array Module access rights - */ - public $rights; + /** + * @var array Module access rights + */ + public $rights; - /** - * @var string Module access rights family - */ - public $rights_class; + /** + * @var string Module access rights family + */ + public $rights_class; - /** - * @var array Module menu entries - */ - public $menu = array(); + /** + * @var array Module menu entries + */ + public $menu = array(); - /** - * @var array Module parts - * array( - * // Set this to 1 if module has its own trigger directory (/mymodule/core/triggers) - * 'triggers' => 0, - * // Set this to 1 if module has its own login method directory (/mymodule/core/login) - * 'login' => 0, - * // Set this to 1 if module has its own substitution function file (/mymodule/core/substitutions) - * 'substitutions' => 0, - * // Set this to 1 if module has its own menus handler directory (/mymodule/core/menus) - * 'menus' => 0, - * // Set this to 1 if module has its own theme directory (/mymodule/theme) - * 'theme' => 0, - * // Set this to 1 if module overwrite template dir (/mymodule/core/tpl) - * 'tpl' => 0, - * // Set this to 1 if module has its own barcode directory (/mymodule/core/modules/barcode) - * 'barcode' => 0, - * // Set this to 1 if module has its own models directory (/mymodule/core/modules/xxx) - * 'models' => 0, - * // Set this to relative path of css file if module has its own css file - * 'css' => '/mymodule/css/mymodule.css.php', - * // Set this to relative path of js file if module must load a js on all pages - * 'js' => '/mymodule/js/mymodule.js', - * // Set here all hooks context managed by module - * 'hooks' => array('hookcontext1','hookcontext2'), - * // Set here all workflow context managed by module - * 'workflow' => array( - * 'WORKFLOW_MODULE1_YOURACTIONTYPE_MODULE2' = >array( - * 'enabled' => '! empty($conf->module1->enabled) && ! empty($conf->module2->enabled)', - * 'picto'=>'yourpicto@mymodule' - * ) - * ) - * ) - */ - public $module_parts = array(); + /** + * @var array Module parts + * array( + * // Set this to 1 if module has its own trigger directory (/mymodule/core/triggers) + * 'triggers' => 0, + * // Set this to 1 if module has its own login method directory (/mymodule/core/login) + * 'login' => 0, + * // Set this to 1 if module has its own substitution function file (/mymodule/core/substitutions) + * 'substitutions' => 0, + * // Set this to 1 if module has its own menus handler directory (/mymodule/core/menus) + * 'menus' => 0, + * // Set this to 1 if module has its own theme directory (/mymodule/theme) + * 'theme' => 0, + * // Set this to 1 if module overwrite template dir (/mymodule/core/tpl) + * 'tpl' => 0, + * // Set this to 1 if module has its own barcode directory (/mymodule/core/modules/barcode) + * 'barcode' => 0, + * // Set this to 1 if module has its own models directory (/mymodule/core/modules/xxx) + * 'models' => 0, + * // Set this to relative path of css file if module has its own css file + * 'css' => '/mymodule/css/mymodule.css.php', + * // Set this to relative path of js file if module must load a js on all pages + * 'js' => '/mymodule/js/mymodule.js', + * // Set here all hooks context managed by module + * 'hooks' => array('hookcontext1','hookcontext2'), + * // Set here all workflow context managed by module + * 'workflow' => array( + * 'WORKFLOW_MODULE1_YOURACTIONTYPE_MODULE2' = >array( + * 'enabled' => '! empty($conf->module1->enabled) && ! empty($conf->module2->enabled)', + * 'picto'=>'yourpicto@mymodule' + * ) + * ) + * ) + */ + public $module_parts = array(); - /** - * @var string Module documents ? - * @deprecated Seems unused anywhere - */ - public $docs; + /** + * @var string Module documents ? + * @deprecated Seems unused anywhere + */ + public $docs; - /** - * @var string ? - * @deprecated Seems unused anywhere - */ - public $dbversion = "-"; + /** + * @var string ? + * @deprecated Seems unused anywhere + */ + public $dbversion = "-"; - /** - * @var string Error message - */ - public $error; + /** + * @var string Error message + */ + public $error; - /** - * @var string Module version - * @see http://semver.org - * - * The following keywords can also be used: - * 'development' - * 'experimental' - * 'dolibarr': only for core modules that share its version - * 'dolibarr_deprecated': only for deprecated core modules - * - */ - public $version; + /** + * @var string Module version + * @see http://semver.org + * + * The following keywords can also be used: + * 'development' + * 'experimental' + * 'dolibarr': only for core modules that share its version + * 'dolibarr_deprecated': only for deprecated core modules + * + */ + public $version; - /** - * @var string Module description (short text) - * - * Only used if Module[ID]Desc translation string is not found. - */ - public $description; + /** + * @var string Module description (short text) + * + * Only used if Module[ID]Desc translation string is not found. + */ + public $description; - /** - * @var string Module description (long text) - * @since 4.0.0 - * - * HTML content supported. - */ - public $descriptionlong; + /** + * @var string Module description (long text) + * @since 4.0.0 + * + * HTML content supported. + */ + public $descriptionlong; - // For exports + // For exports - /** - * @var string Module export code - */ - public $export_code; + /** + * @var string Module export code + */ + public $export_code; - /** - * @var string Module export label - */ - public $export_label; + /** + * @var string Module export label + */ + public $export_label; - public $export_permission; - public $export_fields_array; - public $export_TypeFields_array; - public $export_entities_array; - public $export_special_array; // special or computed field - public $export_dependencies_array; - public $export_sql_start; - public $export_sql_end; - public $export_sql_order; + public $export_permission; + public $export_fields_array; + public $export_TypeFields_array; + public $export_entities_array; + public $export_special_array; // special or computed field + public $export_dependencies_array; + public $export_sql_start; + public $export_sql_end; + public $export_sql_order; - // For import + // For import - /** - * @var string Module import code - */ - public $import_code; + /** + * @var string Module import code + */ + public $import_code; - /** - * @var string Module import label - */ - public $import_label; + /** + * @var string Module import label + */ + public $import_label; - /** - * @var string Module constant name - */ - public $const_name; + /** + * @var string Module constant name + */ + public $const_name; - /** - * @var bool Module can't be disabled - */ - public $always_enabled; + /** + * @var bool Module can't be disabled + */ + public $always_enabled; - /** - * @var bool Module is enabled globally (Multicompany support) - */ - public $core_enabled; + /** + * @var bool Module is enabled globally (Multicompany support) + */ + public $core_enabled; - /** - * @var string Relative path to module style sheet - * @deprecated - * @see module_parts - */ - public $style_sheet = ''; + /** + * @var string Relative path to module style sheet + * @deprecated + * @see module_parts + */ + public $style_sheet = ''; /** * @var 0|1|2|3 Where to display the module in setup page @@ -322,24 +322,24 @@ class DolibarrModules // Can not be abstract, because we need to insta */ public $conflictwith; - /** - * @var string[] Module language files - */ - public $langfiles; + /** + * @var string[] Module language files + */ + public $langfiles; - /** - * @var string[] Array of warnings to show when we activate the module - * - * array('always'='text') or array('FR'='text') - */ - public $warnings_activation; + /** + * @var array Array of warnings to show when we activate the module + * + * array('always'='text') or array('FR'='text') + */ + public $warnings_activation; - /** - * @var string[] Array of warnings to show when we activate an external module - * - * array('always'='text') or array('FR'='text') - */ - public $warnings_activation_ext; + /** + * @var array Array of warnings to show when we activate an external module + * + * array('always'='text') or array('FR'='text') + */ + public $warnings_activation_ext; /** @@ -378,1072 +378,1072 @@ class DolibarrModules // Can not be abstract, because we need to insta // We need constructor into function unActivateModule into admin.lib.php - /** - * Enables a module. - * Inserts all informations into database - * + /** + * Enables a module. + * Inserts all informations into database + * * @param array $array_sql SQL requests to be executed when enabling module - * @param string $options String with options when disabling module: - * 'noboxes' = Do not insert boxes - * 'newboxdefonly' = For boxes, insert def of boxes only and not boxes activation - * - * @return int 1 if OK, 0 if KO - */ - function _init($array_sql, $options='') - { - global $conf; - $err=0; - - $this->db->begin(); - - // Insert activation module constant - if (! $err) $err+=$this->_active(); - - // Insert new pages for tabs (into llx_const) - if (! $err) $err+=$this->insert_tabs(); - - // Insert activation of module's parts - if (! $err) $err+=$this->insert_module_parts(); - - // Insert constant defined by modules (into llx_const) - if (! $err) $err+=$this->insert_const(); - - // Insert boxes def into llx_boxes_def and boxes setup (into llx_boxes) - if (! $err && ! preg_match('/noboxes/',$options)) $err+=$this->insert_boxes($options); - - // Insert cron job entries (entry in llx_cronjobs) - if (! $err) $err+=$this->insert_cronjobs(); - - // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user. - if (! $err) $err+=$this->insert_permissions(1, null, 1); - - // Insert specific menus entries into database - if (! $err) $err+=$this->insert_menus(); - - // Create module's directories - if (! $err) $err+=$this->create_dirs(); - - // Execute addons requests - $num=count($array_sql); - for ($i = 0; $i < $num; $i++) - { - if (! $err) - { - $val=$array_sql[$i]; - $sql=$val; - $ignoreerror=0; - if (is_array($val)) - { - $sql=$val['sql']; - $ignoreerror=$val['ignoreerror']; - } - // Add current entity id - $sql=str_replace('__ENTITY__', $conf->entity, $sql); - - dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror."", LOG_DEBUG); - $result=$this->db->query($sql, $ignoreerror); - if (! $result) - { - if (! $ignoreerror) - { - $this->error=$this->db->lasterror(); - $err++; - } - else - { - dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING); - } - } - } - } - - // Return code - if (! $err) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return 0; - } - } - - /** - * Disable function. Deletes the module constant and boxes from the database. - * - * @param string[] $array_sql SQL requests to be executed when module is disabled - * @param string $options Options when disabling module: - * 'newboxdefonly|noboxes' = We don't remove boxes. - * - * @return int 1 if OK, 0 if KO - */ - function _remove($array_sql, $options='') - { - $err=0; - - $this->db->begin(); - - // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const) - if (! $err) $err+=$this->_unactive(); - - // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const) - if (! $err) $err+=$this->delete_tabs(); - - // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const) - if (! $err) $err+=$this->delete_module_parts(); - - // Remove constants defined by modules - if (! $err) $err+=$this->delete_const(); - - // Remove list of module's available boxes (entry in llx_boxes) - if (! $err && ! preg_match('/(newboxdefonly|noboxes)/',$options)) $err+=$this->delete_boxes(); // We don't have to delete if option ask to keep boxes safe or ask to add new box def only - - // Remove list of module's cron job entries (entry in llx_cronjobs) - if (! $err) $err+=$this->delete_cronjobs(); - - // Remove module's permissions from list of available permissions (entries in llx_rights_def) - if (! $err) $err+=$this->delete_permissions(); - - // Remove module's menus (entries in llx_menu) - if (! $err) $err+=$this->delete_menus(); - - // Remove module's directories - if (! $err) $err+=$this->delete_dirs(); - - // Run complementary sql requests - $num=count($array_sql); - for ($i = 0; $i < $num; $i++) - { - if (! $err) - { - dol_syslog(get_class($this)."::_remove", LOG_DEBUG); - $result=$this->db->query($array_sql[$i]); - if (! $result) - { - $this->error=$this->db->error(); - $err++; - } - } - } - - // Return code - if (! $err) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return 0; - } - } - - - /** - * Gives the translated module name if translation exists in admin.lang or into language files of module. - * Otherwise return the module key name. - * - * @return string Translated module name - */ - function getName() - { - global $langs; - $langs->load("admin"); - - if ($langs->trans("Module".$this->numero."Name") != ("Module".$this->numero."Name")) - { - // If module name translation exists - return $langs->trans("Module".$this->numero."Name"); - } - else - { - // If module name translation using it's unique id does not exists, we try to use its name to find translation - if (is_array($this->langfiles)) - { - foreach($this->langfiles as $val) - { - if ($val) $langs->load($val); - } - } - - if ($langs->trans("Module".$this->name."Name") != ("Module".$this->name."Name")) - { - // If module name translation exists - return $langs->trans("Module".$this->name."Name"); - } - - // Last change with simple product label - return $langs->trans($this->name); - } - } - - - /** - * Gives the translated module description if translation exists in admin.lang or the default module description - * - * @return string Translated module description - */ - function getDesc() - { - global $langs; - $langs->load("admin"); - - if ($langs->trans("Module".$this->numero."Desc") != ("Module".$this->numero."Desc")) - { - // If module description translation exists - return $langs->trans("Module".$this->numero."Desc"); - } - else - { - // If module description translation does not exist using its unique id, we can use its name to find translation - if (is_array($this->langfiles)) - { - foreach($this->langfiles as $val) - { - if ($val) $langs->load($val); - } - } - return $langs->trans($this->description); - } - } - - /** - * Gives the long description of a module. First check README-la_LA.md then README.md - * If not markdown files found, it return translated value of the key ->descriptionlong. - * - * @return string Long description of a module from README.md of from property. - */ - function getDescLong() - { - global $langs; - $langs->load("admin"); - - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - - $pathoffile = $this->getDescLongReadmeFound(); - - if ($pathoffile) // Mostly for external modules - { - $content = file_get_contents($pathoffile); - - if ((float) DOL_VERSION >= 6.0) - { - @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php'; - $content = dolMd2Html($content, 'parsedown', - array( - 'doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1), - 'img/'=>dol_buildpath(strtolower($this->name).'/img/', 1), - 'images/'=>dol_buildpath(strtolower($this->name).'/imgages/', 1), - )); - } - else - { - $content = nl2br($content); - } - } - else // Mostly for internal modules - { - if (! empty($this->descriptionlong)) - { - if (is_array($this->langfiles)) - { - foreach($this->langfiles as $val) - { - if ($val) $langs->load($val); - } - } - - $content = $langs->trans($this->descriptionlong); - } - } - - return $content; - } - - /** - * Return path of file if a README file was found. - * - * @return string Path of file if a README file was found. - */ - function getDescLongReadmeFound() - { - $filefound= false; - - // Define path to file README.md. - // First check README-la_LA.md then README.md - $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0); - if (dol_is_file($pathoffile)) - { - $filefound = true; - } - if (! $filefound) - { - $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0); - if (dol_is_file($pathoffile)) - { - $filefound = true; - } - } - - return ($filefound?$pathoffile:''); - } - - - /** - * Gives the changelog. First check ChangeLog-la_LA.md then ChangeLog.md - * - * @return string Content of ChangeLog - */ - function getChangeLog() - { - global $langs; - $langs->load("admin"); - - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - - $filefound= false; - - // Define path to file README.md. - // First check README-la_LA.md then README.md - $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0); - if (dol_is_file($pathoffile)) - { - $filefound = true; - } - if (! $filefound) - { - $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0); - if (dol_is_file($pathoffile)) - { - $filefound = true; - } - } - - if ($filefound) // Mostly for external modules - { - $content = file_get_contents($pathoffile); - - if ((float) DOL_VERSION >= 6.0) - { - @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php'; - $content = dolMd2Html($content, 'parsedown', array('doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1))); - } - else - { - $content = nl2br($content); - } - } - - return $content; - } - - /** - * Gives the publisher name - * - * @return string Publisher name - */ - function getPublisher() - { - return $this->editor_name; - } - - /** - * Gives the publisher url - * - * @return string Publisher url - */ - function getPublisherUrl() - { - return $this->editor_url; - } - - /** - * Gives module version (translated if param $translated is on) - * For 'experimental' modules, gives 'experimental' translation - * For 'dolibarr' modules, gives Dolibarr version - * - * @param int $translated 1=Special version keys are translated, 0=Special version keys are not translated - * @return string Module version - */ - function getVersion($translated=1) - { - global $langs; - $langs->load("admin"); - - $ret=''; - - $newversion=preg_replace('/_deprecated/','',$this->version); - if ($newversion == 'experimental') $ret=($translated?$langs->trans("VersionExperimental"):$newversion); - elseif ($newversion == 'development') $ret=($translated?$langs->trans("VersionDevelopment"):$newversion); - elseif ($newversion == 'dolibarr') $ret=DOL_VERSION; - elseif ($newversion) $ret=$newversion; - else $ret=($translated?$langs->trans("VersionUnknown"):'unknown'); - - if (preg_match('/_deprecated/',$this->version)) $ret.=($translated?' ('.$langs->trans("Deprecated").')':$this->version); - return $ret; - } - - - /** - * Tells if module is core or external - * - * @return string 'core', 'external' or 'unknown' - */ - function isCoreOrExternalModule() - { - if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') return 'core'; - if (! empty($this->version) && ! in_array($this->version,array('experimental','development'))) return 'external'; - if (! empty($this->editor_name) || ! empty($this->editor_url)) return 'external'; - if ($this->numero >= 100000) return 'external'; - return 'unknown'; - } - - - /** - * Gives module related language files list - * - * @return string[] Language files list - */ - function getLangFilesArray() - { - return $this->langfiles; - } - - /** - * Gives translated label of an export dataset - * - * @param int $r Dataset index - * - * @return string Translated databaset label - */ - function getExportDatasetLabel($r) - { - global $langs; - - $langstring="ExportDataset_".$this->export_code[$r]; - if ($langs->trans($langstring) == $langstring) - { - // Translation not found - return $langs->trans($this->export_label[$r]); - } - else - { - // Translation found - return $langs->trans($langstring); - } - } - - - /** - * Gives translated label of an import dataset - * - * @param int $r Dataset index - * - * @return string Translated dataset label - */ - function getImportDatasetLabel($r) - { - global $langs; - - $langstring="ImportDataset_".$this->import_code[$r]; - //print "x".$langstring; - if ($langs->trans($langstring) == $langstring) - { - // Translation not found - return $langs->trans($this->import_label[$r]); - } - else - { - // Translation found - return $langs->trans($langstring); - } - } - - - /** - * Gives the last date of activation - * - * @return timestamp Date of last activation - */ - function getLastActivationDate() - { - global $conf; - - $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$conf->entity.")"; - - dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - else - { - $obj=$this->db->fetch_object($resql); - if ($obj) return $this->db->jdate($obj->tms); - } - - return ''; - } - - - /** - * Gives the last author of activation - * - * @return array Array array('authorid'=>Id of last activation user, 'lastactivationdate'=>Date of last activation) - */ - function getLastActivationInfo() - { - global $conf; - - $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$conf->entity.")"; - - dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - else - { - $obj=$this->db->fetch_object($resql); - $tmp=array(); - if ($obj->note) - { - $tmp=json_decode($obj->note, true); - } - if ($obj) return array('authorid'=>$tmp['authorid'], 'ip'=>$tmp['ip'], 'lastactivationdate'=>$this->db->jdate($obj->tms)); - } - - return array(); - } - - - /** - * Insert constants for module activation - * - * @return int Error count (0 if OK) - */ - function _active() - { - global $conf, $user; - - $err = 0; - - // Common module - $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$entity.")"; - - dol_syslog(get_class($this)."::_active", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - - $note=json_encode(array('authorid'=>(is_object($user)?$user->id:0), 'ip'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']))); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES"; - $sql.= " (".$this->db->encrypt($this->const_name,1); - $sql.= ", ".$this->db->encrypt('1',1); - $sql.= ", 0, ".$entity; - $sql.= ", '".$this->db->escape($note)."')"; - - dol_syslog(get_class($this)."::_active", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - - return $err; - } - - - /** - * Module deactivation - * - * @return int Error count (0 if OK) - */ - function _unactive() - { - global $conf; - - $err = 0; - - // Common module - $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity); - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql.= " AND entity IN (0, ".$entity.")"; - - dol_syslog(get_class($this)."::_unactive", LOG_DEBUG); - $this->db->query($sql); - - return $err; - } - - - /** - * Create tables and keys required by module. - * Files module.sql and module.key.sql with create table and create keys - * commands must be stored in directory reldir='/module/sql/' - * This function is called by this->init - * - * @param string $reldir Relative directory where to scan files - * @return int <=0 if KO, >0 if OK - */ - function _load_tables($reldir) - { - global $conf; - - $error=0; - $dirfound=0; - - if (empty($reldir)) return 1; - - include_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; - - $ok = 1; - foreach($conf->file->dol_document_root as $dirroot) - { - if ($ok) - { - $dir = $dirroot.$reldir; - $ok = 0; - - $handle=@opendir($dir); // Dir may not exists - if (is_resource($handle)) - { - $dirfound++; - - // Run llx_mytable.sql files, then llx_mytable_*.sql - $files = array(); - while (($file = readdir($handle))!==false) - { - $files[] = $file; - } - sort($files); - foreach ($files as $file) - { - if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'llx_' && substr($file,0,4) != 'data') - { - $result=run_sql($dir.$file,1,'',1); - if ($result <= 0) $error++; - } - } - - rewinddir($handle); - - // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql - $files = array(); - while (($file = readdir($handle))!==false) - { - $files[] = $file; - } - sort($files); - foreach ($files as $file) - { - if (preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'llx_' && substr($file,0,4) != 'data') - { - $result=run_sql($dir.$file,1,'',1); - if ($result <= 0) $error++; - } - } - - rewinddir($handle); - - // Run data_xxx.sql files (Must be done after llx_mytable.key.sql) - $files = array(); - while (($file = readdir($handle))!==false) - { - $files[] = $file; - } - sort($files); - foreach ($files as $file) - { - if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'data') - { - $result=run_sql($dir.$file,1,'',1); - if ($result <= 0) $error++; - } - } - - rewinddir($handle); - - // Run update_xxx.sql files - $files = array(); - while (($file = readdir($handle))!==false) - { - $files[] = $file; - } - sort($files); - foreach ($files as $file) - { - if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,6) == 'update') - { - $result=run_sql($dir.$file,1,'',1); - if ($result <= 0) $error++; - } - } - - closedir($handle); - } - - if ($error == 0) - { - $ok = 1; - } - } - } - - if (! $dirfound) dol_syslog("A module ask to load sql files into ".$reldir." but this directory was not found.", LOG_WARNING); - return $ok; - } - - - /** - * Adds boxes - * - * @param string $option Options when disabling module ('newboxdefonly'=insert only boxes definition) - * - * @return int Error count (0 if OK) - */ - function insert_boxes($option='') - { - require_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php'; - - global $conf; - - $err=0; - - if (is_array($this->boxes)) - { - $pos_name = InfoBox::getListOfPagesForBoxes(); - - foreach ($this->boxes as $key => $value) - { - $file = isset($this->boxes[$key]['file'])?$this->boxes[$key]['file']:''; - $note = isset($this->boxes[$key]['note'])?$this->boxes[$key]['note']:''; - $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton'])?$this->boxes[$key]['enabledbydefaulton']:'Home'; - - if (empty($file)) $file = isset($this->boxes[$key][1])?$this->boxes[$key][1]:''; // For backward compatibility - if (empty($note)) $note = isset($this->boxes[$key][2])?$this->boxes[$key][2]:''; // For backward compatibility - - // Search if boxes def already present - $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def"; - $sql.= " WHERE file = '".$this->db->escape($file)."'"; - $sql.= " AND entity = ".$conf->entity; - if ($note) $sql.=" AND note ='".$this->db->escape($note)."'"; - - dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - $obj = $this->db->fetch_object($result); - if ($obj->nb == 0) - { - $this->db->begin(); - - if (! $err) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)"; - $sql.= " VALUES ('".$this->db->escape($file)."', "; - $sql.= $conf->entity.", "; - $sql.= $note?"'".$this->db->escape($note)."'":"null"; - $sql.= ")"; - - dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - - } - if (! $err && ! preg_match('/newboxdefonly/',$option)) - { - $lastid=$this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def","rowid"); - - foreach ($pos_name as $key2 => $val2) - { - //print 'key2='.$key2.'-val2='.$val2."
          \n"; - if ($enabledbydefaulton && $val2 != $enabledbydefaulton) continue; // Not enabled by default onto this page. - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id,position,box_order,fk_user,entity)"; - $sql.= " VALUES (".$lastid.", ".$key2.", '0', 0, ".$conf->entity.")"; - - dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2."", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - } - } - - if (! $err) - { - $this->db->commit(); - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - } - } - // else box already registered into database - } - else - { - $this->error=$this->db->lasterror(); - $err++; - } - } - } - - return $err; - } - - - /** - * Removes boxes - * - * @return int Error count (0 if OK) - */ - function delete_boxes() - { - global $conf; - - $err=0; - - if (is_array($this->boxes)) - { - foreach ($this->boxes as $key => $value) - { - //$titre = $this->boxes[$key][0]; - $file = $this->boxes[$key]['file']; - //$note = $this->boxes[$key][2]; - - // TODO If the box is also included by another module and the other module is still on, we should not remove it. - // For the moment, we manage this with hard coded exception - //print "Remove box ".$file.'
          '; - if ($file == 'box_graph_product_distribution.php') - { - if (! empty($conf->produit->enabled) || ! empty($conf->service->enabled)) - { - dol_syslog("We discard disabling of module ".$file." because another module still active require it."); - continue; - } - } - - if (empty($file)) $file = isset($this->boxes[$key][1])?$this->boxes[$key][1]:''; // For backward compatibility - - if ($this->db->type == 'sqlite3') { - // sqlite doesn't support "USING" syntax. - // TODO: remove this dependency. - $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes "; - $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN ("; - $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid "; - $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def "; - $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') "; - $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; - } else { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes"; - $sql.= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def"; - $sql.= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid"; - $sql.= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'"; - $sql.= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; - } - - dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $err++; - } - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def"; - $sql.= " WHERE file = '".$this->db->escape($file)."'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $err++; - } - } - } - - return $err; - } - - /** - * Adds cronjobs - * - * @return int Error count (0 if OK) - */ - function insert_cronjobs() - { - require_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php'; - - global $conf; - - $err=0; - - if (is_array($this->cronjobs)) - { - foreach ($this->cronjobs as $key => $value) - { - $label = isset($this->cronjobs[$key]['label'])?$this->cronjobs[$key]['label']:''; - $jobtype = isset($this->cronjobs[$key]['jobtype'])?$this->cronjobs[$key]['jobtype']:''; - $class = isset($this->cronjobs[$key]['class'])?$this->cronjobs[$key]['class']:''; - $objectname = isset($this->cronjobs[$key]['objectname'])?$this->cronjobs[$key]['objectname']:''; - $method = isset($this->cronjobs[$key]['method'])?$this->cronjobs[$key]['method']:''; - $command = isset($this->cronjobs[$key]['command'])?$this->cronjobs[$key]['command']:''; - $parameters = isset($this->cronjobs[$key]['parameters'])?$this->cronjobs[$key]['parameters']:''; - $comment = isset($this->cronjobs[$key]['comment'])?$this->cronjobs[$key]['comment']:''; - $frequency = isset($this->cronjobs[$key]['frequency'])?$this->cronjobs[$key]['frequency']:''; - $unitfrequency = isset($this->cronjobs[$key]['unitfrequency'])?$this->cronjobs[$key]['unitfrequency']:''; - $status = isset($this->cronjobs[$key]['status'])?$this->cronjobs[$key]['status']:''; - $priority = isset($this->cronjobs[$key]['priority'])?$this->cronjobs[$key]['priority']:''; - $test = isset($this->cronjobs[$key]['test'])?$this->cronjobs[$key]['test']:''; // Line must be visible - - // Search if boxes def already present - $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."cronjob"; - $sql.= " WHERE module_name = '".$this->db->escape($this->rights_class)."'"; - if ($class) $sql.= " AND classesname = '".$this->db->escape($class)."'"; - if ($objectname) $sql.= " AND objectname = '".$this->db->escape($objectname)."'"; - if ($method) $sql.= " AND methodename = '".$this->db->escape($method)."'"; - if ($command) $sql.= " AND command = '".$this->db->escape($command)."'"; - $sql.= " AND entity = ".$conf->entity; - - $now=dol_now(); - - dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - $obj = $this->db->fetch_object($result); - if ($obj->nb == 0) - { - $this->db->begin(); - - if (! $err) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob (module_name, datec, datestart, label, jobtype, classesname, objectname, methodename, command, params, note,"; - if(is_int($frequency)){ $sql.= ' frequency,'; } - if(is_int($unitfrequency)){ $sql.= ' unitfrequency,'; } - if(is_int($priority)){ $sql.= ' priority,'; } - if(is_int($status)){ $sql.= ' status,'; } - $sql.= " entity, test)"; - $sql.= " VALUES ("; - $sql.= "'".$this->db->escape($this->rights_class)."', "; - $sql.= "'".$this->db->idate($now)."', "; - $sql.= "'".$this->db->idate($now)."', "; - $sql.= "'".$this->db->escape($label)."', "; - $sql.= "'".$this->db->escape($jobtype)."', "; - $sql.= ($class?"'".$this->db->escape($class)."'":"null").","; - $sql.= ($objectname?"'".$this->db->escape($objectname)."'":"null").","; - $sql.= ($method?"'".$this->db->escape($method)."'":"null").","; - $sql.= ($command?"'".$this->db->escape($command)."'":"null").","; - $sql.= ($parameters?"'".$this->db->escape($parameters)."'":"null").","; - $sql.= ($comment?"'".$this->db->escape($comment)."'":"null").","; - if(is_int($frequency)){ $sql.= "'".$this->db->escape($frequency)."', "; } - if(is_int($unitfrequency)){ $sql.= "'".$this->db->escape($unitfrequency)."', "; } - if(is_int($priority)) {$sql.= "'".$this->db->escape($priority)."', ";} - if(is_int($status)){ $sql.= "'".$this->db->escape($status)."', "; } - $sql.= $conf->entity.","; - $sql.= "'".$this->db->escape($test)."'"; - $sql.= ")"; - - dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) $err++; - - } - - if (! $err) - { - $this->db->commit(); - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - } - } - // else box already registered into database - } - else - { - $this->error=$this->db->lasterror(); - $err++; - } - } - } - - return $err; - } - - - /** - * Removes boxes - * - * @return int Error count (0 if OK) - */ - function delete_cronjobs() - { - global $conf; - - $err=0; - - if (is_array($this->cronjobs)) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob"; - $sql.= " WHERE module_name = '".$this->db->escape($this->rights_class)."'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $err++; - } - } - - return $err; - } - - /** - * Removes tabs - * - * @return int Error count (0 if OK) - */ - function delete_tabs() - { - global $conf; - - $err=0; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG); - if (! $this->db->query($sql)) - { - $this->error=$this->db->lasterror(); - $err++; - } - - return $err; - } - - /** - * Adds tabs - * - * @return int Error count (0 if ok) - */ + * @param string $options String with options when disabling module: + * 'noboxes' = Do not insert boxes + * 'newboxdefonly' = For boxes, insert def of boxes only and not boxes activation + * + * @return int 1 if OK, 0 if KO + */ + function _init($array_sql, $options='') + { + global $conf; + $err=0; + + $this->db->begin(); + + // Insert activation module constant + if (! $err) $err+=$this->_active(); + + // Insert new pages for tabs (into llx_const) + if (! $err) $err+=$this->insert_tabs(); + + // Insert activation of module's parts + if (! $err) $err+=$this->insert_module_parts(); + + // Insert constant defined by modules (into llx_const) + if (! $err && ! preg_match('/newboxdefonly/',$options)) $err+=$this->insert_const(); // Test on newboxdefonly to avoid to erase value during upgrade + + // Insert boxes def into llx_boxes_def and boxes setup (into llx_boxes) + if (! $err && ! preg_match('/noboxes/',$options)) $err+=$this->insert_boxes($options); + + // Insert cron job entries (entry in llx_cronjobs) + if (! $err) $err+=$this->insert_cronjobs(); + + // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user. + if (! $err) $err+=$this->insert_permissions(1, null, 1); + + // Insert specific menus entries into database + if (! $err) $err+=$this->insert_menus(); + + // Create module's directories + if (! $err) $err+=$this->create_dirs(); + + // Execute addons requests + $num=count($array_sql); + for ($i = 0; $i < $num; $i++) + { + if (! $err) + { + $val=$array_sql[$i]; + $sql=$val; + $ignoreerror=0; + if (is_array($val)) + { + $sql=$val['sql']; + $ignoreerror=$val['ignoreerror']; + } + // Add current entity id + $sql=str_replace('__ENTITY__', $conf->entity, $sql); + + dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror."", LOG_DEBUG); + $result=$this->db->query($sql, $ignoreerror); + if (! $result) + { + if (! $ignoreerror) + { + $this->error=$this->db->lasterror(); + $err++; + } + else + { + dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING); + } + } + } + } + + // Return code + if (! $err) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return 0; + } + } + + /** + * Disable function. Deletes the module constant and boxes from the database. + * + * @param string[] $array_sql SQL requests to be executed when module is disabled + * @param string $options Options when disabling module: + * 'newboxdefonly|noboxes' = We don't remove boxes. + * + * @return int 1 if OK, 0 if KO + */ + function _remove($array_sql, $options='') + { + $err=0; + + $this->db->begin(); + + // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const) + if (! $err) $err+=$this->_unactive(); + + // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const) + if (! $err) $err+=$this->delete_tabs(); + + // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const) + if (! $err) $err+=$this->delete_module_parts(); + + // Remove constants defined by modules + if (! $err) $err+=$this->delete_const(); + + // Remove list of module's available boxes (entry in llx_boxes) + if (! $err && ! preg_match('/(newboxdefonly|noboxes)/',$options)) $err+=$this->delete_boxes(); // We don't have to delete if option ask to keep boxes safe or ask to add new box def only + + // Remove list of module's cron job entries (entry in llx_cronjobs) + if (! $err) $err+=$this->delete_cronjobs(); + + // Remove module's permissions from list of available permissions (entries in llx_rights_def) + if (! $err) $err+=$this->delete_permissions(); + + // Remove module's menus (entries in llx_menu) + if (! $err) $err+=$this->delete_menus(); + + // Remove module's directories + if (! $err) $err+=$this->delete_dirs(); + + // Run complementary sql requests + $num=count($array_sql); + for ($i = 0; $i < $num; $i++) + { + if (! $err) + { + dol_syslog(get_class($this)."::_remove", LOG_DEBUG); + $result=$this->db->query($array_sql[$i]); + if (! $result) + { + $this->error=$this->db->error(); + $err++; + } + } + } + + // Return code + if (! $err) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return 0; + } + } + + + /** + * Gives the translated module name if translation exists in admin.lang or into language files of module. + * Otherwise return the module key name. + * + * @return string Translated module name + */ + function getName() + { + global $langs; + $langs->load("admin"); + + if ($langs->trans("Module".$this->numero."Name") != ("Module".$this->numero."Name")) + { + // If module name translation exists + return $langs->trans("Module".$this->numero."Name"); + } + else + { + // If module name translation using it's unique id does not exists, we try to use its name to find translation + if (is_array($this->langfiles)) + { + foreach($this->langfiles as $val) + { + if ($val) $langs->load($val); + } + } + + if ($langs->trans("Module".$this->name."Name") != ("Module".$this->name."Name")) + { + // If module name translation exists + return $langs->trans("Module".$this->name."Name"); + } + + // Last change with simple product label + return $langs->trans($this->name); + } + } + + + /** + * Gives the translated module description if translation exists in admin.lang or the default module description + * + * @return string Translated module description + */ + function getDesc() + { + global $langs; + $langs->load("admin"); + + if ($langs->trans("Module".$this->numero."Desc") != ("Module".$this->numero."Desc")) + { + // If module description translation exists + return $langs->trans("Module".$this->numero."Desc"); + } + else + { + // If module description translation does not exist using its unique id, we can use its name to find translation + if (is_array($this->langfiles)) + { + foreach($this->langfiles as $val) + { + if ($val) $langs->load($val); + } + } + return $langs->trans($this->description); + } + } + + /** + * Gives the long description of a module. First check README-la_LA.md then README.md + * If not markdown files found, it return translated value of the key ->descriptionlong. + * + * @return string Long description of a module from README.md of from property. + */ + function getDescLong() + { + global $langs; + $langs->load("admin"); + + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + $pathoffile = $this->getDescLongReadmeFound(); + + if ($pathoffile) // Mostly for external modules + { + $content = file_get_contents($pathoffile); + + if ((float) DOL_VERSION >= 6.0) + { + @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php'; + $content = dolMd2Html($content, 'parsedown', + array( + 'doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1), + 'img/'=>dol_buildpath(strtolower($this->name).'/img/', 1), + 'images/'=>dol_buildpath(strtolower($this->name).'/imgages/', 1), + )); + } + else + { + $content = nl2br($content); + } + } + else // Mostly for internal modules + { + if (! empty($this->descriptionlong)) + { + if (is_array($this->langfiles)) + { + foreach($this->langfiles as $val) + { + if ($val) $langs->load($val); + } + } + + $content = $langs->trans($this->descriptionlong); + } + } + + return $content; + } + + /** + * Return path of file if a README file was found. + * + * @return string Path of file if a README file was found. + */ + function getDescLongReadmeFound() + { + $filefound= false; + + // Define path to file README.md. + // First check README-la_LA.md then README.md + $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0); + if (dol_is_file($pathoffile)) + { + $filefound = true; + } + if (! $filefound) + { + $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0); + if (dol_is_file($pathoffile)) + { + $filefound = true; + } + } + + return ($filefound?$pathoffile:''); + } + + + /** + * Gives the changelog. First check ChangeLog-la_LA.md then ChangeLog.md + * + * @return string Content of ChangeLog + */ + function getChangeLog() + { + global $langs; + $langs->load("admin"); + + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + $filefound= false; + + // Define path to file README.md. + // First check README-la_LA.md then README.md + $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0); + if (dol_is_file($pathoffile)) + { + $filefound = true; + } + if (! $filefound) + { + $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0); + if (dol_is_file($pathoffile)) + { + $filefound = true; + } + } + + if ($filefound) // Mostly for external modules + { + $content = file_get_contents($pathoffile); + + if ((float) DOL_VERSION >= 6.0) + { + @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php'; + $content = dolMd2Html($content, 'parsedown', array('doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1))); + } + else + { + $content = nl2br($content); + } + } + + return $content; + } + + /** + * Gives the publisher name + * + * @return string Publisher name + */ + function getPublisher() + { + return $this->editor_name; + } + + /** + * Gives the publisher url + * + * @return string Publisher url + */ + function getPublisherUrl() + { + return $this->editor_url; + } + + /** + * Gives module version (translated if param $translated is on) + * For 'experimental' modules, gives 'experimental' translation + * For 'dolibarr' modules, gives Dolibarr version + * + * @param int $translated 1=Special version keys are translated, 0=Special version keys are not translated + * @return string Module version + */ + function getVersion($translated=1) + { + global $langs; + $langs->load("admin"); + + $ret=''; + + $newversion=preg_replace('/_deprecated/','',$this->version); + if ($newversion == 'experimental') $ret=($translated?$langs->trans("VersionExperimental"):$newversion); + elseif ($newversion == 'development') $ret=($translated?$langs->trans("VersionDevelopment"):$newversion); + elseif ($newversion == 'dolibarr') $ret=DOL_VERSION; + elseif ($newversion) $ret=$newversion; + else $ret=($translated?$langs->trans("VersionUnknown"):'unknown'); + + if (preg_match('/_deprecated/',$this->version)) $ret.=($translated?' ('.$langs->trans("Deprecated").')':$this->version); + return $ret; + } + + + /** + * Tells if module is core or external + * + * @return string 'core', 'external' or 'unknown' + */ + function isCoreOrExternalModule() + { + if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') return 'core'; + if (! empty($this->version) && ! in_array($this->version,array('experimental','development'))) return 'external'; + if (! empty($this->editor_name) || ! empty($this->editor_url)) return 'external'; + if ($this->numero >= 100000) return 'external'; + return 'unknown'; + } + + + /** + * Gives module related language files list + * + * @return string[] Language files list + */ + function getLangFilesArray() + { + return $this->langfiles; + } + + /** + * Gives translated label of an export dataset + * + * @param int $r Dataset index + * + * @return string Translated databaset label + */ + function getExportDatasetLabel($r) + { + global $langs; + + $langstring="ExportDataset_".$this->export_code[$r]; + if ($langs->trans($langstring) == $langstring) + { + // Translation not found + return $langs->trans($this->export_label[$r]); + } + else + { + // Translation found + return $langs->trans($langstring); + } + } + + + /** + * Gives translated label of an import dataset + * + * @param int $r Dataset index + * + * @return string Translated dataset label + */ + function getImportDatasetLabel($r) + { + global $langs; + + $langstring="ImportDataset_".$this->import_code[$r]; + //print "x".$langstring; + if ($langs->trans($langstring) == $langstring) + { + // Translation not found + return $langs->trans($this->import_label[$r]); + } + else + { + // Translation found + return $langs->trans($langstring); + } + } + + + /** + * Gives the last date of activation + * + * @return timestamp Date of last activation + */ + function getLastActivationDate() + { + global $conf; + + $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql.= " AND entity IN (0, ".$conf->entity.")"; + + dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + else + { + $obj=$this->db->fetch_object($resql); + if ($obj) return $this->db->jdate($obj->tms); + } + + return ''; + } + + + /** + * Gives the last author of activation + * + * @return array Array array('authorid'=>Id of last activation user, 'lastactivationdate'=>Date of last activation) + */ + function getLastActivationInfo() + { + global $conf; + + $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql.= " AND entity IN (0, ".$conf->entity.")"; + + dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + else + { + $obj=$this->db->fetch_object($resql); + $tmp=array(); + if ($obj->note) + { + $tmp=json_decode($obj->note, true); + } + if ($obj) return array('authorid'=>$tmp['authorid'], 'ip'=>$tmp['ip'], 'lastactivationdate'=>$this->db->jdate($obj->tms)); + } + + return array(); + } + + + /** + * Insert constants for module activation + * + * @return int Error count (0 if OK) + */ + function _active() + { + global $conf, $user; + + $err = 0; + + // Common module + $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql.= " AND entity IN (0, ".$entity.")"; + + dol_syslog(get_class($this)."::_active", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + + $note=json_encode(array('authorid'=>(is_object($user)?$user->id:0), 'ip'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']))); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES"; + $sql.= " (".$this->db->encrypt($this->const_name,1); + $sql.= ", ".$this->db->encrypt('1',1); + $sql.= ", 0, ".$entity; + $sql.= ", '".$this->db->escape($note)."')"; + + dol_syslog(get_class($this)."::_active", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + + return $err; + } + + + /** + * Module deactivation + * + * @return int Error count (0 if OK) + */ + function _unactive() + { + global $conf; + + $err = 0; + + // Common module + $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql.= " AND entity IN (0, ".$entity.")"; + + dol_syslog(get_class($this)."::_unactive", LOG_DEBUG); + $this->db->query($sql); + + return $err; + } + + + /** + * Create tables and keys required by module. + * Files module.sql and module.key.sql with create table and create keys + * commands must be stored in directory reldir='/module/sql/' + * This function is called by this->init + * + * @param string $reldir Relative directory where to scan files + * @return int <=0 if KO, >0 if OK + */ + function _load_tables($reldir) + { + global $conf; + + $error=0; + $dirfound=0; + + if (empty($reldir)) return 1; + + include_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; + + $ok = 1; + foreach($conf->file->dol_document_root as $dirroot) + { + if ($ok) + { + $dir = $dirroot.$reldir; + $ok = 0; + + $handle=@opendir($dir); // Dir may not exists + if (is_resource($handle)) + { + $dirfound++; + + // Run llx_mytable.sql files, then llx_mytable_*.sql + $files = array(); + while (($file = readdir($handle))!==false) + { + $files[] = $file; + } + sort($files); + foreach ($files as $file) + { + if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'llx_' && substr($file,0,4) != 'data') + { + $result=run_sql($dir.$file,1,'',1); + if ($result <= 0) $error++; + } + } + + rewinddir($handle); + + // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql + $files = array(); + while (($file = readdir($handle))!==false) + { + $files[] = $file; + } + sort($files); + foreach ($files as $file) + { + if (preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'llx_' && substr($file,0,4) != 'data') + { + $result=run_sql($dir.$file,1,'',1); + if ($result <= 0) $error++; + } + } + + rewinddir($handle); + + // Run data_xxx.sql files (Must be done after llx_mytable.key.sql) + $files = array(); + while (($file = readdir($handle))!==false) + { + $files[] = $file; + } + sort($files); + foreach ($files as $file) + { + if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,4) == 'data') + { + $result=run_sql($dir.$file,1,'',1); + if ($result <= 0) $error++; + } + } + + rewinddir($handle); + + // Run update_xxx.sql files + $files = array(); + while (($file = readdir($handle))!==false) + { + $files[] = $file; + } + sort($files); + foreach ($files as $file) + { + if (preg_match('/\.sql$/i',$file) && ! preg_match('/\.key\.sql$/i',$file) && substr($file,0,6) == 'update') + { + $result=run_sql($dir.$file,1,'',1); + if ($result <= 0) $error++; + } + } + + closedir($handle); + } + + if ($error == 0) + { + $ok = 1; + } + } + } + + if (! $dirfound) dol_syslog("A module ask to load sql files into ".$reldir." but this directory was not found.", LOG_WARNING); + return $ok; + } + + + /** + * Adds boxes + * + * @param string $option Options when disabling module ('newboxdefonly'=insert only boxes definition) + * + * @return int Error count (0 if OK) + */ + function insert_boxes($option='') + { + require_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php'; + + global $conf; + + $err=0; + + if (is_array($this->boxes)) + { + $pos_name = InfoBox::getListOfPagesForBoxes(); + + foreach ($this->boxes as $key => $value) + { + $file = isset($this->boxes[$key]['file'])?$this->boxes[$key]['file']:''; + $note = isset($this->boxes[$key]['note'])?$this->boxes[$key]['note']:''; + $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton'])?$this->boxes[$key]['enabledbydefaulton']:'Home'; + + if (empty($file)) $file = isset($this->boxes[$key][1])?$this->boxes[$key][1]:''; // For backward compatibility + if (empty($note)) $note = isset($this->boxes[$key][2])?$this->boxes[$key][2]:''; // For backward compatibility + + // Search if boxes def already present + $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def"; + $sql.= " WHERE file = '".$this->db->escape($file)."'"; + $sql.= " AND entity = ".$conf->entity; + if ($note) $sql.=" AND note ='".$this->db->escape($note)."'"; + + dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $obj = $this->db->fetch_object($result); + if ($obj->nb == 0) + { + $this->db->begin(); + + if (! $err) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)"; + $sql.= " VALUES ('".$this->db->escape($file)."', "; + $sql.= $conf->entity.", "; + $sql.= $note?"'".$this->db->escape($note)."'":"null"; + $sql.= ")"; + + dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + + } + if (! $err && ! preg_match('/newboxdefonly/',$option)) + { + $lastid=$this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def","rowid"); + + foreach ($pos_name as $key2 => $val2) + { + //print 'key2='.$key2.'-val2='.$val2."
          \n"; + if ($enabledbydefaulton && $val2 != $enabledbydefaulton) continue; // Not enabled by default onto this page. + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id,position,box_order,fk_user,entity)"; + $sql.= " VALUES (".$lastid.", ".$key2.", '0', 0, ".$conf->entity.")"; + + dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2."", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + } + } + + if (! $err) + { + $this->db->commit(); + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + } + } + // else box already registered into database + } + else + { + $this->error=$this->db->lasterror(); + $err++; + } + } + } + + return $err; + } + + + /** + * Removes boxes + * + * @return int Error count (0 if OK) + */ + function delete_boxes() + { + global $conf; + + $err=0; + + if (is_array($this->boxes)) + { + foreach ($this->boxes as $key => $value) + { + //$titre = $this->boxes[$key][0]; + $file = $this->boxes[$key]['file']; + //$note = $this->boxes[$key][2]; + + // TODO If the box is also included by another module and the other module is still on, we should not remove it. + // For the moment, we manage this with hard coded exception + //print "Remove box ".$file.'
          '; + if ($file == 'box_graph_product_distribution.php') + { + if (! empty($conf->produit->enabled) || ! empty($conf->service->enabled)) + { + dol_syslog("We discard disabling of module ".$file." because another module still active require it."); + continue; + } + } + + if (empty($file)) $file = isset($this->boxes[$key][1])?$this->boxes[$key][1]:''; // For backward compatibility + + if ($this->db->type == 'sqlite3') { + // sqlite doesn't support "USING" syntax. + // TODO: remove this dependency. + $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes "; + $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN ("; + $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid "; + $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def "; + $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') "; + $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; + } else { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes"; + $sql.= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def"; + $sql.= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid"; + $sql.= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'"; + $sql.= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity; + } + + dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $err++; + } + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def"; + $sql.= " WHERE file = '".$this->db->escape($file)."'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $err++; + } + } + } + + return $err; + } + + /** + * Adds cronjobs + * + * @return int Error count (0 if OK) + */ + function insert_cronjobs() + { + require_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php'; + + global $conf; + + $err=0; + + if (is_array($this->cronjobs)) + { + foreach ($this->cronjobs as $key => $value) + { + $label = isset($this->cronjobs[$key]['label'])?$this->cronjobs[$key]['label']:''; + $jobtype = isset($this->cronjobs[$key]['jobtype'])?$this->cronjobs[$key]['jobtype']:''; + $class = isset($this->cronjobs[$key]['class'])?$this->cronjobs[$key]['class']:''; + $objectname = isset($this->cronjobs[$key]['objectname'])?$this->cronjobs[$key]['objectname']:''; + $method = isset($this->cronjobs[$key]['method'])?$this->cronjobs[$key]['method']:''; + $command = isset($this->cronjobs[$key]['command'])?$this->cronjobs[$key]['command']:''; + $parameters = isset($this->cronjobs[$key]['parameters'])?$this->cronjobs[$key]['parameters']:''; + $comment = isset($this->cronjobs[$key]['comment'])?$this->cronjobs[$key]['comment']:''; + $frequency = isset($this->cronjobs[$key]['frequency'])?$this->cronjobs[$key]['frequency']:''; + $unitfrequency = isset($this->cronjobs[$key]['unitfrequency'])?$this->cronjobs[$key]['unitfrequency']:''; + $status = isset($this->cronjobs[$key]['status'])?$this->cronjobs[$key]['status']:''; + $priority = isset($this->cronjobs[$key]['priority'])?$this->cronjobs[$key]['priority']:''; + $test = isset($this->cronjobs[$key]['test'])?$this->cronjobs[$key]['test']:''; // Line must be visible + + // Search if boxes def already present + $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."cronjob"; + $sql.= " WHERE module_name = '".$this->db->escape($this->rights_class)."'"; + if ($class) $sql.= " AND classesname = '".$this->db->escape($class)."'"; + if ($objectname) $sql.= " AND objectname = '".$this->db->escape($objectname)."'"; + if ($method) $sql.= " AND methodename = '".$this->db->escape($method)."'"; + if ($command) $sql.= " AND command = '".$this->db->escape($command)."'"; + $sql.= " AND entity = ".$conf->entity; + + $now=dol_now(); + + dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $obj = $this->db->fetch_object($result); + if ($obj->nb == 0) + { + $this->db->begin(); + + if (! $err) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob (module_name, datec, datestart, label, jobtype, classesname, objectname, methodename, command, params, note,"; + if(is_int($frequency)){ $sql.= ' frequency,'; } + if(is_int($unitfrequency)){ $sql.= ' unitfrequency,'; } + if(is_int($priority)){ $sql.= ' priority,'; } + if(is_int($status)){ $sql.= ' status,'; } + $sql.= " entity, test)"; + $sql.= " VALUES ("; + $sql.= "'".$this->db->escape($this->rights_class)."', "; + $sql.= "'".$this->db->idate($now)."', "; + $sql.= "'".$this->db->idate($now)."', "; + $sql.= "'".$this->db->escape($label)."', "; + $sql.= "'".$this->db->escape($jobtype)."', "; + $sql.= ($class?"'".$this->db->escape($class)."'":"null").","; + $sql.= ($objectname?"'".$this->db->escape($objectname)."'":"null").","; + $sql.= ($method?"'".$this->db->escape($method)."'":"null").","; + $sql.= ($command?"'".$this->db->escape($command)."'":"null").","; + $sql.= ($parameters?"'".$this->db->escape($parameters)."'":"null").","; + $sql.= ($comment?"'".$this->db->escape($comment)."'":"null").","; + if(is_int($frequency)){ $sql.= "'".$this->db->escape($frequency)."', "; } + if(is_int($unitfrequency)){ $sql.= "'".$this->db->escape($unitfrequency)."', "; } + if(is_int($priority)) {$sql.= "'".$this->db->escape($priority)."', ";} + if(is_int($status)){ $sql.= "'".$this->db->escape($status)."', "; } + $sql.= $conf->entity.","; + $sql.= "'".$this->db->escape($test)."'"; + $sql.= ")"; + + dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) $err++; + + } + + if (! $err) + { + $this->db->commit(); + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + } + } + // else box already registered into database + } + else + { + $this->error=$this->db->lasterror(); + $err++; + } + } + } + + return $err; + } + + + /** + * Removes boxes + * + * @return int Error count (0 if OK) + */ + function delete_cronjobs() + { + global $conf; + + $err=0; + + if (is_array($this->cronjobs)) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob"; + $sql.= " WHERE module_name = '".$this->db->escape($this->rights_class)."'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $err++; + } + } + + return $err; + } + + /** + * Removes tabs + * + * @return int Error count (0 if OK) + */ + function delete_tabs() + { + global $conf; + + $err=0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG); + if (! $this->db->query($sql)) + { + $this->error=$this->db->lasterror(); + $err++; + } + + return $err; + } + + /** + * Adds tabs + * + * @return int Error count (0 if ok) + */ function insert_tabs() { global $conf; @@ -1505,642 +1505,642 @@ class DolibarrModules // Can not be abstract, because we need to insta return $err; } - /** - * Adds constants - * - * @return int Error count (0 if OK) - */ - function insert_const() - { - global $conf; - - $err=0; - - if (empty($this->const)) return 0; - - foreach ($this->const as $key => $value) - { - $name = $this->const[$key][0]; - $type = $this->const[$key][1]; - $val = $this->const[$key][2]; - $note = isset($this->const[$key][3])?$this->const[$key][3]:''; - $visible = isset($this->const[$key][4])?$this->const[$key][4]:0; - $entity = (! empty($this->const[$key][5]) && $this->const[$key][5]!='current')?0:$conf->entity; - - // Clean - if (empty($visible)) $visible='0'; - if (empty($val) && $val != '0') $val=''; - - $sql = "SELECT count(*)"; - $sql.= " FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'"; - $sql.= " AND entity = ".$entity; - - $result=$this->db->query($sql); - if ($result) - { - $row = $this->db->fetch_row($result); - - if ($row[0] == 0) // If not found - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)"; - $sql.= " VALUES ("; - $sql.= $this->db->encrypt($name,1); - $sql.= ",'".$type."'"; - $sql.= ",".(($val != '')?$this->db->encrypt($val,1):"''"); - $sql.= ",".($note?"'".$this->db->escape($note)."'":"null"); - $sql.= ",'".$visible."'"; - $sql.= ",".$entity; - $sql.= ")"; - - - dol_syslog(get_class($this)."::insert_const", LOG_DEBUG); - if (! $this->db->query($sql) ) - { - $err++; - } - } - else - { - dol_syslog(get_class($this)."::insert_const constant '".$name."' already exists", LOG_WARNING); - } - } - else - { - $err++; - } - } - - return $err; - } - - /** - * Removes constants tagged 'deleteonunactive' - * - * @return int <0 if KO, 0 if OK - */ - function delete_const() - { - global $conf; - - $err=0; - - if (empty($this->const)) return 0; - - foreach ($this->const as $key => $value) - { - $name = $this->const[$key][0]; - $deleteonunactive = (! empty($this->const[$key][6]))?1:0; - - if ($deleteonunactive) - { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; - $sql.= " AND entity in (0, ".$conf->entity.")"; - dol_syslog(get_class($this)."::delete_const", LOG_DEBUG); - if (! $this->db->query($sql)) - { - $this->error=$this->db->lasterror(); - $err++; - } - } - } - - return $err; - } - - /** - * Adds access rights - * - * @param int $reinitadminperms If 1, we also grant them to all admin users - * @param int $force_entity Force current entity - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int Error count (0 if OK) - */ - function insert_permissions($reinitadminperms=0, $force_entity=null, $notrigger=0) - { - global $conf,$user; - - $err=0; - $entity=(! empty($force_entity) ? $force_entity : $conf->entity); - - // Test if module is activated - $sql_del = "SELECT ".$this->db->decrypt('value')." as value"; - $sql_del.= " FROM ".MAIN_DB_PREFIX."const"; - $sql_del.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; - $sql_del.= " AND entity IN (0,".$entity.")"; - - dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG); - $resql=$this->db->query($sql_del); - - if ($resql) - { - $obj=$this->db->fetch_object($resql); - if ($obj !== null && ! empty($obj->value) && ! empty($this->rights)) - { - // If the module is active - foreach ($this->rights as $key => $value) - { - $r_id = $this->rights[$key][0]; - $r_desc = $this->rights[$key][1]; - $r_type = isset($this->rights[$key][2])?$this->rights[$key][2]:''; - $r_def = $this->rights[$key][3]; - $r_perms = $this->rights[$key][4]; - $r_subperms = isset($this->rights[$key][5])?$this->rights[$key][5]:''; - $r_modul = $this->rights_class; - - if (empty($r_type)) $r_type='w'; - - // Search if perm already present - $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def"; - $sql.= " WHERE id = ".$r_id." AND entity = ".$entity; - $resqlselect=$this->db->query($sql); - - $obj = $this->db->fetch_object($resqlselect); - if ($obj->nb == 0) - { - if (dol_strlen($r_perms) ) - { - if (dol_strlen($r_subperms) ) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def"; - $sql.= " (id, entity, libelle, module, type, bydefault, perms, subperms)"; - $sql.= " VALUES "; - $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."','".$r_subperms."')"; - } - else - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def"; - $sql.= " (id, entity, libelle, module, type, bydefault, perms)"; - $sql.= " VALUES "; - $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."')"; - } - } - else - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def "; - $sql .= " (id, entity, libelle, module, type, bydefault)"; - $sql .= " VALUES "; - $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.")"; - } - - $resqlinsert=$this->db->query($sql,1); - - if (! $resqlinsert) - { - if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") - { - $this->error=$this->db->lasterror(); - $err++; - break; - } - else dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO); - - } - - $this->db->free($resqlinsert); - } - - $this->db->free($resqlselect); - - // If we want to init permissions on admin users - if ($reinitadminperms) - { - if (! class_exists('User')) { - require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; - } - $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1"; - dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG); - $resqlseladmin=$this->db->query($sql,1); - if ($resqlseladmin) - { - $num=$this->db->num_rows($resqlseladmin); - $i=0; - while ($i < $num) - { - $obj2=$this->db->fetch_object($resqlseladmin); - dol_syslog(get_class($this)."::insert_permissions Add permission to user id=".$obj2->rowid); - $tmpuser=new User($this->db); - $tmpuser->fetch($obj2->rowid); - if (!empty($tmpuser->id)) { - $tmpuser->addrights($r_id, '', '', 0, 1); - } - $i++; - } - if (! empty($user->admin)) // Reload permission for current user if defined - { - // We reload permissions - $user->clearrights(); - $user->getrights(); - } - } - else dol_print_error($this->db); - } - } - } - $this->db->free($resql); - } - else - { - $this->error=$this->db->lasterror(); - $err++; - } - - return $err; - } - - - /** - * Removes access rights - * - * @return int Error count (0 if OK) - */ - function delete_permissions() - { - global $conf; - - $err=0; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def"; - $sql.= " WHERE module = '".$this->db->escape($this->rights_class)."'"; - $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG); - if (! $this->db->query($sql)) - { - $this->error=$this->db->lasterror(); - $err++; - } - - return $err; - } - - - /** - * Adds menu entries - * - * @return int Error count (0 if OK) - */ - function insert_menus() - { - global $user; - - if (! is_array($this->menu) || empty($this->menu)) return 0; - - require_once DOL_DOCUMENT_ROOT . '/core/class/menubase.class.php'; - - $err=0; - - $this->db->begin(); - - foreach ($this->menu as $key => $value) - { - $menu = new Menubase($this->db); - $menu->menu_handler='all'; - $menu->module=$this->rights_class; - if (! $this->menu[$key]['fk_menu']) - { - $menu->fk_menu=0; - } - else - { - $foundparent=0; - $fk_parent=$this->menu[$key]['fk_menu']; - if (preg_match('/^r=/',$fk_parent)) // old deprecated method - { - $fk_parent=str_replace('r=','',$fk_parent); - if (isset($this->menu[$fk_parent]['rowid'])) - { - $menu->fk_menu=$this->menu[$fk_parent]['rowid']; - $foundparent=1; - } - } - elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/',$fk_parent,$reg)) - { - $menu->fk_menu=-1; - $menu->fk_mainmenu=$reg[1]; - $menu->fk_leftmenu=$reg[2]; - $foundparent=1; - } - elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/',$fk_parent,$reg)) - { - $menu->fk_menu=-1; - $menu->fk_mainmenu=$reg[1]; - $menu->fk_leftmenu=''; - $foundparent=1; - } - if (! $foundparent) - { - $this->error="ErrorBadDefinitionOfMenuArrayInModuleDescriptor"; - dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR); - $err++; - } - } - $menu->type=$this->menu[$key]['type']; - $menu->mainmenu=isset($this->menu[$key]['mainmenu'])?$this->menu[$key]['mainmenu']:(isset($menu->fk_mainmenu)?$menu->fk_mainmenu:''); - $menu->leftmenu=isset($this->menu[$key]['leftmenu'])?$this->menu[$key]['leftmenu']:''; - $menu->titre=$this->menu[$key]['titre']; - $menu->url=$this->menu[$key]['url']; - $menu->langs=$this->menu[$key]['langs']; - $menu->position=$this->menu[$key]['position']; - $menu->perms=$this->menu[$key]['perms']; - $menu->target=$this->menu[$key]['target']; - $menu->user=$this->menu[$key]['user']; - $menu->enabled=isset($this->menu[$key]['enabled'])?$this->menu[$key]['enabled']:0; - $menu->position=$this->menu[$key]['position']; - - if (! $err) - { - $result=$menu->create($user); // Save menu entry into table llx_menu - if ($result > 0) - { - $this->menu[$key]['rowid']=$result; - } - else - { - $this->error=$menu->error; - dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR); - $err++; - break; - } - } - } - - if (! $err) - { - $this->db->commit(); - } - else - { - dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR); - $this->db->rollback(); - } - - return $err; - } - - - /** - * Removes menu entries - * - * @return int Error count (0 if OK) - */ - function delete_menus() - { - global $conf; - - $err=0; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu"; - $sql.= " WHERE module = '".$this->db->escape($this->rights_class)."'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - $err++; - } - - return $err; - } - - /** - * Creates directories - * - * @return int Error count (0 if OK) - */ - function create_dirs() - { - global $langs, $conf; - - $err=0; - - if (isset($this->dirs) && is_array($this->dirs)) - { - foreach ($this->dirs as $key => $value) - { - $addtodatabase=0; - - if (! is_array($value)) $dir=$value; // Default simple mode - else { - $constname = $this->const_name."_DIR_"; - $dir = $this->dirs[$key][1]; - $addtodatabase = empty($this->dirs[$key][2])?'':$this->dirs[$key][2]; // Create constante in llx_const - $subname = empty($this->dirs[$key][3])?'':strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output) - $forcename = empty($this->dirs[$key][4])?'':strtoupper($this->dirs[$key][4]); // Change the module name if different - - if (! empty($forcename)) $constname = 'MAIN_MODULE_'.$forcename."_DIR_"; - if (! empty($subname)) $constname = $constname.$subname."_"; - - $name = $constname.strtoupper($this->dirs[$key][0]); - } - - // Define directory full path ($dir must start with "/") - if (empty($conf->global->MAIN_MODULE_MULTICOMPANY) || $conf->entity == 1) $fulldir = DOL_DATA_ROOT.$dir; - else $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir; - // Create dir if it does not exists - if (! empty($fulldir) && ! file_exists($fulldir)) - { - if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) - { - $this->error = $langs->trans("ErrorCanNotCreateDir",$fulldir); - dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR); - $err++; - } - } - - // Define the constant in database if requested (not the default mode) - if (! empty($addtodatabase)) - { - $result = $this->insert_dirs($name, $dir); - if ($result) $err++; - } - } - } - - return $err; - } - - - /** - * Adds directories definitions - * - * @param string $name Name - * @param string $dir Directory - * - * @return int Error count (0 if OK) - */ - function insert_dirs($name,$dir) - { - global $conf; - - $err=0; - - $sql = "SELECT count(*)"; - $sql.= " FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG); - $result=$this->db->query($sql); - if ($result) - { - $row = $this->db->fetch_row($result); - - if ($row[0] == 0) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)"; - $sql.= " VALUES (".$this->db->encrypt($name,1).",'chaine',".$this->db->encrypt($dir,1).",'Directory for module ".$this->name."','0',".$conf->entity.")"; - - dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG); - $this->db->query($sql); - } - } - else - { - $this->error=$this->db->lasterror(); - $err++; - } - - return $err; - } - - - /** - * Removes directories - * - * @return int Error count (0 if OK) - */ - function delete_dirs() - { - global $conf; - - $err=0; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'"; - $sql.= " AND entity = ".$conf->entity; - - dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG); - if (! $this->db->query($sql)) - { - $this->error=$this->db->lasterror(); - $err++; - } - - return $err; - } - - /** - * Adds generic parts - * - * @return int Error count (0 if OK) - */ - function insert_module_parts() - { - global $conf; - - $error=0; - - if (is_array($this->module_parts) && ! empty($this->module_parts)) - { - foreach($this->module_parts as $key => $value) - { - if (is_array($value) && count($value) == 0) continue; // Discard empty arrays - - $entity=$conf->entity; // Reset the current entity - $newvalue = $value; - - // Serialize array parameters - if (is_array($value)) - { - // Can defined other parameters - if (is_array($value['data']) && ! empty($value['data'])) - { - $newvalue = json_encode($value['data']); - if (isset($value['entity'])) $entity = $value['entity']; - } - else if (isset($value['data']) && !is_array($value['data'])) - { - $newvalue = $value['data']; - if (isset($value['entity'])) $entity = $value['entity']; - } - else - { - $newvalue = json_encode($value); - } - } - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."const ("; - $sql.= "name"; - $sql.= ", type"; - $sql.= ", value"; - $sql.= ", note"; - $sql.= ", visible"; - $sql.= ", entity"; - $sql.= ")"; - $sql.= " VALUES ("; - $sql.= $this->db->encrypt($this->const_name."_".strtoupper($key), 1); - $sql.= ", 'chaine'"; - $sql.= ", ".$this->db->encrypt($newvalue, 1); - $sql.= ", null"; - $sql.= ", '0'"; - $sql.= ", ".$entity; - $sql.= ")"; - - dol_syslog(get_class($this)."::insert_const_".$key."", LOG_DEBUG); - $resql=$this->db->query($sql,1); - if (! $resql) - { - if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $error++; - $this->error=$this->db->lasterror(); - } - else - { - dol_syslog(get_class($this)."::insert_const_".$key." Record already exists.", LOG_WARNING); - } - } - } - } - return $error; - } - - /** - * Removes generic parts - * - * @return int Error count (0 if OK) - */ - function delete_module_parts() - { - global $conf; - - $err=0; - $entity=$conf->entity; - - if (is_array($this->module_parts) && ! empty($this->module_parts)) - { - foreach($this->module_parts as $key => $value) - { - // If entity is defined - if (is_array($value) && isset($value['entity'])) $entity = $value['entity']; - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; - $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'"; - $sql.= " AND entity = ".$entity; - - dol_syslog(get_class($this)."::delete_const_".$key."", LOG_DEBUG); - if (! $this->db->query($sql)) - { - $this->error=$this->db->lasterror(); - $err++; - } - } - } - return $err; - } + /** + * Adds constants + * + * @return int Error count (0 if OK) + */ + function insert_const() + { + global $conf; + + $err=0; + + if (empty($this->const)) return 0; + + foreach ($this->const as $key => $value) + { + $name = $this->const[$key][0]; + $type = $this->const[$key][1]; + $val = $this->const[$key][2]; + $note = isset($this->const[$key][3])?$this->const[$key][3]:''; + $visible = isset($this->const[$key][4])?$this->const[$key][4]:0; + $entity = (! empty($this->const[$key][5]) && $this->const[$key][5]!='current')?0:$conf->entity; + + // Clean + if (empty($visible)) $visible='0'; + if (empty($val) && $val != '0') $val=''; + + $sql = "SELECT count(*)"; + $sql.= " FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'"; + $sql.= " AND entity = ".$entity; + + $result=$this->db->query($sql); + if ($result) + { + $row = $this->db->fetch_row($result); + + if ($row[0] == 0) // If not found + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)"; + $sql.= " VALUES ("; + $sql.= $this->db->encrypt($name,1); + $sql.= ",'".$type."'"; + $sql.= ",".(($val != '')?$this->db->encrypt($val,1):"''"); + $sql.= ",".($note?"'".$this->db->escape($note)."'":"null"); + $sql.= ",'".$visible."'"; + $sql.= ",".$entity; + $sql.= ")"; + + + dol_syslog(get_class($this)."::insert_const", LOG_DEBUG); + if (! $this->db->query($sql) ) + { + $err++; + } + } + else + { + dol_syslog(get_class($this)."::insert_const constant '".$name."' already exists", LOG_WARNING); + } + } + else + { + $err++; + } + } + + return $err; + } + + /** + * Removes constants tagged 'deleteonunactive' + * + * @return int <0 if KO, 0 if OK + */ + function delete_const() + { + global $conf; + + $err=0; + + if (empty($this->const)) return 0; + + foreach ($this->const as $key => $value) + { + $name = $this->const[$key][0]; + $deleteonunactive = (! empty($this->const[$key][6]))?1:0; + + if ($deleteonunactive) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; + $sql.= " AND entity in (0, ".$conf->entity.")"; + dol_syslog(get_class($this)."::delete_const", LOG_DEBUG); + if (! $this->db->query($sql)) + { + $this->error=$this->db->lasterror(); + $err++; + } + } + } + + return $err; + } + + /** + * Adds access rights + * + * @param int $reinitadminperms If 1, we also grant them to all admin users + * @param int $force_entity Force current entity + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int Error count (0 if OK) + */ + function insert_permissions($reinitadminperms=0, $force_entity=null, $notrigger=0) + { + global $conf,$user; + + $err=0; + $entity=(! empty($force_entity) ? $force_entity : $conf->entity); + + // Test if module is activated + $sql_del = "SELECT ".$this->db->decrypt('value')." as value"; + $sql_del.= " FROM ".MAIN_DB_PREFIX."const"; + $sql_del.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'"; + $sql_del.= " AND entity IN (0,".$entity.")"; + + dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG); + $resql=$this->db->query($sql_del); + + if ($resql) + { + $obj=$this->db->fetch_object($resql); + if ($obj !== null && ! empty($obj->value) && ! empty($this->rights)) + { + // If the module is active + foreach ($this->rights as $key => $value) + { + $r_id = $this->rights[$key][0]; + $r_desc = $this->rights[$key][1]; + $r_type = isset($this->rights[$key][2])?$this->rights[$key][2]:''; + $r_def = $this->rights[$key][3]; + $r_perms = $this->rights[$key][4]; + $r_subperms = isset($this->rights[$key][5])?$this->rights[$key][5]:''; + $r_modul = $this->rights_class; + + if (empty($r_type)) $r_type='w'; + + // Search if perm already present + $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def"; + $sql.= " WHERE id = ".$r_id." AND entity = ".$entity; + $resqlselect=$this->db->query($sql); + + $obj = $this->db->fetch_object($resqlselect); + if ($obj->nb == 0) + { + if (dol_strlen($r_perms) ) + { + if (dol_strlen($r_subperms) ) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def"; + $sql.= " (id, entity, libelle, module, type, bydefault, perms, subperms)"; + $sql.= " VALUES "; + $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."','".$r_subperms."')"; + } + else + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def"; + $sql.= " (id, entity, libelle, module, type, bydefault, perms)"; + $sql.= " VALUES "; + $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."')"; + } + } + else + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def "; + $sql .= " (id, entity, libelle, module, type, bydefault)"; + $sql .= " VALUES "; + $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.")"; + } + + $resqlinsert=$this->db->query($sql,1); + + if (! $resqlinsert) + { + if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") + { + $this->error=$this->db->lasterror(); + $err++; + break; + } + else dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO); + + } + + $this->db->free($resqlinsert); + } + + $this->db->free($resqlselect); + + // If we want to init permissions on admin users + if ($reinitadminperms) + { + if (! class_exists('User')) { + require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; + } + $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1"; + dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG); + $resqlseladmin=$this->db->query($sql,1); + if ($resqlseladmin) + { + $num=$this->db->num_rows($resqlseladmin); + $i=0; + while ($i < $num) + { + $obj2=$this->db->fetch_object($resqlseladmin); + dol_syslog(get_class($this)."::insert_permissions Add permission to user id=".$obj2->rowid); + $tmpuser=new User($this->db); + $tmpuser->fetch($obj2->rowid); + if (!empty($tmpuser->id)) { + $tmpuser->addrights($r_id, '', '', 0, 1); + } + $i++; + } + if (! empty($user->admin)) // Reload permission for current user if defined + { + // We reload permissions + $user->clearrights(); + $user->getrights(); + } + } + else dol_print_error($this->db); + } + } + } + $this->db->free($resql); + } + else + { + $this->error=$this->db->lasterror(); + $err++; + } + + return $err; + } + + + /** + * Removes access rights + * + * @return int Error count (0 if OK) + */ + function delete_permissions() + { + global $conf; + + $err=0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def"; + $sql.= " WHERE module = '".$this->db->escape($this->rights_class)."'"; + $sql.= " AND entity = ".$conf->entity; + dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG); + if (! $this->db->query($sql)) + { + $this->error=$this->db->lasterror(); + $err++; + } + + return $err; + } + + + /** + * Adds menu entries + * + * @return int Error count (0 if OK) + */ + function insert_menus() + { + global $user; + + if (! is_array($this->menu) || empty($this->menu)) return 0; + + require_once DOL_DOCUMENT_ROOT . '/core/class/menubase.class.php'; + + $err=0; + + $this->db->begin(); + + foreach ($this->menu as $key => $value) + { + $menu = new Menubase($this->db); + $menu->menu_handler='all'; + $menu->module=$this->rights_class; + if (! $this->menu[$key]['fk_menu']) + { + $menu->fk_menu=0; + } + else + { + $foundparent=0; + $fk_parent=$this->menu[$key]['fk_menu']; + if (preg_match('/^r=/',$fk_parent)) // old deprecated method + { + $fk_parent=str_replace('r=','',$fk_parent); + if (isset($this->menu[$fk_parent]['rowid'])) + { + $menu->fk_menu=$this->menu[$fk_parent]['rowid']; + $foundparent=1; + } + } + elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/',$fk_parent,$reg)) + { + $menu->fk_menu=-1; + $menu->fk_mainmenu=$reg[1]; + $menu->fk_leftmenu=$reg[2]; + $foundparent=1; + } + elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/',$fk_parent,$reg)) + { + $menu->fk_menu=-1; + $menu->fk_mainmenu=$reg[1]; + $menu->fk_leftmenu=''; + $foundparent=1; + } + if (! $foundparent) + { + $this->error="ErrorBadDefinitionOfMenuArrayInModuleDescriptor"; + dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR); + $err++; + } + } + $menu->type=$this->menu[$key]['type']; + $menu->mainmenu=isset($this->menu[$key]['mainmenu'])?$this->menu[$key]['mainmenu']:(isset($menu->fk_mainmenu)?$menu->fk_mainmenu:''); + $menu->leftmenu=isset($this->menu[$key]['leftmenu'])?$this->menu[$key]['leftmenu']:''; + $menu->titre=$this->menu[$key]['titre']; + $menu->url=$this->menu[$key]['url']; + $menu->langs=$this->menu[$key]['langs']; + $menu->position=$this->menu[$key]['position']; + $menu->perms=$this->menu[$key]['perms']; + $menu->target=$this->menu[$key]['target']; + $menu->user=$this->menu[$key]['user']; + $menu->enabled=isset($this->menu[$key]['enabled'])?$this->menu[$key]['enabled']:0; + $menu->position=$this->menu[$key]['position']; + + if (! $err) + { + $result=$menu->create($user); // Save menu entry into table llx_menu + if ($result > 0) + { + $this->menu[$key]['rowid']=$result; + } + else + { + $this->error=$menu->error; + dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR); + $err++; + break; + } + } + } + + if (! $err) + { + $this->db->commit(); + } + else + { + dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR); + $this->db->rollback(); + } + + return $err; + } + + + /** + * Removes menu entries + * + * @return int Error count (0 if OK) + */ + function delete_menus() + { + global $conf; + + $err=0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu"; + $sql.= " WHERE module = '".$this->db->escape($this->rights_class)."'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $err++; + } + + return $err; + } + + /** + * Creates directories + * + * @return int Error count (0 if OK) + */ + function create_dirs() + { + global $langs, $conf; + + $err=0; + + if (isset($this->dirs) && is_array($this->dirs)) + { + foreach ($this->dirs as $key => $value) + { + $addtodatabase=0; + + if (! is_array($value)) $dir=$value; // Default simple mode + else { + $constname = $this->const_name."_DIR_"; + $dir = $this->dirs[$key][1]; + $addtodatabase = empty($this->dirs[$key][2])?'':$this->dirs[$key][2]; // Create constante in llx_const + $subname = empty($this->dirs[$key][3])?'':strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output) + $forcename = empty($this->dirs[$key][4])?'':strtoupper($this->dirs[$key][4]); // Change the module name if different + + if (! empty($forcename)) $constname = 'MAIN_MODULE_'.$forcename."_DIR_"; + if (! empty($subname)) $constname = $constname.$subname."_"; + + $name = $constname.strtoupper($this->dirs[$key][0]); + } + + // Define directory full path ($dir must start with "/") + if (empty($conf->global->MAIN_MODULE_MULTICOMPANY) || $conf->entity == 1) $fulldir = DOL_DATA_ROOT.$dir; + else $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir; + // Create dir if it does not exists + if (! empty($fulldir) && ! file_exists($fulldir)) + { + if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) + { + $this->error = $langs->trans("ErrorCanNotCreateDir",$fulldir); + dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR); + $err++; + } + } + + // Define the constant in database if requested (not the default mode) + if (! empty($addtodatabase)) + { + $result = $this->insert_dirs($name, $dir); + if ($result) $err++; + } + } + } + + return $err; + } + + + /** + * Adds directories definitions + * + * @param string $name Name + * @param string $dir Directory + * + * @return int Error count (0 if OK) + */ + function insert_dirs($name,$dir) + { + global $conf; + + $err=0; + + $sql = "SELECT count(*)"; + $sql.= " FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $row = $this->db->fetch_row($result); + + if ($row[0] == 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)"; + $sql.= " VALUES (".$this->db->encrypt($name,1).",'chaine',".$this->db->encrypt($dir,1).",'Directory for module ".$this->name."','0',".$conf->entity.")"; + + dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG); + $this->db->query($sql); + } + } + else + { + $this->error=$this->db->lasterror(); + $err++; + } + + return $err; + } + + + /** + * Removes directories + * + * @return int Error count (0 if OK) + */ + function delete_dirs() + { + global $conf; + + $err=0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'"; + $sql.= " AND entity = ".$conf->entity; + + dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG); + if (! $this->db->query($sql)) + { + $this->error=$this->db->lasterror(); + $err++; + } + + return $err; + } + + /** + * Adds generic parts + * + * @return int Error count (0 if OK) + */ + function insert_module_parts() + { + global $conf; + + $error=0; + + if (is_array($this->module_parts) && ! empty($this->module_parts)) + { + foreach($this->module_parts as $key => $value) + { + if (is_array($value) && count($value) == 0) continue; // Discard empty arrays + + $entity=$conf->entity; // Reset the current entity + $newvalue = $value; + + // Serialize array parameters + if (is_array($value)) + { + // Can defined other parameters + if (is_array($value['data']) && ! empty($value['data'])) + { + $newvalue = json_encode($value['data']); + if (isset($value['entity'])) $entity = $value['entity']; + } + else if (isset($value['data']) && !is_array($value['data'])) + { + $newvalue = $value['data']; + if (isset($value['entity'])) $entity = $value['entity']; + } + else + { + $newvalue = json_encode($value); + } + } + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."const ("; + $sql.= "name"; + $sql.= ", type"; + $sql.= ", value"; + $sql.= ", note"; + $sql.= ", visible"; + $sql.= ", entity"; + $sql.= ")"; + $sql.= " VALUES ("; + $sql.= $this->db->encrypt($this->const_name."_".strtoupper($key), 1); + $sql.= ", 'chaine'"; + $sql.= ", ".$this->db->encrypt($newvalue, 1); + $sql.= ", null"; + $sql.= ", '0'"; + $sql.= ", ".$entity; + $sql.= ")"; + + dol_syslog(get_class($this)."::insert_const_".$key."", LOG_DEBUG); + $resql=$this->db->query($sql,1); + if (! $resql) + { + if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + $error++; + $this->error=$this->db->lasterror(); + } + else + { + dol_syslog(get_class($this)."::insert_const_".$key." Record already exists.", LOG_WARNING); + } + } + } + } + return $error; + } + + /** + * Removes generic parts + * + * @return int Error count (0 if OK) + */ + function delete_module_parts() + { + global $conf; + + $err=0; + $entity=$conf->entity; + + if (is_array($this->module_parts) && ! empty($this->module_parts)) + { + foreach($this->module_parts as $key => $value) + { + // If entity is defined + if (is_array($value) && isset($value['entity'])) $entity = $value['entity']; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."const"; + $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'"; + $sql.= " AND entity = ".$entity; + + dol_syslog(get_class($this)."::delete_const_".$key."", LOG_DEBUG); + if (! $this->db->query($sql)) + { + $this->error=$this->db->lasterror(); + $err++; + } + } + } + return $err; + } /** * Function called when module is enabled. @@ -2148,8 +2148,8 @@ class DolibarrModules // Can not be abstract, because we need to insta * It also creates data directories * * @param string $options Options when enabling module ('', 'newboxdefonly', 'noboxes') - * 'noboxes' = Do not insert boxes - * 'newboxdefonly' = For boxes, insert def of boxes only and not boxes activation + * 'noboxes' = Do not insert boxes + * 'newboxdefonly' = For boxes, insert def of boxes only and not boxes activation * @return int 1 if OK, 0 if KO */ public function init($options = '') diff --git a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php index e5a22c62867..f5ab606f404 100644 --- a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php @@ -140,7 +140,7 @@ class pdf_einstein extends ModelePDFCommandes } else { - $this->posxtva=112; + $this->posxtva=110; $this->posxup=126; $this->posxqty=145; } @@ -431,8 +431,8 @@ class pdf_einstein extends ModelePDFCommandes if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) { $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails); - $pdf->SetXY($this->posxtva, $curY); - $pdf->MultiCell($this->posxup-$this->posxtva-0.8, 3, $vat_rate, 0, 'R'); + $pdf->SetXY($this->posxtva-5, $curY); + $pdf->MultiCell($this->posxup-$this->posxtva+4, 3, $vat_rate, 0, 'R'); } // Unit price before discount diff --git a/htdocs/core/modules/dons/html_cerfafr.modules.php b/htdocs/core/modules/dons/html_cerfafr.modules.php index 24027375528..0f7f2aa2c36 100644 --- a/htdocs/core/modules/dons/html_cerfafr.modules.php +++ b/htdocs/core/modules/dons/html_cerfafr.modules.php @@ -35,22 +35,22 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; */ class html_cerfafr extends ModeleDon { - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - function __construct($db) - { - global $conf,$langs; + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + function __construct($db) + { + global $conf,$langs; - $this->db = $db; - $this->name = "cerfafr"; - $this->description = $langs->trans('DonationsReceiptModel').' - fr_FR - Cerfa 11580*03'; + $this->db = $db; + $this->name = "cerfafr"; + $this->description = $langs->trans('DonationsReceiptModel').' - fr_FR - Cerfa 11580*03'; - // Dimension page for size A4 - $this->type = 'html'; - } + // Dimension page for size A4 + $this->type = 'html'; + } /** @@ -64,16 +64,16 @@ class html_cerfafr extends ModeleDon } - /** - * Write the object to document file to disk - * - * @param Don $don Donation object - * @param Translate $outputlangs Lang object for output language + /** + * Write the object to document file to disk + * + * @param Don $don Donation object + * @param Translate $outputlangs Lang object for output language * @param string $currency Currency code - * @return int >0 if OK, <0 if KO - */ - function write_file($don,$outputlangs,$currency='') - { + * @return int >0 if OK, <0 if KO + */ + function write_file($don,$outputlangs,$currency='') + { global $user,$conf,$langs,$mysoc; $now=dol_now(); @@ -91,13 +91,13 @@ class html_cerfafr extends ModeleDon $currency = !empty($currency) ? $currency : $conf->currency; if (! empty($conf->don->dir_output)) - { + { // Definition of the object don (for upward compatibility) - if (! is_object($don)) - { - $don = new Don($this->db); - $ret=$don->fetch($id); - $id=$don->id; + if (! is_object($don)) + { + $don = new Don($this->db); + $ret=$don->fetch($id); + $id=$don->id; } // Definition of $dir and $file @@ -113,99 +113,99 @@ class html_cerfafr extends ModeleDon $file = $dir . "/" . $donref . ".html"; } - if (! file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { - $this->error=$langs->trans("ErrorCanNotCreateDir",$dir); - return -1; - } - } + if (! file_exists($dir)) + { + if (dol_mkdir($dir) < 0) + { + $this->error=$langs->trans("ErrorCanNotCreateDir",$dir); + return -1; + } + } - if (file_exists($dir)) - { - $formclass = new Form($this->db); + if (file_exists($dir)) + { + $formclass = new Form($this->db); - // This is not the proper way to do it but $formclass->form_modes_reglement - // prints the translation instead of returning it - if ($don->modepaiementid) - { - $formclass->load_cache_types_paiements(); - $paymentmode = $formclass->cache_types_paiements[$don->modepaiementid]['label']; - } - else $paymentmode = ''; + // This is not the proper way to do it but $formclass->form_modes_reglement + // prints the translation instead of returning it + if ($don->modepaiementid) + { + $formclass->load_cache_types_paiements(); + $paymentmode = $formclass->cache_types_paiements[$don->modepaiementid]['label']; + } + else $paymentmode = ''; if ($don->modepaiementid==7){ - $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; + $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; } else if ($don->modepaiementid==4){ - $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; + $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; } - else if ($don->modepaiementid==2 OR $don->modepaiementid==3 OR $don->modepaiementid==6){ - $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; + else if ($don->modepaiementid==2 || $don->modepaiementid==3 || $don->modepaiementid==6){ + $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; } else { - $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; + $ModePaiement = ' Remise d\'espèces Chèque Virement, prélèvement, carte bancaire'; } /* if (empty($don->societe)) { - $CodeDon = ' 200 du CGI 238 bis du CGI 885-0 V bis A du CGI'; + $CodeDon = ' 200 du CGI 238 bis du CGI 885-0 V bis A du CGI'; } else { - $CodeDon = ' 200 du CGI 238 bis du CGI 885-0 V bis A du CGI'; + $CodeDon = ' 200 du CGI 238 bis du CGI 885-0 V bis A du CGI'; } */ - // Define contents - $donmodel=DOL_DOCUMENT_ROOT ."/core/modules/dons/html_cerfafr.html"; - $form = implode('', file($donmodel)); - $form = str_replace('__REF__',$don->id,$form); - $form = str_replace('__DATE__',dol_print_date($don->date,'day',false,$outputlangs),$form); - //$form = str_replace('__IP__',$user->ip,$form); // TODO $user->ip not exist - $form = str_replace('__AMOUNT__',$don->amount,$form); + // Define contents + $donmodel=DOL_DOCUMENT_ROOT ."/core/modules/dons/html_cerfafr.html"; + $form = implode('', file($donmodel)); + $form = str_replace('__REF__',$don->id,$form); + $form = str_replace('__DATE__',dol_print_date($don->date,'day',false,$outputlangs),$form); + //$form = str_replace('__IP__',$user->ip,$form); // TODO $user->ip not exist + $form = str_replace('__AMOUNT__',$don->amount,$form); $form = str_replace('__AMOUNTLETTERS__',chiffre_en_lettre($don->amount),$form); - $form = str_replace('__CURRENCY__',$outputlangs->transnoentitiesnoconv("Currency".$currency),$form); - $form = str_replace('__CURRENCYCODE__',$conf->currency,$form); - $form = str_replace('__MAIN_INFO_SOCIETE_NOM__',$mysoc->name,$form); - $form = str_replace('__MAIN_INFO_SOCIETE_ADDRESS__',$mysoc->address,$form); - $form = str_replace('__MAIN_INFO_SOCIETE_ZIP__',$mysoc->zip,$form); - $form = str_replace('__MAIN_INFO_SOCIETE_TOWN__',$mysoc->town,$form); + $form = str_replace('__CURRENCY__',$outputlangs->transnoentitiesnoconv("Currency".$currency),$form); + $form = str_replace('__CURRENCYCODE__',$conf->currency,$form); + $form = str_replace('__MAIN_INFO_SOCIETE_NOM__',$mysoc->name,$form); + $form = str_replace('__MAIN_INFO_SOCIETE_ADDRESS__',$mysoc->address,$form); + $form = str_replace('__MAIN_INFO_SOCIETE_ZIP__',$mysoc->zip,$form); + $form = str_replace('__MAIN_INFO_SOCIETE_TOWN__',$mysoc->town,$form); $form = str_replace('__MAIN_INFO_SOCIETE_OBJECT__',$mysoc->object,$form); $form = str_replace('__DONATOR_FIRSTNAME__',$don->firstname,$form); - $form = str_replace('__DONATOR_LASTNAME__',$don->lastname,$form); + $form = str_replace('__DONATOR_LASTNAME__',$don->lastname,$form); $form = str_replace('__DONATOR_SOCIETE__',$don->societe,$form); $form = str_replace('__DONATOR_STATUT__',$don->statut,$form); - $form = str_replace('__DONATOR_ADDRESS__',$don->address,$form); - $form = str_replace('__DONATOR_ZIP__',$don->zip,$form); - $form = str_replace('__DONATOR_TOWN__',$don->town,$form); - $form = str_replace('__PAYMENTMODE_LIB__ ', $paymentmode,$form); + $form = str_replace('__DONATOR_ADDRESS__',$don->address,$form); + $form = str_replace('__DONATOR_ZIP__',$don->zip,$form); + $form = str_replace('__DONATOR_TOWN__',$don->town,$form); + $form = str_replace('__PAYMENTMODE_LIB__ ', $paymentmode,$form); $form = str_replace('__ModePaiement__', $ModePaiement,$form); - $form = str_replace('__NOW__',dol_print_date($now,'day',false,$outputlangs),$form); - $form = str_replace('__DonationRef__',$outputlangs->trans("DonationRef"),$form); + $form = str_replace('__NOW__',dol_print_date($now,'day',false,$outputlangs),$form); + $form = str_replace('__DonationRef__',$outputlangs->trans("DonationRef"),$form); $form = str_replace('__DonationTitle__',$outputlangs->trans("DonationTitle"),$form); - $form = str_replace('__DonationReceipt__',$outputlangs->trans("DonationReceipt"),$form); - $form = str_replace('__DonationRecipient__',$outputlangs->trans("DonationRecipient"),$form); - $form = str_replace('__DonationDatePayment__',$outputlangs->trans("DonationDatePayment"),$form); + $form = str_replace('__DonationReceipt__',$outputlangs->trans("DonationReceipt"),$form); + $form = str_replace('__DonationRecipient__',$outputlangs->trans("DonationRecipient"),$form); + $form = str_replace('__DonationDatePayment__',$outputlangs->trans("DonationDatePayment"),$form); $form = str_replace('__PaymentMode__',$outputlangs->trans("PaymentMode"),$form); // $form = str_replace('__CodeDon__',$CodeDon,$form); - $form = str_replace('__Name__',$outputlangs->trans("Name"),$form); - $form = str_replace('__Address__',$outputlangs->trans("Address"),$form); - $form = str_replace('__Zip__',$outputlangs->trans("Zip"),$form); - $form = str_replace('__Town__',$outputlangs->trans("Town"),$form); + $form = str_replace('__Name__',$outputlangs->trans("Name"),$form); + $form = str_replace('__Address__',$outputlangs->trans("Address"),$form); + $form = str_replace('__Zip__',$outputlangs->trans("Zip"),$form); + $form = str_replace('__Town__',$outputlangs->trans("Town"),$form); $form = str_replace('__Object__',$outputlangs->trans("Object"),$form); - $form = str_replace('__Donor__',$outputlangs->trans("Donor"),$form); - $form = str_replace('__Date__',$outputlangs->trans("Date"),$form); - $form = str_replace('__Signature__',$outputlangs->trans("Signature"),$form); - $form = str_replace('__Message__',$outputlangs->trans("Message"),$form); - $form = str_replace('__IConfirmDonationReception__',$outputlangs->trans("IConfirmDonationReception"),$form); - $form = str_replace('__DonationMessage__',$conf->global->DONATION_MESSAGE,$form); + $form = str_replace('__Donor__',$outputlangs->trans("Donor"),$form); + $form = str_replace('__Date__',$outputlangs->trans("Date"),$form); + $form = str_replace('__Signature__',$outputlangs->trans("Signature"),$form); + $form = str_replace('__Message__',$outputlangs->trans("Message"),$form); + $form = str_replace('__IConfirmDonationReception__',$outputlangs->trans("IConfirmDonationReception"),$form); + $form = str_replace('__DonationMessage__',$conf->global->DONATION_MESSAGE,$form); $frencharticle=''; - if (preg_match('/fr/i',$outputlangs->defaultlang)) $frencharticle='Article 200, 238 bis et 885-0 V bis A du code général des impôts (CGI)'; + if (preg_match('/fr/i',$outputlangs->defaultlang)) $frencharticle='Article 200, 238 bis et 885-0 V bis A du code général des impôts (CGI)'; $form = str_replace('__FrenchArticle__',$frencharticle,$form); $frencheligibility=''; @@ -252,176 +252,176 @@ class html_cerfafr extends ModeleDon $form = str_replace('__ARTICLE885__',$art885,$form); // Save file on disk - dol_syslog("html_cerfafr::write_file $file"); - $handle=fopen($file,"w"); - fwrite($handle,$form); - fclose($handle); + dol_syslog("html_cerfafr::write_file $file"); + $handle=fopen($file,"w"); + fwrite($handle,$form); + fclose($handle); if (! empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - return 1; - } - else - { - $this->error=$langs->trans("ErrorCanNotCreateDir",$dir); - return 0; - } - } - else - { - $this->error=$langs->trans("ErrorConstantNotDefined","DON_OUTPUTDIR"); - return 0; + return 1; + } + else + { + $this->error=$langs->trans("ErrorCanNotCreateDir",$dir); + return 0; + } } - } + else + { + $this->error=$langs->trans("ErrorConstantNotDefined","DON_OUTPUTDIR"); + return 0; + } + } } function chiffre_en_lettre($montant, $devise1='', $devise2='') { - if(empty($devise1)) $dev1='euros'; - else $dev1=$devise1; - if(empty($devise2)) $dev2='centimes'; - else $dev2=$devise2; - $valeur_entiere=intval($montant); - $valeur_decimal=intval(round($montant-intval($montant), 2)*100); - $dix_c=intval($valeur_decimal%100/10); - $cent_c=intval($valeur_decimal%1000/100); - $unite[1]=$valeur_entiere%10; - $dix[1]=intval($valeur_entiere%100/10); - $cent[1]=intval($valeur_entiere%1000/100); - $unite[2]=intval($valeur_entiere%10000/1000); - $dix[2]=intval($valeur_entiere%100000/10000); - $cent[2]=intval($valeur_entiere%1000000/100000); - $unite[3]=intval($valeur_entiere%10000000/1000000); - $dix[3]=intval($valeur_entiere%100000000/10000000); - $cent[3]=intval($valeur_entiere%1000000000/100000000); - $chif=array('', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix sept', 'dix huit', 'dix neuf'); - $secon_c=''; - $trio_c=''; - for($i=1; $i<=3; $i++){ - $prim[$i]=''; - $secon[$i]=''; - $trio[$i]=''; - if($dix[$i]==0){ - $secon[$i]=''; - $prim[$i]=$chif[$unite[$i]]; - } - else if($dix[$i]==1){ - $secon[$i]=''; - $prim[$i]=$chif[($unite[$i]+10)]; - } - else if($dix[$i]==2){ - if($unite[$i]==1){ - $secon[$i]='vingt et'; - $prim[$i]=$chif[$unite[$i]]; - } - else { - $secon[$i]='vingt'; - $prim[$i]=$chif[$unite[$i]]; - } - } - else if($dix[$i]==3){ - if($unite[$i]==1){ - $secon[$i]='trente et'; - $prim[$i]=$chif[$unite[$i]]; - } - else { - $secon[$i]='trente'; - $prim[$i]=$chif[$unite[$i]]; - } - } - else if($dix[$i]==4){ - if($unite[$i]==1){ - $secon[$i]='quarante et'; - $prim[$i]=$chif[$unite[$i]]; - } - else { - $secon[$i]='quarante'; - $prim[$i]=$chif[$unite[$i]]; - } - } - else if($dix[$i]==5){ - if($unite[$i]==1){ - $secon[$i]='cinquante et'; - $prim[$i]=$chif[$unite[$i]]; - } - else { - $secon[$i]='cinquante'; - $prim[$i]=$chif[$unite[$i]]; - } - } - else if($dix[$i]==6){ - if($unite[$i]==1){ - $secon[$i]='soixante et'; - $prim[$i]=$chif[$unite[$i]]; - } - else { - $secon[$i]='soixante'; - $prim[$i]=$chif[$unite[$i]]; - } - } - else if($dix[$i]==7){ - if($unite[$i]==1){ - $secon[$i]='soixante et'; - $prim[$i]=$chif[$unite[$i]+10]; - } - else { - $secon[$i]='soixante'; - $prim[$i]=$chif[$unite[$i]+10]; - } - } - else if($dix[$i]==8){ - if($unite[$i]==1){ - $secon[$i]='quatre-vingts et'; - $prim[$i]=$chif[$unite[$i]]; - } - else { - $secon[$i]='quatre-vingt'; - $prim[$i]=$chif[$unite[$i]]; - } - } - else if($dix[$i]==9){ - if($unite[$i]==1){ - $secon[$i]='quatre-vingts et'; - $prim[$i]=$chif[$unite[$i]+10]; - } - else { - $secon[$i]='quatre-vingts'; - $prim[$i]=$chif[$unite[$i]+10]; - } - } - if($cent[$i]==1) $trio[$i]='cent'; - else if($cent[$i]!=0 || $cent[$i]!='') $trio[$i]=$chif[$cent[$i]] .' cents'; - } + if(empty($devise1)) $dev1='euros'; + else $dev1=$devise1; + if(empty($devise2)) $dev2='centimes'; + else $dev2=$devise2; + $valeur_entiere=intval($montant); + $valeur_decimal=intval(round($montant-intval($montant), 2)*100); + $dix_c=intval($valeur_decimal%100/10); + $cent_c=intval($valeur_decimal%1000/100); + $unite[1]=$valeur_entiere%10; + $dix[1]=intval($valeur_entiere%100/10); + $cent[1]=intval($valeur_entiere%1000/100); + $unite[2]=intval($valeur_entiere%10000/1000); + $dix[2]=intval($valeur_entiere%100000/10000); + $cent[2]=intval($valeur_entiere%1000000/100000); + $unite[3]=intval($valeur_entiere%10000000/1000000); + $dix[3]=intval($valeur_entiere%100000000/10000000); + $cent[3]=intval($valeur_entiere%1000000000/100000000); + $chif=array('', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix sept', 'dix huit', 'dix neuf'); + $secon_c=''; + $trio_c=''; + for($i=1; $i<=3; $i++){ + $prim[$i]=''; + $secon[$i]=''; + $trio[$i]=''; + if($dix[$i]==0){ + $secon[$i]=''; + $prim[$i]=$chif[$unite[$i]]; + } + else if($dix[$i]==1){ + $secon[$i]=''; + $prim[$i]=$chif[($unite[$i]+10)]; + } + else if($dix[$i]==2){ + if($unite[$i]==1){ + $secon[$i]='vingt et'; + $prim[$i]=$chif[$unite[$i]]; + } + else { + $secon[$i]='vingt'; + $prim[$i]=$chif[$unite[$i]]; + } + } + else if($dix[$i]==3){ + if($unite[$i]==1){ + $secon[$i]='trente et'; + $prim[$i]=$chif[$unite[$i]]; + } + else { + $secon[$i]='trente'; + $prim[$i]=$chif[$unite[$i]]; + } + } + else if($dix[$i]==4){ + if($unite[$i]==1){ + $secon[$i]='quarante et'; + $prim[$i]=$chif[$unite[$i]]; + } + else { + $secon[$i]='quarante'; + $prim[$i]=$chif[$unite[$i]]; + } + } + else if($dix[$i]==5){ + if($unite[$i]==1){ + $secon[$i]='cinquante et'; + $prim[$i]=$chif[$unite[$i]]; + } + else { + $secon[$i]='cinquante'; + $prim[$i]=$chif[$unite[$i]]; + } + } + else if($dix[$i]==6){ + if($unite[$i]==1){ + $secon[$i]='soixante et'; + $prim[$i]=$chif[$unite[$i]]; + } + else { + $secon[$i]='soixante'; + $prim[$i]=$chif[$unite[$i]]; + } + } + else if($dix[$i]==7){ + if($unite[$i]==1){ + $secon[$i]='soixante et'; + $prim[$i]=$chif[$unite[$i]+10]; + } + else { + $secon[$i]='soixante'; + $prim[$i]=$chif[$unite[$i]+10]; + } + } + else if($dix[$i]==8){ + if($unite[$i]==1){ + $secon[$i]='quatre-vingts et'; + $prim[$i]=$chif[$unite[$i]]; + } + else { + $secon[$i]='quatre-vingt'; + $prim[$i]=$chif[$unite[$i]]; + } + } + else if($dix[$i]==9){ + if($unite[$i]==1){ + $secon[$i]='quatre-vingts et'; + $prim[$i]=$chif[$unite[$i]+10]; + } + else { + $secon[$i]='quatre-vingts'; + $prim[$i]=$chif[$unite[$i]+10]; + } + } + if($cent[$i]==1) $trio[$i]='cent'; + else if($cent[$i]!=0 || $cent[$i]!='') $trio[$i]=$chif[$cent[$i]] .' cents'; + } $chif2=array('', 'dix', 'vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante-dix', 'quatre-vingts', 'quatre-vingts dix'); - $secon_c=$chif2[$dix_c]; - if($cent_c==1) $trio_c='cent'; - else if($cent_c!=0 || $cent_c!='') $trio_c=$chif[$cent_c] .' cents'; + $secon_c=$chif2[$dix_c]; + if($cent_c==1) $trio_c='cent'; + else if($cent_c!=0 || $cent_c!='') $trio_c=$chif[$cent_c] .' cents'; - if(($cent[3]==0 || $cent[3]=='') && ($dix[3]==0 || $dix[3]=='') && ($unite[3]==1)) - $somme = $trio[3]. ' ' .$secon[3]. ' ' . $prim[3]. ' million '; - else if(($cent[3]!=0 && $cent[3]!='') || ($dix[3]!=0 && $dix[3]!='') || ($unite[3]!=0 && $unite[3]!='')) - $somme = $trio[3]. ' ' .$secon[3]. ' ' . $prim[3]. ' millions '; - else - $somme = $trio[3]. ' ' .$secon[3]. ' ' . $prim[3]; + if(($cent[3]==0 || $cent[3]=='') && ($dix[3]==0 || $dix[3]=='') && ($unite[3]==1)) + $somme = $trio[3]. ' ' .$secon[3]. ' ' . $prim[3]. ' million '; + else if(($cent[3]!=0 && $cent[3]!='') || ($dix[3]!=0 && $dix[3]!='') || ($unite[3]!=0 && $unite[3]!='')) + $somme = $trio[3]. ' ' .$secon[3]. ' ' . $prim[3]. ' millions '; + else + $somme = $trio[3]. ' ' .$secon[3]. ' ' . $prim[3]; - if(($cent[2]==0 || $cent[2]=='') && ($dix[2]==0 || $dix[2]=='') && ($unite[2]==1)) - $somme = $somme.' mille '; - else if(($cent[2]!=0 && $cent[2]!='') || ($dix[2]!=0 && $dix[2]!='') || ($unite[2]!=0 && $unite[2]!='')) - $somme = $somme. $trio[2]. ' ' .$secon[2]. ' ' . $prim[2]. ' milles '; - else - $somme = $somme. $trio[2]. ' ' .$secon[2]. ' ' . $prim[2]; + if(($cent[2]==0 || $cent[2]=='') && ($dix[2]==0 || $dix[2]=='') && ($unite[2]==1)) + $somme = $somme.' mille '; + else if(($cent[2]!=0 && $cent[2]!='') || ($dix[2]!=0 && $dix[2]!='') || ($unite[2]!=0 && $unite[2]!='')) + $somme = $somme. $trio[2]. ' ' .$secon[2]. ' ' . $prim[2]. ' milles '; + else + $somme = $somme. $trio[2]. ' ' .$secon[2]. ' ' . $prim[2]; - $somme = $somme. $trio[1]. ' ' .$secon[1]. ' ' . $prim[1]; + $somme = $somme. $trio[1]. ' ' .$secon[1]. ' ' . $prim[1]; - $somme = $somme. ' '. $dev1 .' ' ; + $somme = $somme. ' '. $dev1 .' ' ; - if(($cent_c=='0' || $cent_c=='') && ($dix_c=='0' || $dix_c=='')) - return $somme. ' et zéro '. $dev2; - else - return $somme. $trio_c. ' ' .$secon_c. ' ' . $dev2; + if(($cent_c=='0' || $cent_c=='') && ($dix_c=='0' || $dix_c=='')) + return $somme. ' et zéro '. $dev2; + else + return $somme. $trio_c. ' ' .$secon_c. ' ' . $dev2; } diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php index ef4dd5ff6fc..2d5a27bb3df 100644 --- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php @@ -125,7 +125,7 @@ class pdf_crabe extends ModelePDFFactures } else { - $this->posxtva=112; + $this->posxtva=110; $this->posxup=126; $this->posxqty=145; } @@ -496,8 +496,8 @@ class pdf_crabe extends ModelePDFFactures if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) { $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails); - $pdf->SetXY($this->posxtva, $curY); - $pdf->MultiCell($this->posxup-$this->posxtva-0.8, 3, $vat_rate, 0, 'R'); + $pdf->SetXY($this->posxtva-5, $curY); + $pdf->MultiCell($this->posxup-$this->posxtva+4, 3, $vat_rate, 0, 'R'); } // Unit price before discount @@ -820,7 +820,7 @@ class pdf_crabe extends ModelePDFFactures $sql = "SELECT p.datep as date, p.fk_paiement, p.num_paiement as num, pf.amount as amount, pf.multicurrency_amount,"; $sql.= " cp.code"; $sql.= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id AND cp.entity = " . getEntity('c_paiement'); $sql.= " WHERE pf.fk_paiement = p.rowid AND pf.fk_facture = ".$object->id; //$sql.= " WHERE pf.fk_paiement = p.rowid AND pf.fk_facture = 1"; $sql.= " ORDER BY p.datep"; @@ -1566,7 +1566,7 @@ class pdf_crabe extends ModelePDFFactures if ($object->type == 1) $title=$outputlangs->transnoentities("InvoiceReplacement"); if ($object->type == 2) $title=$outputlangs->transnoentities("InvoiceAvoir"); if ($object->type == 3) $title=$outputlangs->transnoentities("InvoiceDeposit"); - if ($object->type == 4) $title=$outputlangs->transnoentities("InvoiceProFormat"); + if ($object->type == 4) $title=$outputlangs->transnoentities("InvoiceProForma"); if ($this->situationinvoice) $title=$outputlangs->transnoentities("InvoiceSituation"); $pdf->MultiCell($w, 3, $title, '', 'R'); diff --git a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php index eeba25962cb..fcb0bb6b057 100644 --- a/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php +++ b/htdocs/core/modules/livraison/doc/pdf_typhon.modules.php @@ -283,11 +283,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1); $nexY = $pdf->GetY(); $height_incoterms=$nexY-$tab_top; - + // Rect prend une longueur en 3eme param $pdf->SetDrawColor(192,192,192); $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1); - + $tab_top = $nexY+6; $height_incoterms += 4; } @@ -567,7 +567,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - + return 1; // pas d'erreur } else @@ -662,14 +662,14 @@ class pdf_typhon extends ModelePDFDeliveryOrder $pdf->line($this->posxqty, $tab_top, $this->posxqty, $tab_top + $tab_height); if (empty($hidetop)) { $pdf->SetXY($this->posxqty, $tab_top+1); - $pdf->MultiCell($this->posxremainingqty - $this->posxqty, 2, $outputlangs->transnoentities("QtyShipped"),'','R'); + $pdf->MultiCell($this->posxremainingqty - $this->posxqty, 2, $outputlangs->transnoentities("QtyShippedShort"),'','R'); } // Remain to ship $pdf->line($this->posxremainingqty, $tab_top, $this->posxremainingqty, $tab_top + $tab_height); if (empty($hidetop)) { $pdf->SetXY($this->posxremainingqty, $tab_top+1); - $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->posxremainingqty, 2, $outputlangs->transnoentities("KeepToShip"),'','R'); + $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->posxremainingqty, 2, $outputlangs->transnoentities("KeepToShipShort"),'','R'); } } diff --git a/htdocs/core/modules/mailings/advthirdparties.modules.php b/htdocs/core/modules/mailings/advthirdparties.modules.php index 497d3c54f54..9252ae5ec3a 100644 --- a/htdocs/core/modules/mailings/advthirdparties.modules.php +++ b/htdocs/core/modules/mailings/advthirdparties.modules.php @@ -116,7 +116,7 @@ class mailing_advthirdparties extends MailingTargets } } - if (($type_of_target==1) || ($type_of_target==2)) { + if (($type_of_target==1) || ($type_of_target==2) || ($type_of_target==4)) { // Select the third parties from category if (count($socid)>0 || count($contactid)>0) { diff --git a/htdocs/core/modules/member/doc/pdf_standard.class.php b/htdocs/core/modules/member/doc/pdf_standard.class.php index 6fd8ecfee70..4d08be83a43 100644 --- a/htdocs/core/modules/member/doc/pdf_standard.class.php +++ b/htdocs/core/modules/member/doc/pdf_standard.class.php @@ -48,8 +48,8 @@ class pdf_standard extends CommonStickerGenerator /** * Output a sticker on page at position _COUNTX, _COUNTY (_COUNTX and _COUNTY start from 0) - * - %LOGO% is replace with company logo - * - %PHOTO% is replace with photo provided as parameter + * - __LOGO__ is replace with company logo + * - __PHOTO__ is replace with photo provided as parameter * * @param PDF $pdf PDF * @param string $textleft Text left @@ -58,7 +58,7 @@ class pdf_standard extends CommonStickerGenerator * @param Translate $outputlangs Output langs * @param string $textright Text right * @param int $idmember Id member - * @param string $photo Photo (full path to image file used as replacement for key %PHOTOS% into left, right, header or footer text) + * @param string $photo Photo (full path to image file used as replacement for key __PHOTOS__ into left, right, header or footer text) * @return void */ function Add_PDF_card(&$pdf,$textleft,$header,$footer,$outputlangs,$textright='',$idmember=0,$photo='') @@ -95,7 +95,7 @@ class pdf_standard extends CommonStickerGenerator $member=new Adherent($db); $member->id = $idmember; $member->ref = $idmember; - + // Define photo $dir=$conf->adherent->dir_output; if (! empty($photo)) @@ -161,8 +161,8 @@ class pdf_standard extends CommonStickerGenerator if ($textright=='') // Only a left part { // Output left area - if ($textleft == '%LOGO%' && $logo) $pdf->Image($logo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); - else if ($textleft == '%PHOTO%' && $photo) $pdf->Image($photo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + if ($textleft == '__LOGO__' && $logo) $pdf->Image($logo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + else if ($textleft == '__PHOTO__' && $photo) $pdf->Image($photo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); else { $pdf->SetXY($_PosX+$xleft, $_PosY+$ytop); @@ -171,17 +171,17 @@ class pdf_standard extends CommonStickerGenerator } else if ($textleft!='' && $textright!='') // { - if ($textleft == '%LOGO%' || $textleft == '%PHOTO%') + if ($textleft == '__LOGO__' || $textleft == '__PHOTO__') { - if ($textleft == '%LOGO%' && $logo) $pdf->Image($logo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); - else if ($textleft == '%PHOTO%' && $photo) $pdf->Image($photo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + if ($textleft == '__LOGO__' && $logo) $pdf->Image($logo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + else if ($textleft == '__PHOTO__' && $photo) $pdf->Image($photo,$_PosX+$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); $pdf->SetXY($_PosX+$xleft+$widthtouse+1, $_PosY+$ytop); $pdf->MultiCell($this->_Width-$xleft-$xleft-$widthtouse-1, $this->_Line_Height, $outputlangs->convToOutputCharset($textright),0,'R'); } - else if ($textright == '%LOGO%' || $textright == '%PHOTO%') + else if ($textright == '__LOGO__' || $textright == '__PHOTO__') { - if ($textright == '%LOGO%' && $logo) $pdf->Image($logo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); - else if ($textright == '%PHOTO%' && $photo) $pdf->Image($photo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + if ($textright == '__LOGO__' && $logo) $pdf->Image($logo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + else if ($textright == '__PHOTO__' && $photo) $pdf->Image($photo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); $pdf->SetXY($_PosX+$xleft, $_PosY+$ytop); $pdf->MultiCell($this->_Width-$widthtouse-$xleft-$xleft-1, $this->_Line_Height, $outputlangs->convToOutputCharset($textleft),0,'L'); } @@ -196,8 +196,8 @@ class pdf_standard extends CommonStickerGenerator else // Only a right part { // Output right area - if ($textright == '%LOGO%' && $logo) $pdf->Image($logo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); - else if ($textright == '%PHOTO%' && $photo) $pdf->Image($photo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + if ($textright == '__LOGO__' && $logo) $pdf->Image($logo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); + else if ($textright == '__PHOTO__' && $photo) $pdf->Image($photo,$_PosX+$this->_Width-$widthtouse-$xleft,$_PosY+$ytop,$widthtouse,$heighttouse); else { $pdf->SetXY($_PosX+$xleft, $_PosY+$ytop); @@ -247,34 +247,34 @@ class pdf_standard extends CommonStickerGenerator function write_file($object, $outputlangs, $srctemplatepath, $mode='member', $nooutput=0) { global $user,$conf,$langs,$mysoc,$_Avery_Labels; - + $this->code=$srctemplatepath; - + if (is_object($object)) { if ($object->country == '-') $object->country=''; // List of values to scan for a replacement $substitutionarray = array ( - '%ID%'=>$object->rowid, - '%LOGIN%'=>$object->login, - '%FIRSTNAME%'=>$object->firstname, - '%LASTNAME%'=>$object->lastname, - '%FULLNAME%'=>$object->getFullName($langs), - '%COMPANY%'=>$object->company, - '%ADDRESS%'=>$object->address, - '%ZIP%'=>$object->zip, - '%TOWN%'=>$object->town, - '%COUNTRY%'=>$object->country, - '%COUNTRY_CODE%'=>$object->country_code, - '%EMAIL%'=>$object->email, - '%BIRTH%'=>dol_print_date($object->birth,'day'), - '%TYPE%'=>$object->type, - '%YEAR%'=>$year, - '%MONTH%'=>$month, - '%DAY%'=>$day, - '%DOL_MAIN_URL_ROOT%'=>DOL_MAIN_URL_ROOT, - '%SERVER%'=>"http://".$_SERVER["SERVER_NAME"]."/" + '__ID__'=>$object->rowid, + '__LOGIN__'=>$object->login, + '__FIRSTNAME__'=>$object->firstname, + '__LASTNAME__'=>$object->lastname, + '__FULLNAME__'=>$object->getFullName($langs), + '__COMPANY__'=>$object->company, + '__ADDRESS__'=>$object->address, + '__ZIP__'=>$object->zip, + '__TOWN__'=>$object->town, + '__COUNTRY__'=>$object->country, + '__COUNTRY_CODE__'=>$object->country_code, + '__EMAIL__'=>$object->email, + '__BIRTH__'=>dol_print_date($object->birth,'day'), + '__TYPE__'=>$object->type, + '__YEAR__'=>$year, + '__MONTH__'=>$month, + '__DAY__'=>$day, + '__DOL_MAIN_URL_ROOT__'=>DOL_MAIN_URL_ROOT, + '__SERVER__'=>"http://".$_SERVER["SERVER_NAME"]."/" ); complete_substitutions_array($substitutionarray, $langs); @@ -283,10 +283,10 @@ class pdf_standard extends CommonStickerGenerator $textheader=make_substitutions($conf->global->ADHERENT_CARD_HEADER_TEXT, $substitutionarray); $textfooter=make_substitutions($conf->global->ADHERENT_CARD_FOOTER_TEXT, $substitutionarray); $textright=make_substitutions($conf->global->ADHERENT_CARD_TEXT_RIGHT, $substitutionarray); - + $nb = $_Avery_Labels[$this->code]['NX'] * $_Avery_Labels[$this->code]['NY']; if ($nb <= 0) $nb=1; // Protection to avoid empty page - + for($j=0;$j<$nb;$j++) { $arrayofmembers[]=array( @@ -298,7 +298,7 @@ class pdf_standard extends CommonStickerGenerator 'photo'=>$object->photo ); } - + $arrayofrecords = $arrayofmembers; } else @@ -348,7 +348,7 @@ class pdf_standard extends CommonStickerGenerator $dir = $outputdir."/".get_exdir(0, 0, 0, 0, $object, 'member'); $file = $dir.'/'.$filename; } - else + else { $outputdir = $conf->adherent->dir_temp; $dir = $outputdir; @@ -419,28 +419,28 @@ class pdf_standard extends CommonStickerGenerator $this->result = array('fullpath'=>$file); - + // Output to http stream if (empty($nooutput)) { clearstatcache(); - + $attachment=true; if (! empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS)) $attachment=false; $type=dol_mimetype($filename); - + //if ($encoding) header('Content-Encoding: '.$encoding); if ($type) header('Content-Type: '.$type); if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); else header('Content-Disposition: inline; filename="'.$filename.'"'); - + // Ajout directives pour resoudre bug IE header('Cache-Control: Public, must-revalidate'); header('Pragma: public'); - + readfile($file); } - + return 1; } diff --git a/htdocs/core/modules/modAdherent.class.php b/htdocs/core/modules/modAdherent.class.php index ade0e2c7e75..aa098146dc7 100644 --- a/htdocs/core/modules/modAdherent.class.php +++ b/htdocs/core/modules/modAdherent.class.php @@ -93,7 +93,7 @@ class modAdherent extends DolibarrModules $this->const[$r][0] = "ADHERENT_MAIL_VALID"; $this->const[$r][1] = "texte"; - $this->const[$r][2] = "Votre adhésion vient d'être validée. \r\nVoici le rappel de vos coordonnées (toute information erronée entrainera la non validation de votre inscription) :\r\n\r\n%INFOS%\r\n\r\n"; + $this->const[$r][2] = "Votre adhésion vient d'être validée. \r\nVoici le rappel de vos coordonnées (toute information erronée entrainera la non validation de votre inscription) :\r\n\r\n__INFOS__\r\n\r\n"; $this->const[$r][3] = "Mail de validation"; $this->const[$r][4] = 0; $r++; @@ -121,7 +121,7 @@ class modAdherent extends DolibarrModules $this->const[$r][0] = "ADHERENT_MAIL_COTIS"; $this->const[$r][1] = "texte"; - $this->const[$r][2] = "Bonjour %FIRSTNAME%,\r\nCet email confirme que votre cotisation a été reçue\r\net enregistrée"; + $this->const[$r][2] = "Bonjour __FIRSTNAME__,\r\nCet email confirme que votre cotisation a été reçue\r\net enregistrée"; $this->const[$r][3] = "Mail de validation de cotisation"; $this->const[$r][4] = 0; $r++; @@ -135,21 +135,21 @@ class modAdherent extends DolibarrModules $this->const[$r][0] = "ADHERENT_CARD_HEADER_TEXT"; $this->const[$r][1] = "chaine"; - $this->const[$r][2] = "%YEAR%"; + $this->const[$r][2] = "__YEAR__"; $this->const[$r][3] = "Texte imprimé sur le haut de la carte adhérent"; $this->const[$r][4] = 0; $r++; $this->const[$r][0] = "ADHERENT_CARD_FOOTER_TEXT"; $this->const[$r][1] = "chaine"; - $this->const[$r][2] = "%COMPANY%"; + $this->const[$r][2] = "__COMPANY__"; $this->const[$r][3] = "Texte imprimé sur le bas de la carte adhérent"; $this->const[$r][4] = 0; $r++; $this->const[$r][0] = "ADHERENT_CARD_TEXT"; $this->const[$r][1] = "texte"; - $this->const[$r][2] = "%FULLNAME%\r\nID: %ID%\r\n%EMAIL%\r\n%ADDRESS%\r\n%ZIP% %TOWN%\r\n%COUNTRY%"; + $this->const[$r][2] = "__FULLNAME__\r\nID: __ID__\r\n__EMAIL__\r\n__ADDRESS__\r\n__ZIP__ __TOWN__\r\n__COUNTRY__"; $this->const[$r][3] = "Text to print on member cards"; $this->const[$r][4] = 0; $r++; @@ -184,7 +184,7 @@ class modAdherent extends DolibarrModules $this->const[$r][0] = "ADHERENT_ETIQUETTE_TEXT"; $this->const[$r][1] = "texte"; - $this->const[$r][2] = "%FULLNAME%\n%ADDRESS%\n%ZIP% %TOWN%\n%COUNTRY%"; + $this->const[$r][2] = "__FULLNAME__\n__ADDRESS__\n__ZIP__ __TOWN__\n__COUNTRY%"; $this->const[$r][3] = "Text to print on member address sheets"; $this->const[$r][4] = 0; $r++; @@ -324,7 +324,7 @@ class modAdherent extends DolibarrModules // End add extra fields $this->import_fieldshidden_array[$r]=array('extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'adherent'); // aliastable.field => ('user->id' or 'lastrowid-'.tableparent) $this->import_regex_array[$r]=array('a.civility'=>'code@'.MAIN_DB_PREFIX.'c_civility','a.fk_adherent_type'=>'rowid@'.MAIN_DB_PREFIX.'adherent_type','a.morphy'=>'(phy|mor)','a.statut'=>'^[0|1]','a.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$','a.datefin'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$'); - $this->import_examplevalues_array[$r]=array('a.civility'=>"MR",'a.lastname'=>'Smith','a.firstname'=>'John','a.login'=>'jsmith','a.pass'=>'passofjsmith','a.fk_adherent_type'=>'1','a.morphy'=>'"mor" or "phy"','a.societe'=>'JS company','a.address'=>'21 jump street','a.zip'=>'55000','a.town'=>'New York','a.country'=>'1','a.email'=>'jsmith@example.com','a.birth'=>'1972-10-10','a.statut'=>"0 or 1",'a.note_public'=>"This is a public comment on member",'a.note_private'=>"This is private comment on member",'a.datec'=>dol_print_date($now,'%Y-%m-%d'),'a.datefin'=>dol_print_date(dol_time_plus_duree($now, 1, 'y'),'%Y-%m-%d')); + $this->import_examplevalues_array[$r]=array('a.civility'=>"MR",'a.lastname'=>'Smith','a.firstname'=>'John','a.login'=>'jsmith','a.pass'=>'passofjsmith','a.fk_adherent_type'=>'1','a.morphy'=>'"mor" or "phy"','a.societe'=>'JS company','a.address'=>'21 jump street','a.zip'=>'55000','a.town'=>'New York','a.country'=>'1','a.email'=>'jsmith@example.com','a.birth'=>'1972-10-10','a.statut'=>"0 or 1",'a.note_public'=>"This is a public comment on member",'a.note_private'=>"This is private comment on member",'a.datec'=>dol_print_date($now,'%Y-%m__%d'),'a.datefin'=>dol_print_date(dol_time_plus_duree($now, 1, 'y'),'%Y-%m-%d')); } diff --git a/htdocs/core/modules/modApi.class.php b/htdocs/core/modules/modApi.class.php index fc1821fde53..34c8e62a03f 100644 --- a/htdocs/core/modules/modApi.class.php +++ b/htdocs/core/modules/modApi.class.php @@ -20,7 +20,7 @@ /** * \defgroup api Module Api * \brief Descriptor file for Api modulee - * \file htdocs/api/core/modules/modApi.class.php + * \file htdocs/core/modules/modApi.class.php * \ingroup api * \brief Description and activation file for module Api */ @@ -67,7 +67,7 @@ class modApi extends DolibarrModules // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' $this->picto='technic'; - + $this->module_parts = array(); // Data directories to create when module is enabled. diff --git a/htdocs/core/modules/modFacture.class.php b/htdocs/core/modules/modFacture.class.php index 6e5206ac7a5..53f23265d6b 100644 --- a/htdocs/core/modules/modFacture.class.php +++ b/htdocs/core/modules/modFacture.class.php @@ -249,23 +249,23 @@ class modFacture extends DolibarrModules $this->export_dependencies_array[$r] = array('payment'=>'p.rowid', 'none.rest'=>array('f.rowid', 'f.total_ttc')); // To add unique key if we ask a field of a child to avoid the DISTINCT to discard them $keyforselect = 'facture'; $keyforelement = 'invoice'; $keyforaliasextra = 'extra'; include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; - $this->export_sql_start[$r] = 'SELECT DISTINCT '; - $this->export_sql_end[$r] = ' FROM '.MAIN_DB_PREFIX.'societe as s'; - if (empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_commerciaux as sc ON sc.fk_soc = s.rowid'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c on s.fk_pays = c.rowid,'; - $this->export_sql_end[$r] .= ' '.MAIN_DB_PREFIX.'facture as f'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pj ON f.fk_projet = pj.rowid'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as uc ON f.fk_user_author = uc.rowid'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as uv ON f.fk_user_valid = uv.rowid'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_extrafields as extra ON f.rowid = extra.fk_object'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement as p ON pf.fk_paiement = p.rowid'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pt ON pt.id = p.fk_paiement'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON b.rowid = p.fk_bank'; - $this->export_sql_end[$r] .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON ba.rowid = b.fk_account'; - $this->export_sql_end[$r] .= ' WHERE f.fk_soc = s.rowid'; - $this->export_sql_end[$r] .= ' AND f.entity IN ('.getEntity('facture').')'; - if (isset($user) && empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .= ' AND sc.fk_user = '.$user->id; + $this->export_sql_start[$r]='SELECT DISTINCT '; + $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'societe as s'; + if (empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'societe_commerciaux as sc ON sc.fk_soc = s.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c on s.fk_pays = c.rowid,'; + $this->export_sql_end[$r] .=' '.MAIN_DB_PREFIX.'facture as f'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pj ON f.fk_projet = pj.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'user as uc ON f.fk_user_author = uc.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'user as uv ON f.fk_user_valid = uv.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'facture_extrafields as extra ON f.rowid = extra.fk_object'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'paiement as p ON pf.fk_paiement = p.rowid'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pt ON pt.id = p.fk_paiement AND pt.entity IN (' . getEntity('c_paiement').')'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON b.rowid = p.fk_bank'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON ba.rowid = b.fk_account'; + $this->export_sql_end[$r] .=' WHERE f.fk_soc = s.rowid'; + $this->export_sql_end[$r] .=' AND f.entity IN ('.getEntity('facture').')'; + if (isset($user) && empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .=' AND sc.fk_user = '.$user->id; $r++; } diff --git a/htdocs/core/modules/modProduct.class.php b/htdocs/core/modules/modProduct.class.php index f51e69039e9..79541c10105 100644 --- a/htdocs/core/modules/modProduct.class.php +++ b/htdocs/core/modules/modProduct.class.php @@ -260,10 +260,12 @@ class modProduct extends DolibarrModules $this->import_entities_array[$r]=array(); // We define here only fields that use another icon that the one defined into import_icon $this->import_tables_array[$r]=array('p'=>MAIN_DB_PREFIX.'product','extra'=>MAIN_DB_PREFIX.'product_extrafields'); $this->import_tables_creator_array[$r]=array('p'=>'fk_user_author'); // Fields to store import user id - $this->import_fields_array[$r]=array('p.ref'=>"Ref*",'p.label'=>"Label*",'p.description'=>"Description",'p.url'=>"PublicUrl",'p.accountancy_code_sell'=>"ProductAccountancySellCode",'p.accountancy_code_buy'=>"ProductAccountancyBuyCode",'p.note'=>"Note",'p.length'=>"Length",'p.surface'=>"Surface",'p.volume'=>"Volume",'p.weight'=>"Weight",'p.duration'=>"Duration",'p.customcode'=>'CustomCode','p.price'=>"SellingPriceHT",'p.price_ttc'=>"SellingPriceTTC",'p.tva_tx'=>'VAT','p.tosell'=>"OnSell*",'p.tobuy'=>"OnBuy*",'p.fk_product_type'=>"Type*",'p.finished'=>'Nature','p.datec'=>'DateCreation'); + $this->import_fields_array[$r]=array('p.ref'=>"Ref*",'p.label'=>"Label*",'p.description'=>"Description",'p.url'=>"PublicUrl",'p.accountancy_code_sell'=>"ProductAccountancySellCode",'p.accountancy_code_buy'=>"ProductAccountancyBuyCode",'p.note'=>"Note",'p.length'=>"Length",'p.surface'=>"Surface",'p.volume'=>"Volume",'p.weight'=>"Weight",'p.duration'=>"Duration",'p.customcode'=>'CustomCode','p.price'=>"SellingPriceHT",'p.price_ttc'=>"SellingPriceTTC", 'p.tva_tx'=>'VATRate', 'p.tosell'=>"OnSell*",'p.tobuy'=>"OnBuy*",'p.fk_product_type'=>"Type*",'p.finished'=>'Nature','p.datec'=>'DateCreation'); if (! empty($conf->stock->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('p.seuil_stock_alerte'=>'StockLimit','p.desiredstock'=>'DesiredStock','p.pmp'=>'PMPValue')); if (! empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('p.cost_price'=>'CostPrice')); if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('p.recuperableonly'=>'NPR')); + if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('p.localtax1_tx'=>'LT1', 'p.localtax1_type'=>'LT1Type')); + if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('p.localtax2_tx'=>'LT2', 'p.localtax2_type'=>'LT2Type')); if (! empty($conf->barcode->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('p.barcode'=>'BarCode')); if (! empty($conf->global->PRODUCT_USE_UNITS)) $this->import_fields_array[$r]['p.fk_unit'] = 'Unit'; // Add extra fields @@ -300,9 +302,12 @@ class modProduct extends DolibarrModules $this->import_fields_array[$r]=array('sp.fk_product'=>"ProductOrService*", 'sp.fk_soc'=>"Supplier*", 'sp.ref_fourn'=>'SupplierRef', 'sp.quantity'=>"QtyMin*", 'sp.tva_tx'=>'VATRate', 'sp.price'=>"PriceQtyMinHT*", - 'sp.unitprice'=>'UnitPriceHT*', // TODO Make this file not required and calculate it from price and qty + 'sp.unitprice'=>'UnitPriceHT*', // TODO Make this field not required and calculate it from price and qty 'sp.remise_percent'=>'DiscountQtyMin' ); + if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('sp.recuperableonly'=>'NPR')); + if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type')); + if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r],array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type')); $this->import_convertvalue_array[$r]=array( 'sp.fk_soc'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty'), diff --git a/htdocs/core/modules/modSalaries.class.php b/htdocs/core/modules/modSalaries.class.php index 6af1e138b90..27bad86856c 100644 --- a/htdocs/core/modules/modSalaries.class.php +++ b/htdocs/core/modules/modSalaries.class.php @@ -165,7 +165,7 @@ class modSalaries extends DolibarrModules $this->export_sql_start[$r]='SELECT DISTINCT '; $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'user as u'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'payment_salary as p ON p.fk_user = u.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_typepayment = cp.id'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_typepayment = cp.id AND cp.entity IN (' . getEntity('c_paiement').')'; $this->export_sql_end[$r] .=' AND u.entity IN ('.getEntity('user').')'; } diff --git a/htdocs/core/modules/modSociete.class.php b/htdocs/core/modules/modSociete.class.php index 0861dea4a1d..15a4834c7d8 100644 --- a/htdocs/core/modules/modSociete.class.php +++ b/htdocs/core/modules/modSociete.class.php @@ -284,8 +284,8 @@ class modSociete extends DolibarrModules $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'societe_commerciaux as sc ON sc.fk_soc = s.rowid LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON sc.fk_user = u.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as payterm ON s.cond_reglement = payterm.rowid'; - $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as paymode ON s.mode_reglement = paymode.id'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as payterm ON s.cond_reglement = payterm.rowid AND payterm.entity IN (' . getEntity('c_payment_term').')'; + $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as paymode ON s.mode_reglement = paymode.id AND paymode.entity IN (' . getEntity('c_paiement').')'; $this->export_sql_end[$r] .=' WHERE s.entity IN ('.getEntity('societe').')'; if (is_object($user) && empty($user->rights->societe->client->voir)) { $this->export_sql_end[$r] .=' AND (sc.fk_user = '.$user->id.' '; diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php index 913f1e3bc29..0c9a39a3fea 100644 --- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php @@ -114,7 +114,7 @@ class pdf_azur extends ModelePDFPropales } else { - $this->posxtva=112; + $this->posxtva=110; $this->posxup=126; $this->posxqty=145; } @@ -505,8 +505,8 @@ class pdf_azur extends ModelePDFPropales if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) { $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails); - $pdf->SetXY($this->posxtva, $curY); - $pdf->MultiCell($this->posxup-$this->posxtva-0.8, 3, $vat_rate, 0, 'R'); + $pdf->SetXY($this->posxtva-5, $curY); + $pdf->MultiCell($this->posxup-$this->posxtva+4, 3, $vat_rate, 0, 'R'); } // Unit price before discount @@ -1312,6 +1312,7 @@ class pdf_azur extends ModelePDFPropales $pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height); if (empty($hidetop)) { + // Not do -3 and +3 instead of -1 -1 to have more space for text 'Sales tax' $pdf->SetXY($this->posxtva-3, $tab_top+1); $pdf->MultiCell($this->posxup-$this->posxtva+3,2, $outputlangs->transnoentities("VAT"),'','C'); } diff --git a/htdocs/core/modules/rapport/pdf_paiement.class.php b/htdocs/core/modules/rapport/pdf_paiement.class.php index da1223526db..336928ce408 100644 --- a/htdocs/core/modules/rapport/pdf_paiement.class.php +++ b/htdocs/core/modules/rapport/pdf_paiement.class.php @@ -42,6 +42,7 @@ class pdf_paiement global $langs,$conf; $langs->load("bills"); $langs->load("compta"); + $langs->load("main"); $this->db = $db; $this->description = $langs->transnoentities("ListOfCustomerPayments"); @@ -77,6 +78,8 @@ class pdf_paiement $this->posxinvoiceamount-=10; $this->posxpaymentamount-=20; } + // which type of document will be generated: clients (client) or providers (fourn) invoices + $this->doc_type = "client"; } @@ -105,7 +108,6 @@ class pdf_paiement $this->month=$month; $this->year=$year; - $dir=$_dir.'/'.$year; if (! is_dir($dir)) @@ -120,7 +122,17 @@ class pdf_paiement $month = sprintf("%02d",$month); $year = sprintf("%04d",$year); + $file = $dir . "/payments-".$year."-".$month.".pdf"; + switch ($this->doc_type) { + case "client": + $file = $dir . "/payments-".$year."-".$month.".pdf"; + break; + case "fourn": + $file = $dir . "/supplier_payments-".$year."-".$month.".pdf"; + break; + } + // Add pdfgeneration hook if (! is_object($hookmanager)) @@ -148,7 +160,14 @@ class pdf_paiement // count number of lines of payment $sql = "SELECT p.rowid as prowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p"; + switch ($this->doc_type) { + case "client": + $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p"; + break; + case "fourn": + $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p"; + break; + } $sql.= " WHERE p.datep BETWEEN '".$this->db->idate(dol_get_first_day($year,$month))."' AND '".$this->db->idate(dol_get_last_day($year,$month))."'"; $sql.= " AND p.entity = " . $conf->entity; $result = $this->db->query($sql); @@ -158,35 +177,72 @@ class pdf_paiement } // number of bill - $sql = "SELECT p.datep as dp, f.facnumber"; - //$sql .= ", c.libelle as paiement_type, p.num_paiement"; - $sql.= ", c.code as paiement_code, p.num_paiement"; - $sql.= ", p.amount as paiement_amount, f.total_ttc as facture_amount"; - $sql.= ", pf.amount as pf_amount"; - if (! empty($conf->banque->enabled)) - $sql.= ", ba.ref as bankaccount"; - $sql.= ", p.rowid as prowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."c_paiement as c, ".MAIN_DB_PREFIX."paiement_facture as pf,"; - if (! empty($conf->banque->enabled)) - $sql.= " ".MAIN_DB_PREFIX."bank as b, ".MAIN_DB_PREFIX."bank_account as ba,"; - $sql.= " ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir && ! $socid) - { - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + switch ($this->doc_type) { + case "client": + $sql = "SELECT p.datep as dp, f.facnumber"; + //$sql .= ", c.libelle as paiement_type, p.num_paiement"; + $sql.= ", c.code as paiement_code, p.num_paiement"; + $sql.= ", p.amount as paiement_amount, f.total_ttc as facture_amount"; + $sql.= ", pf.amount as pf_amount"; + if (! empty($conf->banque->enabled)) + $sql.= ", ba.ref as bankaccount"; + $sql.= ", p.rowid as prowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."facture as f,"; + $sql.= " ".MAIN_DB_PREFIX."c_paiement as c, ".MAIN_DB_PREFIX."paiement_facture as pf,"; + if (! empty($conf->banque->enabled)) + $sql.= " ".MAIN_DB_PREFIX."bank as b, ".MAIN_DB_PREFIX."bank_account as ba,"; + $sql.= " ".MAIN_DB_PREFIX."societe as s"; + if (! $user->rights->societe->client->voir && ! $socid) + { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } + $sql.= " WHERE f.fk_soc = s.rowid AND pf.fk_facture = f.rowid AND pf.fk_paiement = p.rowid"; + if (! empty($conf->banque->enabled)) + $sql.= " AND p.fk_bank = b.rowid AND b.fk_account = ba.rowid "; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND p.fk_paiement = c.id "; + $sql.= " AND c.entity = " . getEntity('c_paiement'); + $sql.= " AND p.datep BETWEEN '".$this->db->idate(dol_get_first_day($year,$month))."' AND '".$this->db->idate(dol_get_last_day($year,$month))."'"; + if (! $user->rights->societe->client->voir && ! $socid) + { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + } + if (! empty($socid)) $sql .= " AND s.rowid = ".$socid; + $sql.= " ORDER BY p.datep ASC, pf.fk_paiement ASC"; + break; + case "fourn": + $sql = "SELECT p.datep as dp, f.ref as facnumber"; + //$sql .= ", c.libelle as paiement_type, p.num_paiement"; + $sql.= ", c.code as paiement_code, p.num_paiement"; + $sql.= ", p.amount as paiement_amount, f.total_ttc as facture_amount"; + $sql.= ", pf.amount as pf_amount"; + if (! empty($conf->banque->enabled)) + $sql.= ", ba.ref as bankaccount"; + $sql.= ", p.rowid as prowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p, ".MAIN_DB_PREFIX."facture_fourn as f,"; + $sql.= " ".MAIN_DB_PREFIX."c_paiement as c, ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf,"; + if (! empty($conf->banque->enabled)) + $sql.= " ".MAIN_DB_PREFIX."bank as b, ".MAIN_DB_PREFIX."bank_account as ba,"; + $sql.= " ".MAIN_DB_PREFIX."societe as s"; + if (! $user->rights->societe->client->voir && ! $socid) + { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } + $sql.= " WHERE f.fk_soc = s.rowid AND pf.fk_facturefourn = f.rowid AND pf.fk_paiementfourn = p.rowid"; + if (! empty($conf->banque->enabled)) + $sql.= " AND p.fk_bank = b.rowid AND b.fk_account = ba.rowid "; + $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND p.fk_paiement = c.id "; + $sql.= " AND c.entity = " . getEntity('c_paiement'); + $sql.= " AND p.datep BETWEEN '".$this->db->idate(dol_get_first_day($year,$month))."' AND '".$this->db->idate(dol_get_last_day($year,$month))."'"; + if (! $user->rights->societe->client->voir && ! $socid) + { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + } + if (! empty($socid)) $sql .= " AND s.rowid = ".$socid; + $sql.= " ORDER BY p.datep ASC, pf.fk_paiementfourn ASC"; + break; } - $sql.= " WHERE f.fk_soc = s.rowid AND pf.fk_facture = f.rowid AND pf.fk_paiement = p.rowid"; - if (! empty($conf->banque->enabled)) - $sql.= " AND p.fk_bank = b.rowid AND b.fk_account = ba.rowid "; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND p.fk_paiement = c.id "; - $sql.= " AND p.datep BETWEEN '".$this->db->idate(dol_get_first_day($year,$month))."' AND '".$this->db->idate(dol_get_last_day($year,$month))."'"; - if (! $user->rights->societe->client->voir && ! $socid) - { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - } - if (! empty($socid)) $sql .= " AND s.rowid = ".$socid; - $sql.= " ORDER BY p.datep ASC, pf.fk_paiement ASC"; dol_syslog(get_class($this)."::write_file", LOG_DEBUG); $result = $this->db->query($sql); @@ -199,7 +255,7 @@ class pdf_paiement while ($i < $num) { $objp = $this->db->fetch_object($result); - + $lines[$i][0] = $objp->facnumber; $lines[$i][1] = dol_print_date($this->db->jdate($objp->dp),"day",false,$outputlangs,true); @@ -210,6 +266,7 @@ class pdf_paiement $lines[$i][6] = price($objp->pf_amount); $lines[$i][7] = $objp->prowid; $lines[$i][8] = $objp->bankaccount; + $lines[$i][9] = $objp->paiement_amount; $i++; } } @@ -275,9 +332,9 @@ class pdf_paiement if (! empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); - + $this->result = array('fullpath'=>$file); - + return 1; } @@ -300,7 +357,14 @@ class pdf_paiement $default_font_size = pdf_getPDFFontSize($outputlangs); $title=$conf->global->MAIN_INFO_SOCIETE_NOM; - $title.=' - '.$outputlangs->transnoentities("ListOfCustomerPayments"); + switch($this->doc_type) { + case "client": + $title.=' - '.$outputlangs->transnoentities("ListOfCustomerPayments"); + break; + case "fourn": + $title.=' - '.$outputlangs->transnoentities("ListOfSupplierPayments"); + break; + } $title.=' - '.dol_print_date(dol_mktime(0,0,0,$this->month,1,$this->year),"%B %Y",false,$outputlangs,true); $pdf->SetFont('','B',$default_font_size + 1); $pdf->SetXY($this->marge_gauche,10); @@ -357,10 +421,13 @@ class pdf_paiement */ function Body(&$pdf, $page, $lines, $outputlangs) { + global $langs; $default_font_size = pdf_getPDFFontSize($outputlangs); $pdf->SetFont('','', $default_font_size - 1); $oldprowid = 0; + $total_page = 0; + $total = 0; $pdf->SetFillColor(220,220,220); $yp = 0; $numlines=count($lines); @@ -377,13 +444,17 @@ class pdf_paiement } if ($oldprowid <> $lines[$j][7]) { - if ($yp > $this->tab_height -10) + if ($yp > $this->tab_height -15) { + $pdf->SetXY($this->posxpaymentamount, $this->tab_top + 10 + $yp); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxpaymentamount, $this->line_height, $langs->transnoentities('SubTotal')." : ".price($total_page), 0, 'R', 0); $page++; $pdf->AddPage(); $this->_pagehead($pdf, $page, 0, $outputlangs); $pdf->SetFont('','', $default_font_size - 1); $yp = 0; + $total += $total_page; + $total_page = 0; } $pdf->SetXY($this->posxdate - 1, $this->tab_top + 10 + $yp); @@ -398,11 +469,12 @@ class pdf_paiement $pdf->SetXY($this->posxpaymentamount, $this->tab_top + 10 + $yp); $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxpaymentamount, $this->line_height, $lines[$j][4], 0, 'R', 1); $yp = $yp + 5; + $total_page += $lines[$j][9]; } // Invoice number $pdf->SetXY($this->posxinvoice, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxinvoiceamount - $this->posxbankaccount, $this->line_height, $lines[$j][0], 0, 'L', 0); + $pdf->MultiCell($this->posxinvoice - $this->posxbankaccount, $this->line_height, $lines[$j][0], 0, 'L', 0); // BankAccount $pdf->SetXY($this->posxbankaccount, $this->tab_top + 10 + $yp); @@ -422,6 +494,9 @@ class pdf_paiement $oldprowid = $lines[$j][7]; } } + $total += $total_page; + $pdf->SetXY($this->posxpaymentamount, $this->tab_top + 10 + $yp); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxpaymentamount, $this->line_height, $langs->transnoentities('Total')." : ".price($total), 0, 'R', 0); } } diff --git a/htdocs/core/modules/rapport/pdf_paiement_fourn.class.php b/htdocs/core/modules/rapport/pdf_paiement_fourn.class.php index 108b3bd6ce6..0b823e0419e 100644 --- a/htdocs/core/modules/rapport/pdf_paiement_fourn.class.php +++ b/htdocs/core/modules/rapport/pdf_paiement_fourn.class.php @@ -23,12 +23,12 @@ */ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - +require_once DOL_DOCUMENT_ROOT.'/core/modules/rapport/pdf_paiement.class.php'; /** * Classe permettant de generer les rapports de paiement */ -class pdf_paiement_fourn +class pdf_paiement_fourn extends pdf_paiement { /** * Constructor @@ -37,389 +37,7 @@ class pdf_paiement_fourn */ function __construct($db) { - global $langs,$conf; - $langs->load("bills"); - $langs->load("compta"); - - $this->db = $db; - $this->description = $langs->transnoentities("ListOfCustomerPayments"); - - // Dimension page pour format A4 - $this->type = 'pdf'; - $formatarray=pdf_getFormat(); - $this->page_largeur = $formatarray['width']; - $this->page_hauteur = $formatarray['height']; - $this->format = array($this->page_largeur,$this->page_hauteur); - $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10; - $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10; - $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10; - $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10; - - $this->tab_top = 30; - - $this->line_height = 5; - $this->line_per_page = 40; - $this->tab_height = $this->page_hauteur - $this->marge_haute - $this->marge_basse - $this->tab_top - 5; // must be > $this->line_height * $this->line_per_page and < $this->page_hauteur - $this->marge_haute - $this->marge_basse - $this->tab_top - 5; - - $this->posxdate=$this->marge_gauche+2; - $this->posxpaymenttype=42; - $this->posxinvoice=82; - $this->posxbankaccount=110; - $this->posxinvoiceamount=132; - $this->posxpaymentamount=162; - if ($this->page_largeur < 210) // To work with US executive format - { - $this->line_per_page = 35; - $this->posxpaymenttype-=10; - $this->posxinvoice-=0; - $this->posxinvoiceamount-=10; - $this->posxpaymentamount-=20; - } - - } - - - /** - * Fonction generant la rapport sur le disque - * - * @param string $_dir repertoire - * @param int $month mois du rapport - * @param int $year annee du rapport - * @param string $outputlangs Lang output object - * @return int <0 if KO, >0 if OK - */ - function write_file($_dir, $month, $year, $outputlangs) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - global $conf, $hookmanager, $langs, $user; - - $socid=0; - if ($user->societe_id) $socid=$user->societe_id; - - if (! is_object($outputlangs)) $outputlangs=$langs; - // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1'; - - $this->month=$month; - $this->year=$year; - - $dir=$_dir.'/'.$year; - - if (! is_dir($dir)) - { - $result=dol_mkdir($dir); - if ($result < 0) - { - $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir); - return -1; - } - } - - $month = sprintf("%02d",$month); - $year = sprintf("%04d",$year); - $file = $dir . "/supplier_payments-".$year."-".$month.".pdf"; - - // Add pdfgeneration hook - if (! is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); - } - $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'outputlangs'=>$outputlangs); - global $action; - $reshook=$hookmanager->executeHooks('beforePDFCreation',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - - $pdf=pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - - if (class_exists('TCPDF')) - { - $pdf->setPrintHeader(false); - $pdf->setPrintFooter(false); - } - $pdf->SetFont(pdf_getPDFFont($outputlangs)); - - $num=0; - $lines=array(); - - // count number of lines of payment - $sql = "SELECT p.rowid as prowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p"; - $sql.= " WHERE p.datep BETWEEN '".$this->db->idate(dol_get_first_day($year,$month))."' AND '".$this->db->idate(dol_get_last_day($year,$month))."'"; - $sql.= " AND p.entity = " . $conf->entity; - $result = $this->db->query($sql); - if ($result) - { - $numpaiement = $this->db->num_rows($result); - } - - // number of bill - $sql = "SELECT p.datep as dp, f.ref"; - //$sql .= ", c.libelle as paiement_type, p.num_paiement"; - $sql.= ", c.code as paiement_code, p.num_paiement"; - $sql.= ", p.amount as paiement_amount, f.total_ttc as facture_amount"; - $sql.= ", pf.amount as pf_amount"; - if (! empty($conf->banque->enabled)) - $sql.= ", ba.ref as bankaccount"; - $sql.= ", p.rowid as prowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn as p, ".MAIN_DB_PREFIX."facture_fourn as f,"; - $sql.= " ".MAIN_DB_PREFIX."c_paiement as c, ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf,"; - if (! empty($conf->banque->enabled)) - $sql.= " ".MAIN_DB_PREFIX."bank as b, ".MAIN_DB_PREFIX."bank_account as ba,"; - $sql.= " ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir && ! $socid) - { - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - } - $sql.= " WHERE f.fk_soc = s.rowid AND pf.fk_facturefourn = f.rowid AND pf.fk_paiementfourn = p.rowid"; - if (! empty($conf->banque->enabled)) - $sql.= " AND p.fk_bank = b.rowid AND b.fk_account = ba.rowid "; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND p.fk_paiement = c.id "; - $sql.= " AND p.datep BETWEEN '".$this->db->idate(dol_get_first_day($year,$month))."' AND '".$this->db->idate(dol_get_last_day($year,$month))."'"; - if (! $user->rights->societe->client->voir && ! $socid) - { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - } - if (! empty($socid)) $sql .= " AND s.rowid = ".$socid; - $sql.= " ORDER BY p.datep ASC, pf.fk_paiementfourn ASC"; - - dol_syslog(get_class($this)."::write_file", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - $var=True; - - while ($i < $num) - { - $objp = $this->db->fetch_object($result); - - - $lines[$i][0] = $objp->ref; - $lines[$i][1] = dol_print_date($this->db->jdate($objp->dp),"day",false,$outputlangs,true); - $lines[$i][2] = $langs->transnoentities("PaymentTypeShort".$objp->paiement_code); - $lines[$i][3] = $objp->num_paiement; - $lines[$i][4] = price($objp->paiement_amount); - $lines[$i][5] = price($objp->facture_amount); - $lines[$i][6] = price($objp->pf_amount); - $lines[$i][7] = $objp->prowid; - $lines[$i][8] = $objp->bankaccount; - $i++; - } - } - else - { - dol_print_error($this->db); - } - - $pages = intval(($num + $numpaiement) / $this->line_per_page); - - if ((($num + $numpaiement) % $this->line_per_page)>0) - { - $pages++; - } - - if ($pages == 0) - { - // force to build at least one page if report has no line - $pages = 1; - } - - $pdf->Open(); - $pagenb=0; - $pdf->SetDrawColor(128,128,128); - - $pdf->SetTitle($outputlangs->transnoentities("Payments")); - $pdf->SetSubject($outputlangs->transnoentities("Payments")); - $pdf->SetCreator("Dolibarr ".DOL_VERSION); - $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); - //$pdf->SetKeyWords(); - if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right - $pdf->SetAutoPageBreak(1,0); - - // New page - $pdf->AddPage(); - $pagenb++; - $this->_pagehead($pdf, $pagenb, 1, $outputlangs); - $pdf->SetFont('','', 9); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 - $pdf->SetTextColor(0,0,0); - - - $this->Body($pdf, 1, $lines, $outputlangs); - - if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages(); - - $pdf->Close(); - - $pdf->Output($file,'F'); - - // Add pdfgeneration hook - if (! is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); - } - $hookmanager->initHooks(array('pdfgeneration')); - $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs); - global $action; - $reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - - if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); - - $this->result = array('fullpath'=>$file); - - return 1; - } - - /** - * Show top header of page. - * - * @param PDF $pdf Object PDF - * @param int $page Object to show - * @param int $showaddress 0=no, 1=yes - * @param Translate $outputlangs Object lang for output - * @return void - */ - function _pagehead(&$pdf, $page, $showaddress, $outputlangs) - { - global $langs; - - // Do not add the BACKGROUND as this is a report - //pdf_pagehead($pdf,$outputlangs,$this->page_hauteur); - - $default_font_size = pdf_getPDFFontSize($outputlangs); - - $title=$conf->global->MAIN_INFO_SOCIETE_NOM; - $title.=' - '.$outputlangs->transnoentities("ListOfSupplierPayments"); - $title.=' - '.dol_print_date(dol_mktime(0,0,0,$this->month,1,$this->year),"%B %Y",false,$outputlangs,true); - $pdf->SetFont('','B',$default_font_size + 1); - $pdf->SetXY($this->marge_gauche,10); - $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->marge_gauche, 2, $title, 0, 'C'); - - $pdf->SetFont('','',$default_font_size); - - $pdf->SetXY($this->posxdate, 16); - $pdf->MultiCell(80, 2, $outputlangs->transnoentities("DateBuild")." : ".dol_print_date(time(),"day",false,$outputlangs,true), 0, 'L'); - - $pdf->SetXY($this->posxdate+100, 16); - $pdf->MultiCell(80, 2, $outputlangs->transnoentities("Page")." : ".$page, 0, 'R'); - - - // Title line - $pdf->SetXY($this->posxdate, $this->tab_top+2); - $pdf->MultiCell($this->posxpaymenttype - $this->posxdate, 2, 'Date'); - - $pdf->line($this->posxpaymenttype - 1, $this->tab_top, $this->posxpaymenttype - 1, $this->tab_top + $this->tab_height + 10); - $pdf->SetXY($this->posxpaymenttype, $this->tab_top+2); - $pdf->MultiCell($this->posxinvoice - $this->posxpaymenttype, 2, $outputlangs->transnoentities("PaymentMode"), 0, 'L'); - - $pdf->line($this->posxinvoice - 1, $this->tab_top, $this->posxinvoice - 1, $this->tab_top + $this->tab_height + 10); - $pdf->SetXY($this->posxinvoice, $this->tab_top+2); - $pdf->MultiCell($this->posxbankaccount - $this->posxinvoice, 2, $outputlangs->transnoentities("Invoice"), 0, 'L'); - - $pdf->line($this->posxbankaccount - 1, $this->tab_top, $this->posxbankaccount - 1, $this->tab_top + $this->tab_height + 10); - $pdf->SetXY($this->posxbankaccount, $this->tab_top+2); - $pdf->MultiCell($this->posxinvoiceamount - $this->posxbankaccount, 2, $outputlangs->transnoentities("Account"), 0, 'L'); - - - $pdf->line($this->posxinvoiceamount - 1, $this->tab_top, $this->posxinvoiceamount - 1, $this->tab_top + $this->tab_height + 10); - $pdf->SetXY($this->posxinvoiceamount, $this->tab_top+2); - $pdf->MultiCell($this->posxpaymentamount - $this->posxinvoiceamount - 1, 2, $outputlangs->transnoentities("AmountInvoice"), 0, 'R'); - - $pdf->line($this->posxpaymentamount - 1, $this->tab_top, $this->posxpaymentamount - 1, $this->tab_top + $this->tab_height + 10); - $pdf->SetXY($this->posxpaymentamount, $this->tab_top+2); - $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxpaymentamount - 1, 2, $outputlangs->transnoentities("AmountPayment"), 0, 'R'); - - $pdf->line($this->marge_gauche, $this->tab_top + 10, $this->page_largeur - $this->marge_droite, $this->tab_top + 10); - - $pdf->Rect($this->marge_gauche, $this->tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $this->tab_height + 10); - } - - - /** - * Output body - * - * @param PDF $pdf PDF object - * @param string $page Page - * @param array $lines Array of lines - * @param Translate $outputlangs Object langs - * @return void - */ - function Body(&$pdf, $page, $lines, $outputlangs) - { - $default_font_size = pdf_getPDFFontSize($outputlangs); - - $pdf->SetFont('','', $default_font_size - 1); - $oldprowid = 0; - $pdf->SetFillColor(220,220,220); - $yp = 0; - $numlines=count($lines); - for ($j = 0 ; $j < $numlines ; $j++) - { - $i = $j; - if ($yp > $this->tab_height -5) - { - $page++; - $pdf->AddPage(); - $this->_pagehead($pdf, $page, 0, $outputlangs); - $pdf->SetFont('','', $default_font_size - 1); - $yp = 0; - } - if ($oldprowid <> $lines[$j][7]) - { - if ($yp > $this->tab_height -10) - { - $page++; - $pdf->AddPage(); - $this->_pagehead($pdf, $page, 0, $outputlangs); - $pdf->SetFont('','', $default_font_size - 1); - $yp = 0; - } - - $pdf->SetXY($this->posxdate - 1, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxpaymenttype - $this->posxdate + 1, $this->line_height, $lines[$j][1], 0, 'L', 1); - - $pdf->SetXY($this->posxpaymenttype, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxinvoiceamount - $this->posxpaymenttype, $this->line_height, $lines[$j][2].' '.$lines[$j][3], 0, 'L', 1); - - $pdf->SetXY($this->posxinvoiceamount, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxpaymentamount- $this->posxinvoiceamount, $this->line_height, '', 0, 'R', 1); - - $pdf->SetXY($this->posxpaymentamount, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxpaymentamount, $this->line_height, $lines[$j][4], 0, 'R', 1); - $yp = $yp + 5; - } - - // Invoice number - $pdf->SetXY($this->posxinvoice, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxinvoiceamount - $this->posxbankaccount, $this->line_height, $lines[$j][0], 0, 'L', 0); - - // BankAccount - $pdf->SetXY($this->posxbankaccount, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxbankaccount - $this->posxdate, $this->line_height, $lines[$j][8], 0, 'L', 0); - - // Invoice amount - $pdf->SetXY($this->posxinvoiceamount, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->posxpaymentamount- $this->posxinvoiceamount - 1, $this->line_height, $lines[$j][5], 0, 'R', 0); - - // Payment amount - $pdf->SetXY($this->posxpaymentamount, $this->tab_top + 10 + $yp); - $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxpaymentamount, $this->line_height, $lines[$j][6], 0, 'R', 0); - $yp = $yp + 5; - - if ($oldprowid <> $lines[$j][7]) - { - $oldprowid = $lines[$j][7]; - } - } + parent::__construct($db); + $this->doc_type = "fourn"; } } - diff --git a/htdocs/core/modules/security/generate/modGeneratePassPerso.class.php b/htdocs/core/modules/security/generate/modGeneratePassPerso.class.php index af08ae53392..96041bcac2c 100644 --- a/htdocs/core/modules/security/generate/modGeneratePassPerso.class.php +++ b/htdocs/core/modules/security/generate/modGeneratePassPerso.class.php @@ -1,6 +1,7 @@ - * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> +/* Copyright (C) 2006-2011 Laurent Destailleur + * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> + * Copyright (C) 2017 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -98,7 +99,10 @@ class modGeneratePassPerso extends ModeleGenPassword $this->Spe = str_replace($this->Ambi,"",$this->Spe); } - $this->All = str_shuffle($this->Maj. $this->Min. $this->Nb. $this->Spe); + $pattern = $this->Min . (! empty($this->NbMaj)?$this->Maj:'') . (! empty($this->NbNum)?$this->Nb:'') . (! empty($this->NbSpe)?$this->Spe:''); + $this->All = str_shuffle($pattern); + + //$this->All = str_shuffle($this->Maj. $this->Min. $this->Nb. $this->Spe); //$this->All = $this->Maj. $this->Min. $this->Nb. $this->Spe; //$this->All = $this->Spe; diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php index b03f6348ebb..6f36c643ccd 100644 --- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php +++ b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php @@ -157,7 +157,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $outputlangs->load("bills"); $outputlangs->load("products"); - if ($conf->fournisseur->dir_output.'/facture') + if ($conf->fournisseur->facture->dir_output) { $object->fetch_thirdparty(); @@ -540,7 +540,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - + return 1; // Pas d'erreur } else @@ -933,7 +933,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices $sql = "SELECT p.datep as date, p.fk_paiement as type, p.num_paiement as num, pf.amount as amount, pf.multicurrency_amount,"; $sql.= " cp.code"; $sql.= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf, ".MAIN_DB_PREFIX."paiementfourn as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON p.fk_paiement = cp.id AND cp.entity = " . getEntity('c_paiement'); $sql.= " WHERE pf.fk_paiementfourn = p.rowid and pf.fk_facturefourn = ".$object->id; $sql.= " ORDER BY p.datep"; $resql=$this->db->query($sql); diff --git a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php index 7907ea741f9..07a9740e2dc 100644 --- a/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php +++ b/htdocs/core/modules/supplier_order/pdf/pdf_muscadet.modules.php @@ -168,7 +168,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $outputlangs->load("orders"); $nblignes = count($object->lines); - + // Loop on each lines to detect if there is at least one image to show $realpatharray=array(); if (! empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE)) @@ -190,7 +190,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $pdir = get_exdir(0,2,0,0,$objphoto,'product') . dol_sanitizeFileName($objphoto->ref).'/'; $dir = $conf->product->dir_output.'/'.$pdir; } - + $realpath=''; foreach ($objphoto->liste_photos($dir,1) as $key => $obj) { @@ -205,7 +205,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders } if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; - if ($conf->fournisseur->dir_output.'/commande') + if ($conf->fournisseur->commande->dir_output) { $object->fetch_thirdparty(); @@ -412,11 +412,11 @@ class pdf_muscadet extends ModelePDFSuppliersOrders $showpricebeforepagebreak=1; $pdf->startTransaction(); - if ($posYAfterImage > 0) + if ($posYAfterImage > 0) { $descWidth = $this->posxpicture-$curX; - } - else + } + else { $descWidth = $this->posxtva-$curX; } @@ -639,7 +639,7 @@ class pdf_muscadet extends ModelePDFSuppliersOrders @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - + return 1; // Pas d'erreur } else diff --git a/htdocs/core/photos_resize.php b/htdocs/core/photos_resize.php index 69056ff02be..fcedc2a4e11 100644 --- a/htdocs/core/photos_resize.php +++ b/htdocs/core/photos_resize.php @@ -170,7 +170,7 @@ if ($action == 'confirm_resize' && (isset($_POST["file"]) != "") && (isset($_POS { $fullpath=$dir."/".$original_file; $result=dol_imageResizeOrCrop($fullpath,0,$_POST['sizex'],$_POST['sizey']); - + if ($result == $fullpath) { $object->addThumbs($fullpath); @@ -178,7 +178,7 @@ if ($action == 'confirm_resize' && (isset($_POST["file"]) != "") && (isset($_POS // Update/create database for file $fullpath $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $fullpath); $rel_filename = preg_replace('/^[\\/]/','',$rel_filename); - + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile=new EcmFiles($db); $result = $ecmfile->fetch(0, '', $rel_filename); @@ -188,7 +188,7 @@ if ($action == 'confirm_resize' && (isset($_POST["file"]) != "") && (isset($_POS $rel_dir = dirname($rel_filename); $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - + $ecmfile->label = md5_file(dol_osencode($fullpath)); $result = $ecmfile->update($user); } @@ -198,7 +198,7 @@ if ($action == 'confirm_resize' && (isset($_POST["file"]) != "") && (isset($_POS $rel_dir = dirname($rel_filename); $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - + $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; $ecmfile->label = md5_file(dol_osencode($fullpath)); // $fullpath is a full path to file @@ -213,7 +213,7 @@ if ($action == 'confirm_resize' && (isset($_POST["file"]) != "") && (isset($_POS } $result = $ecmfile->create($user); } - + if ($backtourl) { header("Location: ".$backtourl); @@ -246,7 +246,7 @@ if ($action == 'confirm_crop') // Update/create database for file $fullpath $rel_filename = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $fullpath); $rel_filename = preg_replace('/^[\\/]/','',$rel_filename); - + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile=new EcmFiles($db); $result = $ecmfile->fetch(0, '', $rel_filename); @@ -256,7 +256,7 @@ if ($action == 'confirm_crop') $rel_dir = dirname($rel_filename); $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - + $ecmfile->label = md5_file(dol_osencode($fullpath)); $result = $ecmfile->update($user); } @@ -266,7 +266,7 @@ if ($action == 'confirm_crop') $rel_dir = dirname($rel_filename); $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir); $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir); - + $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; $ecmfile->label = md5_file(dol_osencode($fullpath)); // $fullpath is a full path to file @@ -281,7 +281,7 @@ if ($action == 'confirm_crop') } $result = $ecmfile->create($user); } - + if ($backtourl) { header("Location: ".$backtourl); @@ -311,7 +311,7 @@ llxHeader($head, $langs->trans("Image"), '', '', 0, 0, array('/includes/jquery/p print load_fiche_titre($langs->trans("ImageEditor")); -$infoarray=dol_getImageSize($dir."/".GETPOST("file")); +$infoarray=dol_getImageSize($dir."/".GETPOST("file",'alpha')); $height=$infoarray['height']; $width=$infoarray['width']; print $langs->trans("CurrentInformationOnImage").': '; @@ -373,7 +373,7 @@ if (! empty($conf->use_javascript_ajax)) print $langs->trans("DefineNewAreaToPick").'...
          '; print '
          '; print '
          '; - print ''; + print ''; print '
          '; print '

          '; print '
          diff --git a/htdocs/core/tpl/admin_extrafields_add.tpl.php b/htdocs/core/tpl/admin_extrafields_add.tpl.php index 6c5f563e106..e04f4e0cb92 100644 --- a/htdocs/core/tpl/admin_extrafields_add.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_add.tpl.php @@ -26,6 +26,8 @@ * $elementtype */ +$langs->load("modulebuilder"); + ?> @@ -101,13 +103,13 @@ if (type == 'separate') { - required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.val('').prop('disabled', true); + required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.removeAttr('checked').prop('disabled', true); jQuery('#size, #default_value').val('').prop('disabled', true); } else { default_value.removeAttr('disabled'); - required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.val('').removeAttr('disabled'); + required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.removeAttr('disabled'); } } init_typeoffields(''); @@ -178,12 +180,9 @@ multicompany->enabled) { ?> trans("AllEntities"); ?>> -global->MAIN_FEATURES_LEVEL >= 2) { ?> -trans("ByDefaultInList"); ?> -trans("FeatureNotYetSupported")); ?> -> - +textwithpicto($langs->trans("ByDefaultInList"), $langs->trans("VisibleDesc")); ?> + diff --git a/htdocs/core/tpl/admin_extrafields_edit.tpl.php b/htdocs/core/tpl/admin_extrafields_edit.tpl.php index 85cfe510df8..def07fa432f 100644 --- a/htdocs/core/tpl/admin_extrafields_edit.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_edit.tpl.php @@ -25,6 +25,8 @@ * $elementtype */ +$langs->load("modulebuilder"); + ?> @@ -96,13 +98,13 @@ if (type == 'separate') { - required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.val('').prop('disabled', true); + required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.removeAttr('checked').prop('disabled', true); jQuery('#size, #default_value').val('').prop('disabled', true); } else { default_value.removeAttr('disabled'); - required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.val('').removeAttr('disabled'); + required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.removeAttr('disabled'); } } init_typeoffields(jQuery("#type").val()); @@ -238,11 +240,8 @@ else trans("AllEntities"); ?>> -global->MAIN_FEATURES_LEVEL >= 2) { ?> -trans("ByDefaultInList"); ?> -trans("FeatureNotYetSupported")); ?> -> - +textwithpicto($langs->trans("ByDefaultInList"), $langs->trans("VisibleDesc")); ?> + diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index f989ce448b5..29d57b8463c 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -1,6 +1,6 @@ - * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2012-2017 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,6 +22,9 @@ * $extrafield * $elementtype */ + +$langs->load("modulebuilder"); + ?> @@ -41,6 +44,7 @@ print ''.$langs->trans("Position"); print ''; print ''; print ''.$langs->trans("Label").''; +print ''.$langs->trans("TranslationString").''; print ''.$langs->trans("AttributeCode").''; print ''.$langs->trans("Type").''; print ''.$langs->trans("Size").''; @@ -48,6 +52,7 @@ print ''.$langs->trans("Unique").''; print ''.$langs->trans("ComputedFormula").''; print ''.$langs->trans("Required").''; print ''.$langs->trans("AlwaysEditable").''; +print ''.$form->textwithpicto($langs->trans("Visible"), $langs->trans("VisibleDesc")).''; if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''.$langs->trans("Hidden").''; if ($conf->multicompany->enabled) { print ''.$langs->trans("Entities").''; @@ -55,40 +60,46 @@ if ($conf->multicompany->enabled) { print ' '; print "\n"; -if (count($extrafields->attribute_type)) +if (count($extrafields->attributes[$elementtype]['type'])) { - foreach($extrafields->attribute_type as $key => $value) - { - - print ''; - print "".$extrafields->attribute_pos[$key]."\n"; - print "".$extrafields->attribute_label[$key]."\n"; - print "".$key."\n"; - print "".$type2label[$extrafields->attribute_type[$key]]."\n"; - print ''.$extrafields->attribute_size[$key]."\n"; - print ''.yn($extrafields->attribute_unique[$key])."\n"; - print ''.dol_trunc($extrafields->attribute_computed[$key], 20)."\n"; - print ''.yn($extrafields->attribute_required[$key])."\n"; - print ''.yn($extrafields->attribute_alwayseditable[$key])."\n"; - if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''.yn($extrafields->attribute_hidden[$key])."\n"; // Add hidden option on not working feature. Why hide if user can't see it. - if ($conf->multicompany->enabled) { - print ''.($extrafields->attribute_entityid[$key]==0?$langs->trans("All"):$extrafields->attribute_entitylabel[$key]).''; - } - print ''.img_edit().''; - print "  ".img_delete()."\n"; - print ""; - } + foreach($extrafields->attributes[$elementtype]['type'] as $key => $value) + { + // Load language if required + if (! empty($extrafields->attributes[$elementtype]['langfile'][$key])) { + $langs->load($extrafields->attributes[$elementtype]['langfile'][$key]); + } + + print ''; + print "".$extrafields->attributes[$elementtype]['pos'][$key]."\n"; + print "".$extrafields->attributes[$elementtype]['label'][$key]."\n"; // We don't translate here, we want admin to know what is the key not translated value + print "".$langs->trans($extrafields->attributes[$elementtype]['label'][$key])."\n"; + print "".$key."\n"; + print "".$type2label[$extrafields->attributes[$elementtype]['type'][$key]]."\n"; + print ''.$extrafields->attributes[$elementtype]['size'][$key]."\n"; + print ''.yn($extrafields->attributes[$elementtype]['unique'][$key])."\n"; + print ''.dol_trunc($extrafields->attributes[$elementtype]['computed'][$key], 20)."\n"; + print ''.yn($extrafields->attributes[$elementtype]['required'][$key])."\n"; + print ''.yn($extrafields->attributes[$elementtype]['alwayseditable'][$key])."\n"; + print ''.$extrafields->attributes[$elementtype]['list'][$key]."\n"; + if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''.yn($extrafields->attributes[$elementtype]['ishidden'][$key])."\n"; // Add hidden option on not working feature. Why hide if user can't see it. + if (! empty($conf->multicompany->enabled)) { + print ''.($extrafields->attributes[$elementtype]['entityid'][$key]==0?$langs->trans("All"):$extrafields->attributes[$elementtype]['entitylabel'][$key]).''; + } + print ''.img_edit().''; + print "  ".img_delete()."\n"; + print ""; + } } else { - $colspan=9; - if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) $colspan++; - - print ''; - print ''; - print $langs->trans("None"); - print ''; - print ''; + $colspan=9; + if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) $colspan++; + + print ''; + print ''; + print $langs->trans("None"); + print ''; + print ''; } print ""; diff --git a/htdocs/core/tpl/bloc_comment.tpl.php b/htdocs/core/tpl/bloc_comment.tpl.php new file mode 100644 index 00000000000..48b0e0c990f --- /dev/null +++ b/htdocs/core/tpl/bloc_comment.tpl.php @@ -0,0 +1,107 @@ +'; +print '
          '; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print ''; + +print ''; +print ''; +print ''; +print ''; +print ''; +print "\n"; + +print ''; + +// Description +print ''; + +print ''; +print '
          '.$langs->trans("Comments").'
          '; + +$desc = GETPOST('comment_description'); + +$doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '100%'); +print $doleditor->Create(1); + +print ''; +print ''; +print '
          '; + +// List of comments +if (!empty($object->comments)) +{ + // Default color for current user + $TColors = array($user->id => array('bgcolor'=>'efefef','color'=>'555')); + $first = true; + foreach($object->comments as $comment) + { + $fk_user = $comment->fk_user_author; + $userstatic->fetch($fk_user); + + if(empty($TColors[$fk_user])) { + $bgcolor = random_color(180,240); + if(!empty($userstatic->color)) { + $bgcolor = $userstatic->color; + } + $color = (colorIsLight($bgcolor))?'555':'fff'; + $TColors[$fk_user] = array('bgcolor'=>$bgcolor,'color'=>$color); + } + print '
          '; + if ($fk_user != $user->id) { + print '
           
          '; + } + + print '
          '; + print '
          '; + if (! empty($user->photo)) + { + print Form::showphoto('userphoto', $userstatic, 80, 0, 0, '', 'small', 0, 1).'
          '; + } + print $langs->trans('User').' : '.$userstatic->getNomUrl().'
          '; + print $langs->trans('Date').' : '.dol_print_date($comment->datec,'dayhoursec'); + print '
          '; // End comment-info + + print '
          '; + print '
          '; + print '
          '; + print $comment->description; + print '
          '; // End comment-description + if(($first && $fk_user == $user->id) || $user->admin == 1) { + print ''; + print img_picto('', 'delete.png'); + print ''; + } + print '
          '; // End comment-table + print '
          '; // End comment-right + print '
          '; // End comment + + if($fk_user == $user->id) { + print '
           
          '; + } + print '
          '; + print '
          '; // end 100p + + $first = false; + } +} + +print '
          '; +print '
          '; diff --git a/htdocs/core/tpl/card_presend.tpl.php b/htdocs/core/tpl/card_presend.tpl.php index e24fbb44f7a..6e653372148 100644 --- a/htdocs/core/tpl/card_presend.tpl.php +++ b/htdocs/core/tpl/card_presend.tpl.php @@ -34,16 +34,19 @@ if ($action == 'presend') $object->fetch_projet(); - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - // - if ($object->element == 'invoice_supplier') + if (! in_array($object->element, array('societe', 'user'))) { - $fileparams = dol_most_recent_file($diroutput . '/' . get_exdir($object->id,2,0,0,$object,$object->element).$ref, preg_quote($ref,'/').'([^\-])+'); - } + $ref = dol_sanitizeFileName($object->ref); + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); + // + if ($object->element == 'invoice_supplier') + { + $fileparams = dol_most_recent_file($diroutput . '/' . get_exdir($object->id,2,0,0,$object,$object->element).$ref, preg_quote($ref,'/').'([^\-])+'); + } - $file = $fileparams['fullname']; + $file = $fileparams['fullname']; + } // Define output language $outputlangs = $langs; @@ -72,16 +75,19 @@ if ($action == 'presend') } // Build document if it not exists - if (! $file || ! is_readable($file)) { - if ($object->element != 'member') - { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); + if (! in_array($object->element, array('societe', 'user'))) + { + if (! $file || ! is_readable($file)) { + if ($object->element != 'member') + { + $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result <= 0) { + dol_print_error($db, $object->error, $object->errors); + exit(); + } + $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); + $file = $fileparams['fullname']; } - $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; } } @@ -106,7 +112,7 @@ if ($action == 'presend') if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'ord'.$object->id); + $formmail->frommail=dolAddEmailTrackId($formmail->frommail, $trackid); } $formmail->withfrom = 1; @@ -123,7 +129,7 @@ if ($action == 'presend') $liste[$key] = $value; } } - elseif ($object->element == 'member') + elseif ($object->element == 'user' || $object->element == 'member') { $liste['thirdparty'] = $object->getFullName($langs)." <".$object->email.">"; } @@ -163,12 +169,15 @@ if ($action == 'presend') $formmail->param['models_id']=GETPOST('modelmailselected','int'); $formmail->param['id'] = $object->id; $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; + $formmail->param['fileinit'] = array($file); // Init list of files - if (GETPOST("mode") == 'init') { + /*if (GETPOST('mode','alpha') == 'init') + { $formmail->clear_attached_files(); + $formmail->add_attached_files($file, basename($file), dol_mimetype($file)); - } + }*/ // Show form print $formmail->get_form(); diff --git a/htdocs/core/tpl/document_actions_post_headers.tpl.php b/htdocs/core/tpl/document_actions_post_headers.tpl.php index e613c479ee0..da1cb9658a0 100644 --- a/htdocs/core/tpl/document_actions_post_headers.tpl.php +++ b/htdocs/core/tpl/document_actions_post_headers.tpl.php @@ -79,7 +79,7 @@ $formfile->form_attach_new_file( ); $disablemove=1; -if ($modulepart == 'produit') $disablemove=0; +if ($modulepart == 'product' || $modulepart == 'produit') $disablemove=0; // Drag and drop for up and down allowed on product // List of document $formfile->list_of_documents( diff --git a/htdocs/core/tpl/extrafields_add.tpl.php b/htdocs/core/tpl/extrafields_add.tpl.php new file mode 100644 index 00000000000..f8be788ae2f --- /dev/null +++ b/htdocs/core/tpl/extrafields_add.tpl.php @@ -0,0 +1,40 @@ + + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $action + * $conf + * $langs + * + * $parameters + * $cols + */ +?> + +executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element]['label'])) { + print $object->showOptionals($extrafields, 'edit'); +} + +?> + \ No newline at end of file diff --git a/htdocs/core/tpl/extrafields_edit.tpl.php b/htdocs/core/tpl/extrafields_edit.tpl.php new file mode 100644 index 00000000000..a2c3bf5771f --- /dev/null +++ b/htdocs/core/tpl/extrafields_edit.tpl.php @@ -0,0 +1,40 @@ + + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $action + * $conf + * $langs + * + * $parameters + * $cols + */ +?> + +executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element]['label'])) { + print $object->showOptionals($extrafields, 'edit'); +} + +?> + \ No newline at end of file diff --git a/htdocs/core/tpl/notes.tpl.php b/htdocs/core/tpl/notes.tpl.php index 45e7dc32697..0d1a0a79339 100644 --- a/htdocs/core/tpl/notes.tpl.php +++ b/htdocs/core/tpl/notes.tpl.php @@ -17,15 +17,15 @@ * along with this program. If not, see . */ -// $permission must be defined by caller. -// $cssclass must be defined by caller. For example cssclass='fieldtitle" +// $permissionnote must be defined by caller. For example $permissionnote=$user->rights->module->create +// $cssclass must be defined by caller. For example $cssclass='fieldtitle" $module = $object->element; $note_public = 'note_public'; $note_private = 'note_private'; $colwidth=(isset($colwidth)?$colwidth:(empty($cssclass)?'25':'')); - -$permission=(isset($permission)?$permission:(isset($user->rights->$module->creer)?$user->rights->$module->creer:0)); // If already defined by caller page +// Set $permission from the $permissionnote var defined on calling page +$permission=(isset($permissionnote)?$permissionnote:(isset($permission)?$permission:(isset($user->rights->$module->create)?$user->rights->$module->create:(isset($user->rights->$module->creer)?$user->rights->$module->creer:0)))); $moreparam=(isset($moreparam)?$moreparam:''); $value_public=$object->note_public; $value_private=$object->note_private; diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index f968fdcbfc7..94c05fd9ffe 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -145,7 +145,7 @@ if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0; tva_tx)) $positiverates.=($positiverates?'/':'').price2num($line->tva_tx); + if (price2num($line->tva_tx)) $positiverates.=($positiverates?'/':'').price2num($line->tva_tx); if (price2num($line->total_localtax1)) $positiverates.=($positiverates?'/':'').price2num($line->localtax1_tx); if (price2num($line->total_localtax2)) $positiverates.=($positiverates?'/':'').price2num($line->localtax2_tx); if (empty($positiverates)) $positiverates='0'; diff --git a/htdocs/core/tpl/originproductline.tpl.php b/htdocs/core/tpl/originproductline.tpl.php index c8cd6674a7a..2efc114cc1d 100644 --- a/htdocs/core/tpl/originproductline.tpl.php +++ b/htdocs/core/tpl/originproductline.tpl.php @@ -19,8 +19,8 @@ ?> -'; +tpl['strike'])?'':' strikefordisabled').'">'; print ''.$this->tpl['label'].''; print ''.$this->tpl['description'].''; print ''.$this->tpl['vat_rate'].''; @@ -29,7 +29,7 @@ if (!empty($conf->multicurrency->enabled)) print ''.$this->tpl['multicurrency_price'].''; print ''.$this->tpl['qty'].''; -if($conf->global->PRODUCT_USE_UNITS) +if($conf->global->PRODUCT_USE_UNITS) print ''.$langs->trans($this->tpl['unit']).''; print ''.$this->tpl['remise_percent'].''; diff --git a/htdocs/core/triggers/interface_20_all_Logevents.class.php b/htdocs/core/triggers/interface_20_all_Logevents.class.php index 466712260c6..c2f15bd336d 100644 --- a/htdocs/core/triggers/interface_20_all_Logevents.class.php +++ b/htdocs/core/triggers/interface_20_all_Logevents.class.php @@ -1,7 +1,7 @@ - * Copyright (C) 2009 Regis Houssin - * Copyright (C) 2014 Marcos García +/* Copyright (C) 2005-2009 Laurent Destailleur + * Copyright (C) 2009-2017 Regis Houssin + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -63,7 +63,7 @@ class InterfaceLogevents extends DolibarrTriggers if ($action == 'USER_LOGIN') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - + $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) $text="(UserLogged,".$object->login.")"; @@ -177,7 +177,7 @@ class InterfaceLogevents extends DolibarrTriggers // Add more information into desc from the context property if (! empty($desc) && ! empty($object->context['audit'])) $desc.=' - '.$object->context['audit']; - + // Add entry in event table include_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php'; diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php index ec1fa9465b5..3c34d0a3ee0 100644 --- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php +++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php @@ -1,10 +1,10 @@ - * Copyright (C) 2009-2011 Regis Houssin - * Copyright (C) 2011-2014 Juanjo Menent - * Copyright (C) 2013 Cedric GROSS - * Copyright (C) 2014 Marcos García - * Copyright (C) 2015 Bahfir Abbes +/* Copyright (C) 2005-2017 Laurent Destailleur + * Copyright (C) 2009-2017 Regis Houssin + * Copyright (C) 2011-2014 Juanjo Menent + * Copyright (C) 2013 Cedric GROSS + * Copyright (C) 2014 Marcos García + * Copyright (C) 2015 Bahfir Abbes * * 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 @@ -635,8 +635,8 @@ class InterfaceActionsAuto extends DolibarrTriggers $langs->load("other"); $langs->load("members"); - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); - $object->actionmsg=$langs->transnoentities("MemberValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberValidatedInDolibarr",$object->getFullName($langs)); + $object->actionmsg=$langs->transnoentities("MemberValidatedInDolibarr",$object->getFullName($langs)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; @@ -648,8 +648,8 @@ class InterfaceActionsAuto extends DolibarrTriggers $langs->load("other"); $langs->load("members"); - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberModifiedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("MemberModifiedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberModifiedInDolibarr",$object->getFullName($langs)); + $object->actionmsg=$langs->transnoentities("MemberModifiedInDolibarr",$object->getFullName($langs)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; @@ -661,8 +661,8 @@ class InterfaceActionsAuto extends DolibarrTriggers $langs->load("other"); $langs->load("members"); - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberSubscriptionAddedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("MemberSubscriptionAddedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberSubscriptionAddedInDolibarr",$object->getFullName($langs)); + $object->actionmsg=$langs->transnoentities("MemberSubscriptionAddedInDolibarr",$object->getFullName($langs)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; $object->actionmsg.="\n".$langs->transnoentities("Amount").': '.$object->last_subscription_amount; @@ -676,8 +676,8 @@ class InterfaceActionsAuto extends DolibarrTriggers $langs->load("other"); $langs->load("members"); - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberResiliatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("MemberResiliatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberResiliatedInDolibarr",$object->getFullName($langs)); + $object->actionmsg=$langs->transnoentities("MemberResiliatedInDolibarr",$object->getFullName($langs)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; @@ -689,8 +689,8 @@ class InterfaceActionsAuto extends DolibarrTriggers $langs->load("other"); $langs->load("members"); - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberDeletedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("MemberDeletedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberDeletedInDolibarr",$object->getFullName($langs)); + $object->actionmsg=$langs->transnoentities("MemberDeletedInDolibarr",$object->getFullName($langs)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; diff --git a/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php b/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php index a906ec821ed..1e9c2c2ec31 100644 --- a/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php +++ b/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php @@ -51,7 +51,8 @@ class InterfaceLdapsynchro extends DolibarrTriggers */ public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { - if (empty($conf->ldap->enabled)) return 0; // Module not active, we do nothing + if (empty($conf->ldap->enabled)) return 0; // Module not active, we do nothing + if (defined('DISABLE_LDAP_SYNCHRO')) return 0; // If constant defined, we do nothing if (! function_exists('ldap_connect')) { @@ -111,8 +112,10 @@ class InterfaceLdapsynchro extends DolibarrTriggers $info=$object->_load_ldap_info(); $dn=$object->_load_ldap_dn($info); + $newrdn=$object->_load_ldap_dn($info,2); + $newparent=$object->_load_ldap_dn($info,1); - $result=$ldap->update($dn,$info,$user,$olddn); + $result=$ldap->update($dn,$info,$user,$olddn,$newrdn,$newparent); } if ($result < 0) $this->error="ErrorLDAP ".$ldap->error; @@ -544,8 +547,10 @@ class InterfaceLdapsynchro extends DolibarrTriggers $info=$object->_load_ldap_info(); $dn=$object->_load_ldap_dn($info); + $newrdn=$object->_load_ldap_dn($info,2); + $newparent=$object->_load_ldap_dn($info,1); - $result=$ldap->update($dn,$info,$user,$olddn); + $result=$ldap->update($dn,$info,$user,$olddn,$newrdn,$newparent); // For member type if (! empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE) && (string) $conf->global->LDAP_MEMBER_TYPE_ACTIVE == '1') diff --git a/htdocs/core/triggers/interface_50_modNotification_Notification.class.php b/htdocs/core/triggers/interface_50_modNotification_Notification.class.php index aaea372ef4a..8698b08a5c3 100644 --- a/htdocs/core/triggers/interface_50_modNotification_Notification.class.php +++ b/htdocs/core/triggers/interface_50_modNotification_Notification.class.php @@ -35,17 +35,18 @@ class InterfaceNotification extends DolibarrTriggers public $version = self::VERSION_DOLIBARR; public $picto = 'email'; - var $listofmanagedevents=array( - 'BILL_VALIDATE', - 'BILL_PAYED', - 'ORDER_VALIDATE', - 'PROPAL_VALIDATE', - 'FICHINTER_VALIDATE', - 'FICHINTER_ADD_CONTACT', - 'ORDER_SUPPLIER_VALIDATE', - 'ORDER_SUPPLIER_APPROVE', - 'ORDER_SUPPLIER_REFUSE', - 'SHIPPING_VALIDATE' + var $listofmanagedevents=array( + 'BILL_VALIDATE', + 'BILL_PAYED', + 'ORDER_VALIDATE', + 'PROPAL_VALIDATE', + 'PROPAL_CLOSE_SIGNED', + 'FICHINTER_VALIDATE', + 'FICHINTER_ADD_CONTACT', + 'ORDER_SUPPLIER_VALIDATE', + 'ORDER_SUPPLIER_APPROVE', + 'ORDER_SUPPLIER_REFUSE', + 'SHIPPING_VALIDATE' ); /** @@ -73,62 +74,62 @@ class InterfaceNotification extends DolibarrTriggers $notify->send($action, $object); return 1; - } + } - /** - * Return list of events managed by notification module - * - * @return array Array of events managed by notification module - */ - function getListOfManagedEvents() - { - global $conf; + /** + * Return list of events managed by notification module + * + * @return array Array of events managed by notification module + */ + function getListOfManagedEvents() + { + global $conf; - $ret=array(); + $ret=array(); - $sql = "SELECT rowid, code, label, description, elementtype"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_action_trigger"; - $sql.= $this->db->order("rang, elementtype, code"); - dol_syslog("getListOfManagedEvents Get list of notifications", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $num=$this->db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj=$this->db->fetch_object($resql); + $sql = "SELECT rowid, code, label, description, elementtype"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_action_trigger"; + $sql.= $this->db->order("rang, elementtype, code"); + dol_syslog("getListOfManagedEvents Get list of notifications", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $num=$this->db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj=$this->db->fetch_object($resql); - $qualified=0; - // Check is this event is supported by notification module - if (in_array($obj->code,$this->listofmanagedevents)) $qualified=1; - // Check if module for this event is active - if ($qualified) - { - //print 'xx'.$obj->code; - $element=$obj->elementtype; + $qualified=0; + // Check is this event is supported by notification module + if (in_array($obj->code,$this->listofmanagedevents)) $qualified=1; + // Check if module for this event is active + if ($qualified) + { + //print 'xx'.$obj->code; + $element=$obj->elementtype; - // Exclude events if related module is disabled - if ($element == 'order_supplier' && empty($conf->fournisseur->enabled)) $qualified=0; - elseif ($element == 'invoice_supplier' && empty($conf->fournisseur->enabled)) $qualified=0; - elseif ($element == 'withdraw' && empty($conf->prelevement->enabled)) $qualified=0; - elseif ($element == 'shipping' && empty($conf->expedition->enabled)) $qualified=0; - elseif ($element == 'member' && empty($conf->adherent->enabled)) $qualified=0; - elseif (! in_array($element,array('order_supplier','invoice_supplier','withdraw','shipping','member')) && empty($conf->$element->enabled)) $qualified=0; - } + // Exclude events if related module is disabled + if ($element == 'order_supplier' && empty($conf->fournisseur->enabled)) $qualified=0; + elseif ($element == 'invoice_supplier' && empty($conf->fournisseur->enabled)) $qualified=0; + elseif ($element == 'withdraw' && empty($conf->prelevement->enabled)) $qualified=0; + elseif ($element == 'shipping' && empty($conf->expedition->enabled)) $qualified=0; + elseif ($element == 'member' && empty($conf->adherent->enabled)) $qualified=0; + elseif (! in_array($element,array('order_supplier','invoice_supplier','withdraw','shipping','member')) && empty($conf->$element->enabled)) $qualified=0; + } - if ($qualified) - { - $ret[]=array('rowid'=>$obj->rowid,'code'=>$obj->code,'label'=>$obj->label,'description'=>$obj->description,'elementtype'=>$obj->elementtype); - } + if ($qualified) + { + $ret[]=array('rowid'=>$obj->rowid,'code'=>$obj->code,'label'=>$obj->label,'description'=>$obj->description,'elementtype'=>$obj->elementtype); + } - $i++; - } - } - else dol_print_error($this->db); + $i++; + } + } + else dol_print_error($this->db); - return $ret; - } + return $ret; + } } diff --git a/htdocs/document.php b/htdocs/document.php index 11017f52cc2..a0b764882f8 100644 --- a/htdocs/document.php +++ b/htdocs/document.php @@ -25,8 +25,9 @@ * \file htdocs/document.php * \brief Wrapper to download data files * \remarks Call of this wrapper is made with URL: - * document.php?modulepart=repfichierconcerne&file=pathrelatifdufichier + * document.php?modulepart=repfichierconcerne&file=relativepathoffile * document.php?modulepart=logs&file=dolibarr.log + * document.php?modulepart=logs&hashp=sharekey */ define('NOTOKENRENEWAL',1); // Disables token renewal diff --git a/htdocs/don/card.php b/htdocs/don/card.php index 02498009cd9..6998b7bdb52 100644 --- a/htdocs/don/card.php +++ b/htdocs/don/card.php @@ -638,6 +638,7 @@ if (! empty($id) && $action != 'edit') $sql.= " AND p.fk_donation = d.rowid"; $sql.= " AND d.entity = ".$conf->entity; $sql.= " AND p.fk_typepayment = c.id"; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " ORDER BY dp"; //print $sql; diff --git a/htdocs/don/class/don.class.php b/htdocs/don/class/don.class.php index 695314bb526..0a683fea355 100644 --- a/htdocs/don/class/don.class.php +++ b/htdocs/don/class/don.class.php @@ -39,7 +39,7 @@ class Don extends CommonObject public $fk_element = 'fk_donation'; protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe var $picto = 'generic'; - + var $date; var $amount; var $societe; @@ -163,7 +163,7 @@ class Don extends CommonObject global $conf, $user,$langs; $now = dol_now(); - + // Charge tableau des id de societe socids $socids = array(); @@ -611,7 +611,7 @@ class Don extends CommonObject $sql.= " c.code as country_code, c.label as country"; $sql.= " FROM ".MAIN_DB_PREFIX."don as d"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = d.fk_projet"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON cp.id = d.fk_payment"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON cp.id = d.fk_payment AND cp.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.fk_country = c.rowid"; if (! empty($id)) { diff --git a/htdocs/don/class/paymentdonation.class.php b/htdocs/don/class/paymentdonation.class.php index 9d478c4d7f5..22fbcd6dab4 100644 --- a/htdocs/don/class/paymentdonation.class.php +++ b/htdocs/don/class/paymentdonation.class.php @@ -32,7 +32,7 @@ class PaymentDonation extends CommonObject public $element='payment_donation'; //!< Id that identify managed objects public $table_element='payment_donation'; //!< Name of table without prefix where object is stored public $picto = 'payment'; - + public $rowid; public $fk_donation; @@ -175,6 +175,7 @@ class PaymentDonation extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."payment_donation as t)"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepayment = pt.id"; + $sql.= " AND pt.entity = " . getEntity('c_paiement'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -443,7 +444,7 @@ class PaymentDonation extends CommonObject { return ''; } - + /** * Renvoi le libelle d'un statut donne * @@ -454,11 +455,11 @@ class PaymentDonation extends CommonObject function LibStatut($statut,$mode=0) { global $langs; - + return ''; } - - + + /** * Initialise an instance with random values. * Used to build previews or test instances. diff --git a/htdocs/ecm/class/ecmfiles.class.php b/htdocs/ecm/class/ecmfiles.class.php index 0035b18d3c7..540c30ec286 100644 --- a/htdocs/ecm/class/ecmfiles.class.php +++ b/htdocs/ecm/class/ecmfiles.class.php @@ -82,14 +82,13 @@ class EcmFiles //extends CommonObject /** * Create object into database * - * @param User $user User that creates - * @param bool $notrigger false=launch triggers after, true=disable triggers - * - * @return int <0 if KO, Id of created object if OK + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK */ public function create(User $user, $notrigger = false) { - global $conf; + global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -141,25 +140,25 @@ class EcmFiles //extends CommonObject if (isset($this->acl)) { $this->acl = trim($this->acl); } - if (empty($this->date_c)) $this->date_c = dol_now(); + if (empty($this->date_c)) $this->date_c = dol_now(); - // If ref not defined - if (empty($ref)) $ref = dol_hash($this->filepath.'/'.$this->filename, 3); + // If ref not defined + $ref = dol_hash($this->filepath.'/'.$this->filename, 3); + if (! empty($this->ref)) $ref=$this->ref; - - $maxposition=0; + $maxposition=0; if (empty($this->position)) // Get max used { - $sql = "SELECT MAX(position) as maxposition FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql.= " WHERE filepath ='".$this->db->escape($this->filepath)."'"; + $sql = "SELECT MAX(position) as maxposition FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql.= " WHERE filepath ='".$this->db->escape($this->filepath)."'"; - $resql = $this->db->query($sql); - if ($resql) - { - $obj = $this->db->fetch_object($resql); - $maxposition = (int) $obj->maxposition; - } - else dol_print_error($this->db); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $maxposition = (int) $obj->maxposition; + } + else dol_print_error($this->db); } $maxposition=$maxposition+1; @@ -218,7 +217,7 @@ class EcmFiles //extends CommonObject if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); - $this->position = $maxposition; + $this->position = $maxposition; if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you @@ -409,7 +408,7 @@ class EcmFiles //extends CommonObject $sql .= $this->db->order($sortfield,$sortorder); } if (!empty($limit)) { - $sql .= ' ' . $this->db->plimit($limit, $offset); + $sql .= ' ' . $this->db->plimit($limit, $offset); } $this->lines = array(); @@ -677,49 +676,49 @@ class EcmFiles //extends CommonObject * * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) * @param string $option On what the link point to - * @param int $notooltip 1=Disable tooltip - * @param int $maxlen Max length of visible user name - * @param string $morecss Add more css on link + * @param int $notooltip 1=Disable tooltip + * @param int $maxlen Max length of visible user name + * @param string $morecss Add more css on link * @return string String with URL */ function getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='') { global $db, $conf, $langs; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips - $result = ''; - $companylink = ''; + $result = ''; + $companylink = ''; - $label = '' . $langs->trans("MyModule") . ''; - $label.= '
          '; - $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + $label = '' . $langs->trans("MyModule") . ''; + $label.= '
          '; + $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; - $url = DOL_URL_ROOT.'/ecm/'.$this->table_name.'_card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/ecm/'.$this->table_name.'_card.php?id='.$this->id; - $linkclose=''; - if (empty($notooltip)) - { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowProject"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; - } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowProject"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + } + else $linkclose = ($morecss?' class="'.$morecss.'"':''); $linkstart = ''; $linkend=''; - if ($withpicto) - { - $result.=($linkstart.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); - if ($withpicto != 2) $result.=' '; + if ($withpicto) + { + $result.=($linkstart.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); + if ($withpicto != 2) $result.=' '; } $result.= $linkstart . $this->ref . $linkend; return $result; @@ -794,7 +793,7 @@ class EcmFiles //extends CommonObject */ public function initAsSpecimen() { - global $conf,$user; + global $conf,$user; $this->id = 0; diff --git a/htdocs/ecm/docfile.php b/htdocs/ecm/docfile.php index a856ab22c36..f6719d08604 100644 --- a/htdocs/ecm/docfile.php +++ b/htdocs/ecm/docfile.php @@ -117,9 +117,9 @@ if (! ($result >= 0)) if ($cancel) { $action =''; - if ($backtourl) + if ($backtopage) { - header("Location: ".$backtourl); + header("Location: ".$backtopage); exit; } else @@ -387,7 +387,7 @@ if ($action != 'edit') { print ''.$langs->trans('Edit').''; - //print ''.$langs->trans('Cancel').''; + //print ''.$langs->trans('Cancel').''; } /* if ($user->rights->ecm->setup) diff --git a/htdocs/expedition/card.php b/htdocs/expedition/card.php index 17777e6e228..9fa609d9d76 100644 --- a/htdocs/expedition/card.php +++ b/htdocs/expedition/card.php @@ -1439,7 +1439,7 @@ else if ($id || $ref) } // Shipment card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
          '; // Ref customer shipment $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->expedition->creer, 'string', '', 0, 1); @@ -2151,6 +2151,16 @@ else if ($id || $ref) if (GETPOST('modelselected')) { $action = 'presend'; } + + // Presend form + $modelmail='shipping_send'; + $defaulttopic='SendShippingRef'; + $diroutput = $conf->expedition->dir_output. '/sending'; + $trackid = 'shi'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; + + /* if ($action == 'presend') { $ref = dol_sanitizeFileName($object->ref); @@ -2221,7 +2231,7 @@ else if ($id || $ref) $formmail->withdeliveryreceipt=1; $formmail->withcancel=1; // Tableau des substitutions - $formmail->setSubstitFromObject($object); + $formmail->setSubstitFromObject($object, $outputlangs); $formmail->substit['__SHIPPINGREF__']=$object->ref; $formmail->substit['__SHIPPINGTRACKNUM__']=$object->tracking_number; $formmail->substit['__SHIPPINGTRACKNUMURL__']=$object->tracking_url; @@ -2278,7 +2288,7 @@ else if ($id || $ref) print $formmail->get_form(); dol_fiche_end(); - } + }*/ } diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index 6c54c2e6615..cf1c7afad9c 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -48,7 +48,7 @@ class Expedition extends CommonObject public $table_element="expedition"; public $table_element_line="expeditiondet"; protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - public $picto = 'sending'; + public $picto = 'sending'; var $socid; var $ref_customer; @@ -131,29 +131,29 @@ class Expedition extends CommonObject global $langs, $conf; $langs->load("sendings"); - if (!empty($conf->global->EXPEDITION_ADDON_NUMBER)) - { + if (!empty($conf->global->EXPEDITION_ADDON_NUMBER)) + { $mybool = false; $file = $conf->global->EXPEDITION_ADDON_NUMBER.".php"; $classname = $conf->global->EXPEDITION_ADDON_NUMBER; - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { + foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/expedition/"); + $dir = dol_buildpath($reldir."core/modules/expedition/"); - // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; - } + // Load file with numbering class (if found) + $mybool|=@include_once $dir.$file; + } - if (! $mybool) - { - dol_print_error('',"Failed to include file ".$file); - return ''; - } + if (! $mybool) + { + dol_print_error('',"Failed to include file ".$file); + return ''; + } $obj = new $classname(); $numref = ""; @@ -168,19 +168,19 @@ class Expedition extends CommonObject dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); return ""; } - } - else - { - print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined"); - return ""; - } + } + else + { + print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined"); + return ""; + } } /** * Create expedition en base * * @param User $user Objet du user qui cree - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 si erreur, id expedition creee si ok */ function create($user, $notrigger=0) @@ -249,8 +249,8 @@ class Expedition extends CommonObject $sql.= ", ".(!empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null"); $sql.= ", ".(!empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null"); $sql.= ", ".(!empty($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null"); - $sql.= ", ".(int) $this->fk_incoterms; - $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; + $sql.= ", ".(int) $this->fk_incoterms; + $sql.= ", '".$this->db->escape($this->location_incoterms)."'"; $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); @@ -315,10 +315,10 @@ class Expedition extends CommonObject if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('SHIPPING_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('SHIPPING_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers if (! $error) { @@ -393,7 +393,7 @@ class Expedition extends CommonObject $resql = $this->db->query($sql); if ($resql) { - $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet"); + $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet"); } else { @@ -471,7 +471,7 @@ class Expedition extends CommonObject * @param int $id Id of object to load * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param string $ref_int Internal reference of other object + * @param string $ref_int Internal reference of other object * @return int >0 if OK, 0 if not found, <0 if KO */ function fetch($id, $ref='', $ref_ext='', $ref_int='') @@ -481,22 +481,22 @@ class Expedition extends CommonObject // Check parameters if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1; - $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut"; + $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut, e.billed"; $sql.= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height"; $sql.= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery"; $sql.= ", e.fk_shipping_method, e.tracking_number"; $sql.= ", el.fk_source as origin_id, el.sourcetype as origin"; $sql.= ", e.note_private, e.note_public"; - $sql.= ', e.fk_incoterms, e.location_incoterms'; - $sql.= ', i.libelle as libelle_incoterms'; + $sql.= ', e.fk_incoterms, e.location_incoterms'; + $sql.= ', i.libelle as libelle_incoterms'; $sql.= " FROM ".MAIN_DB_PREFIX."expedition as e"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid'; $sql.= " WHERE e.entity IN (".getEntity('expedition').")"; if ($id) $sql.= " AND e.rowid=".$id; - if ($ref) $sql.= " AND e.ref='".$this->db->escape($ref)."'"; - if ($ref_ext) $sql.= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($ref_int) $sql.= " AND e.ref_int='".$this->db->escape($ref_int)."'"; + if ($ref) $sql.= " AND e.ref='".$this->db->escape($ref)."'"; + if ($ref_ext) $sql.= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; + if ($ref_int) $sql.= " AND e.ref_int='".$this->db->escape($ref_int)."'"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -525,7 +525,7 @@ class Expedition extends CommonObject $this->tracking_number = $obj->tracking_number; $this->origin = ($obj->origin?$obj->origin:'commande'); // For compatibility $this->origin_id = $obj->origin_id; - $this->billed = ($obj->fk_statut==2?1:0); + $this->billed = $obj->billed; $this->trueWeight = $obj->weight; $this->weight_units = $obj->weight_units; @@ -600,14 +600,14 @@ class Expedition extends CommonObject * Validate object and update stock if option enabled * * @param User $user Object user that validate - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if OK, >0 if KO */ function valid($user, $notrigger=0) { global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; dol_syslog(get_class($this)."::valid"); @@ -618,8 +618,8 @@ class Expedition extends CommonObject return 0; } - if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->shipping_advance->validate)))) + if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->shipping_advance->validate)))) { $this->error='Permission denied'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); @@ -646,7 +646,7 @@ class Expedition extends CommonObject { $numref = "EXP".$this->id; } - $this->newref = $numref; + $this->newref = $numref; $now=dol_now(); @@ -725,7 +725,7 @@ class Expedition extends CommonObject // line with batch detail // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record. - // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version) + // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version) $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr",$numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock); if ($result < 0) { $error++; @@ -748,22 +748,22 @@ class Expedition extends CommonObject // Change status of order to "shipment in process" $ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $this->origin); - if (! $ret) + if (! $ret) { - $error++; + $error++; } if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('SHIPPING_VALIDATE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('SHIPPING_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) { - $this->oldref = $this->ref; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) @@ -780,17 +780,17 @@ class Expedition extends CommonObject if (@rename($dirsource, $dirdest)) { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); - foreach($listoffiles as $fileentry) - { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -812,8 +812,8 @@ class Expedition extends CommonObject { foreach($this->errors as $errmsg) { - dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); + dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); return -1*$error; @@ -885,14 +885,14 @@ class Expedition extends CommonObject if (! ($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS)) { - $langs->load("errors"); + $langs->load("errors"); $this->error=$langs->trans("ErrorWarehouseRequiredIntoShipmentLine"); return -1; } if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT) { - // Check must be done for stock of product into warehouse if $entrepot_id defined + // Check must be done for stock of product into warehouse if $entrepot_id defined $product=new Product($this->db); $result=$product->fetch($fk_product); @@ -906,8 +906,8 @@ class Expedition extends CommonObject $product_type=$product->type; if ($product_type == 0 && $product_stock < $qty) { - $langs->load("errors"); - $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref); + $langs->load("errors"); + $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref); $this->db->rollback(); return -3; } @@ -917,8 +917,8 @@ class Expedition extends CommonObject // If product need a batch number, we should not have called this function but addline_batch instead. if (! empty($conf->productbatch->enabled) && ! empty($orderline->fk_product) && ! empty($orderline->product_tobatch)) { - $this->error='ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH'; - return -4; + $this->error='ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH'; + return -4; } // extrafields @@ -928,7 +928,7 @@ class Expedition extends CommonObject $this->lines[$num] = $line; } - /** + /** * Add a shipment line with batch record * * @param array $dbatch Array of value (key 'detail' -> Array, key 'qty' total quantity for line, key ix_l : original line index) @@ -952,7 +952,7 @@ class Expedition extends CommonObject // $value['id_batch']=id into llx_product_batch of record to move //var_dump($value); - $linebatch = new ExpeditionLineBatch($this->db); + $linebatch = new ExpeditionLineBatch($this->db); $ret=$linebatch->fetchFromStock($value['id_batch']); // load serial, sellby, eatby if ($ret<0) { @@ -970,8 +970,8 @@ class Expedition extends CommonObject if ($prod_batch->qty < $linebatch->dluo_qty) { - $langs->load("errors"); - $this->errors[]=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product); + $langs->load("errors"); + $this->errors[]=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product); dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR); $this->db->rollback(); return -1; @@ -996,16 +996,16 @@ class Expedition extends CommonObject } } - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user=null, $notrigger=0) - { - global $conf; + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function update($user=null, $notrigger=0) + { + global $conf; $error=0; // Clean parameters @@ -1035,8 +1035,8 @@ class Expedition extends CommonObject // Check parameters // Put here code to add control on parameters values - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET"; $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").","; @@ -1063,32 +1063,32 @@ class Expedition extends CommonObject $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").","; $sql.= " entity=".$conf->entity; - $sql.= " WHERE rowid=".$this->id; + $sql.= " WHERE rowid=".$this->id; $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } if (! $error) { if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('SHIPPING_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers - } + // Call trigger + $result=$this->call_trigger('SHIPPING_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } } - // Commit or rollback + // 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); + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); return -1*$error; @@ -1098,7 +1098,7 @@ class Expedition extends CommonObject $this->db->commit(); return 1; } - } + } /** * Delete shipment. @@ -1231,18 +1231,18 @@ class Expedition extends CommonObject if (! empty($this->origin) && $this->origin_id > 0) { - $this->fetch_origin(); - $origin=$this->origin; - if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress" - { - // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress" - $this->$origin->loadExpeditions(); - //var_dump($this->$origin->expeditions);exit; - if (count($this->$origin->expeditions) <= 0) - { - $this->$origin->setStatut(Commande::STATUS_VALIDATED); - } - } + $this->fetch_origin(); + $origin=$this->origin; + if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress" + { + // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress" + $this->$origin->loadExpeditions(); + //var_dump($this->$origin->expeditions);exit; + if (count($this->$origin->expeditions) <= 0) + { + $this->$origin->setStatut(Commande::STATUS_VALIDATED); + } + } } if (! $error) @@ -1354,13 +1354,13 @@ class Expedition extends CommonObject { $obj = $this->db->fetch_object($resql); - if ($originline == $obj->fk_origin_line) { - $line->entrepot_id = 0; // entrepod_id in details_entrepot - $line->qty_shipped += $obj->qty_shipped; + if ($originline == $obj->fk_origin_line) { + $line->entrepot_id = 0; // entrepod_id in details_entrepot + $line->qty_shipped += $obj->qty_shipped; } else { - $line = new ExpeditionLigne($this->db); - $line->entrepot_id = $obj->fk_entrepot; - $line->qty_shipped = $obj->qty_shipped; + $line = new ExpeditionLigne($this->db); + $line->entrepot_id = $obj->fk_entrepot; + $line->qty_shipped = $obj->qty_shipped; } $detail_entrepot = new stdClass; @@ -1368,13 +1368,13 @@ class Expedition extends CommonObject $detail_entrepot->qty_shipped = $obj->qty_shipped; $line->details_entrepot[] = $detail_entrepot; - $line->line_id = $obj->line_id; - $line->rowid = $obj->line_id; // TODO deprecated - $line->id = $obj->line_id; + $line->line_id = $obj->line_id; + $line->rowid = $obj->line_id; // TODO deprecated + $line->id = $obj->line_id; - $line->fk_origin = 'orderline'; - $line->fk_origin_line = $obj->fk_origin_line; - $line->origin_line_id = $obj->fk_origin_line; // TODO deprecated + $line->fk_origin = 'orderline'; + $line->fk_origin_line = $obj->fk_origin_line; + $line->origin_line_id = $obj->fk_origin_line; // TODO deprecated $line->fk_expedition = $this->id; // id of parent @@ -1382,8 +1382,8 @@ class Expedition extends CommonObject $line->fk_product = $obj->fk_product; $line->fk_product_type = $obj->fk_product_type; $line->ref = $obj->product_ref; // TODO deprecated - $line->product_ref = $obj->product_ref; - $line->product_label = $obj->product_label; + $line->product_ref = $obj->product_ref; + $line->product_label = $obj->product_label; $line->libelle = $obj->product_label; // TODO deprecated $line->product_tobatch = $obj->product_tobatch; $line->label = $obj->custom_label; @@ -1440,34 +1440,34 @@ class Expedition extends CommonObject // Eat-by date if (! empty($conf->productbatch->enabled) && $obj->line_id > 0) { - require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; - $newdetailbatch = ExpeditionLineBatch::fetchAll($this->db,$obj->line_id); - if (is_array($newdetailbatch)) - { - if ($originline != $obj->fk_origin_line) - { - $line->detail_batch = $newdetailbatch; - } - else + $newdetailbatch = ExpeditionLineBatch::fetchAll($this->db,$obj->line_id); + if (is_array($newdetailbatch)) + { + if ($originline != $obj->fk_origin_line) { - $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch); - } - } + $line->detail_batch = $newdetailbatch; + } + else + { + $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch); + } + } } if ($originline != $obj->fk_origin_line) { - $this->lines[$lineindex] = $line; - $lineindex++; + $this->lines[$lineindex] = $line; + $lineindex++; } else { - $line->total_ht += $tabprice[0]; - $line->total_localtax1 += $tabprice[9]; - $line->total_localtax2 += $tabprice[10]; - $line->total_ttc += $tabprice[2]; - $line->total_tva += $tabprice[1]; + $line->total_ht += $tabprice[0]; + $line->total_localtax1 += $tabprice[9]; + $line->total_localtax2 += $tabprice[10]; + $line->total_ttc += $tabprice[2]; + $line->total_tva += $tabprice[1]; } $i++; @@ -1484,41 +1484,50 @@ class Expedition extends CommonObject } /** - * Return clicable link of object (with eventually picto) - * - * @param int $withpicto Add picto into link - * @param int $option Where point the link - * @param int $max Max length to show - * @param int $short Use short labels - * @param int $notooltip 1=No tooltip - * @return string String with URL - */ - function getNomUrl($withpicto=0,$option=0,$max=0,$short=0,$notooltip=0) + * Return clicable link of object (with eventually picto) + * + * @param int $withpicto Add picto into link + * @param string $option Where the link point to + * @param int $max Max length to show + * @param int $short Use short labels + * @param int $notooltip 1=No tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $max=0, $short=0, $notooltip=0, $save_lastsearch_value=-1) { global $langs; $result=''; - $label = '' . $langs->trans("ShowSending") . ''; - $label .= '
          ' . $langs->trans('Ref') . ': '.$this->ref; - $label .= '
          '.$langs->trans('RefCustomer').': '.($this->ref_customer ? $this->ref_customer : $this->ref_client); + $label = '' . $langs->trans("ShowSending") . ''; + $label .= '
          ' . $langs->trans('Ref') . ': '.$this->ref; + $label .= '
          '.$langs->trans('RefCustomer').': '.($this->ref_customer ? $this->ref_customer : $this->ref_client); $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id; if ($short) return $url; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $linkclose=''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label=$langs->trans("ShowSending"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip"'; + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowSending"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; } - $linkstart = ''; + $linkstart = ''; $linkend=''; $picto='sending'; @@ -1530,11 +1539,11 @@ class Expedition extends CommonObject } /** - * Return status label - * - * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto - * @return string Libelle - */ + * Return status label + * + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto + * @return string Libelle + */ function getLibStatut($mode=0) { return $this->LibStatut($this->statut,$mode); @@ -1584,11 +1593,11 @@ class Expedition extends CommonObject } /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ function initAsSpecimen() { @@ -1598,7 +1607,7 @@ class Expedition extends CommonObject dol_syslog(get_class($this)."::initAsSpecimen"); - // Load array of products prodids + // Load array of products prodids $num_prods = 0; $prodids = array(); $sql = "SELECT rowid"; @@ -1639,11 +1648,11 @@ class Expedition extends CommonObject $this->commande_id = 0; $this->commande = $order; - $this->origin_id = 1; - $this->origin = 'commande'; + $this->origin_id = 1; + $this->origin = 'commande'; - $this->note_private = 'Private note'; - $this->note_public = 'Public note'; + $this->note_private = 'Private note'; + $this->note_public = 'Public note'; $nbp = 5; $xnbp = 0; @@ -1723,99 +1732,99 @@ class Expedition extends CommonObject } } - /** - * Fetch all deliveries method and return an array. Load array this->listmeths. - * - * @param id $id only this carrier, all if none - * @return void - */ - function list_delivery_methods($id='') - { - global $langs; + /** + * Fetch all deliveries method and return an array. Load array this->listmeths. + * + * @param id $id only this carrier, all if none + * @return void + */ + function list_delivery_methods($id='') + { + global $langs; - $this->listmeths = array(); - $i=0; + $this->listmeths = array(); + $i=0; - $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em"; - if ($id!='') $sql.= " WHERE em.rowid=".$id; + $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em"; + if ($id!='') $sql.= " WHERE em.rowid=".$id; - $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - $this->listmeths[$i]['rowid'] = $obj->rowid; - $this->listmeths[$i]['code'] = $obj->code; - $label=$langs->trans('SendingMethod'.$obj->code); - $this->listmeths[$i]['libelle'] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle); - $this->listmeths[$i]['description'] = $obj->description; - $this->listmeths[$i]['tracking'] = $obj->tracking; - $this->listmeths[$i]['active'] = $obj->active; - $i++; - } - } - } + $resql = $this->db->query($sql); + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { + $this->listmeths[$i]['rowid'] = $obj->rowid; + $this->listmeths[$i]['code'] = $obj->code; + $label=$langs->trans('SendingMethod'.$obj->code); + $this->listmeths[$i]['libelle'] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle); + $this->listmeths[$i]['description'] = $obj->description; + $this->listmeths[$i]['tracking'] = $obj->tracking; + $this->listmeths[$i]['active'] = $obj->active; + $i++; + } + } + } - /** - * Update/create delivery method. - * - * @param string $id id method to activate - * - * @return void - */ - function update_delivery_method($id='') - { - if ($id=='') - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)"; - $sql.=" VALUES ('".$this->db->escape($this->update['code'])."','".$this->db->escape($this->update['libelle'])."','".$this->db->escape($this->update['description'])."','".$this->db->escape($this->update['tracking'])."')"; - $resql = $this->db->query($sql); - } - else - { - $sql = "UPDATE ".MAIN_DB_PREFIX."c_shipment_mode SET"; - $sql.= " code='".$this->db->escape($this->update['code'])."'"; - $sql.= ",libelle='".$this->db->escape($this->update['libelle'])."'"; - $sql.= ",description='".$this->db->escape($this->update['description'])."'"; - $sql.= ",tracking='".$this->db->escape($this->update['tracking'])."'"; - $sql.= " WHERE rowid=".$id; - $resql = $this->db->query($sql); - } - if ($resql < 0) dol_print_error($this->db,''); - } + /** + * Update/create delivery method. + * + * @param string $id id method to activate + * + * @return void + */ + function update_delivery_method($id='') + { + if ($id=='') + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)"; + $sql.=" VALUES ('".$this->db->escape($this->update['code'])."','".$this->db->escape($this->update['libelle'])."','".$this->db->escape($this->update['description'])."','".$this->db->escape($this->update['tracking'])."')"; + $resql = $this->db->query($sql); + } + else + { + $sql = "UPDATE ".MAIN_DB_PREFIX."c_shipment_mode SET"; + $sql.= " code='".$this->db->escape($this->update['code'])."'"; + $sql.= ",libelle='".$this->db->escape($this->update['libelle'])."'"; + $sql.= ",description='".$this->db->escape($this->update['description'])."'"; + $sql.= ",tracking='".$this->db->escape($this->update['tracking'])."'"; + $sql.= " WHERE rowid=".$id; + $resql = $this->db->query($sql); + } + if ($resql < 0) dol_print_error($this->db,''); + } - /** - * Activate delivery method. - * - * @param id $id id method to activate - * - * @return void - */ - function activ_delivery_method($id) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=1'; - $sql.= ' WHERE rowid='.$id; + /** + * Activate delivery method. + * + * @param id $id id method to activate + * + * @return void + */ + function activ_delivery_method($id) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=1'; + $sql.= ' WHERE rowid='.$id; - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - } + } - /** - * DesActivate delivery method. - * - * @param id $id id method to desactivate - * - * @return void - */ - function disable_delivery_method($id) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=0'; - $sql.= ' WHERE rowid='.$id; + /** + * DesActivate delivery method. + * + * @param id $id id method to desactivate + * + * @return void + */ + function disable_delivery_method($id) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=0'; + $sql.= ' WHERE rowid='.$id; - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - } + } /** @@ -1950,8 +1959,8 @@ class Expedition extends CommonObject // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr",$numref)); if ($result < 0) { - $this->error = $mouvS->error; - $this->errors = $mouvS->errors; + $this->error = $mouvS->error; + $this->errors = $mouvS->errors; $error++; break; } } @@ -1962,9 +1971,9 @@ class Expedition extends CommonObject // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr",$numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock); if ($result < 0) { - $this->error = $mouvS->error; - $this->errors = $mouvS->errors; - $error++; break; + $this->error = $mouvS->error; + $this->errors = $mouvS->errors; + $error++; break; } } } @@ -1979,27 +1988,27 @@ class Expedition extends CommonObject // Call trigger if (! $error) { - $result=$this->call_trigger('SHIPPING_CLOSED',$user); - if ($result < 0) { - $error++; - } + $result=$this->call_trigger('SHIPPING_CLOSED',$user); + if ($result < 0) { + $error++; + } } } else { dol_print_error($this->db); - $error++; + $error++; } if (! $error) { - $this->db->commit(); - return 1; + $this->db->commit(); + return 1; } else { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } } @@ -2010,7 +2019,7 @@ class Expedition extends CommonObject */ function set_billed() { - global $user; + global $user; $error=0; $this->db->begin(); @@ -2116,8 +2125,8 @@ class Expedition extends CommonObject // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr",$numref)); if ($result < 0) { - $this->error = $mouvS->error; - $this->errors = $mouvS->errors; + $this->error = $mouvS->error; + $this->errors = $mouvS->errors; $error++; break; } } @@ -2128,9 +2137,9 @@ class Expedition extends CommonObject // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr",$numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock); if ($result < 0) { - $this->error = $mouvS->error; - $this->errors = $mouvS->errors; - $error++; break; + $this->error = $mouvS->error; + $this->errors = $mouvS->errors; + $error++; break; } } } @@ -2144,11 +2153,11 @@ class Expedition extends CommonObject if (! $error) { - // Call trigger - $result=$this->call_trigger('SHIPPING_REOPEN',$user); - if ($result < 0) { - $error++; - } + // Call trigger + $result=$this->call_trigger('SHIPPING_REOPEN',$user); + if ($result < 0) { + $error++; + } } } else { @@ -2271,11 +2280,11 @@ class ExpeditionLigne extends CommonObjectLine */ var $libelle; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ + /** + * Constructor + * + * @param DoliDB $db Database handler + */ function __construct($db) { $this->db=$db; diff --git a/htdocs/expedition/contact.php b/htdocs/expedition/contact.php index 7c721d7cf47..01807432343 100644 --- a/htdocs/expedition/contact.php +++ b/htdocs/expedition/contact.php @@ -91,7 +91,7 @@ if ($action == 'addcontact' && $user->rights->expedition->creer) } else { - if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') + if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); @@ -160,8 +160,8 @@ if ($id > 0 || ! empty($ref)) // Shipment card - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
          '; // Ref customer shipment $morehtmlref.=$form->editfieldkey("RefCustomer", '', $object->ref_customer, $object, $user->rights->expedition->creer, 'string', '', 0, 1); @@ -203,11 +203,11 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
          '; - - + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + + print '
          '; //print '
          '; print '
          '; @@ -237,23 +237,23 @@ if ($id > 0 || ! empty($ref)) print "\n"; print ''; } - + print ""; - + //print '
          '; //print '
          '; //print '
          '; //print '
          '; - - + + //print '
          '; //print '
          '; print '
          '; - + print '
          '; - - + + dol_fiche_end(); // Lignes de contacts diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index a5b693aa3f9..009e163eeb0 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -42,9 +42,10 @@ $result = restrictedArea($user, 'expedition',$expeditionid,''); $diroutputmassaction=$conf->expedition->dir_output . '/temp/massgeneration/'.$user->id; -$search_ref_exp = GETPOST("search_ref_exp"); -$search_ref_liv = GETPOST('search_ref_liv'); -$search_company = GETPOST("search_company"); +$search_ref_exp = GETPOST("search_ref_exp", 'alpha'); +$search_ref_liv = GETPOST('search_ref_liv', 'alpha'); +$search_ref_customer = GETPOST('search_ref_customer', 'alpha'); +$search_company = GETPOST("search_company", 'alpha'); $search_town=GETPOST('search_town','alpha'); $search_zip=GETPOST('search_zip','alpha'); $search_state=trim(GETPOST("search_state")); @@ -80,38 +81,38 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'e.ref'=>"Ref", - 's.nom'=>"ThirdParty", - 'e.note_public'=>'NotePublic', + 'e.ref'=>"Ref", + 's.nom'=>"ThirdParty", + 'e.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["e.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'e.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'e.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'e.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1), - 'e.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'e.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'e.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), - 'l.ref'=>array('label'=>$langs->trans("DeliveryRef"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), - 'l.date_delivery'=>array('label'=>$langs->trans("DateReceived"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), - 'e.billed'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) + 'e.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'e.ref_customer'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'e.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1), + 'e.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'e.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'e.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'l.ref'=>array('label'=>$langs->trans("DeliveryRef"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), + 'l.date_delivery'=>array('label'=>$langs->trans("DateReceived"), 'checked'=>1, 'enabled'=>$conf->livraison_bon->enabled), + 'e.billed'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>(!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -131,34 +132,35 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_ref_exp=''; - $search_ref_liv=''; - $search_company=''; - $search_town=''; + $search_ref_exp=''; + $search_ref_liv=''; + $search_ref_customer=''; + $search_company=''; + $search_town=''; $search_zip=""; - $search_state=""; + $search_state=""; $search_type=''; $search_country=''; $search_type_thirdparty=''; $search_billed=''; - $viewstatut=''; - $search_array_options=array(); + $viewstatut=''; + $search_array_options=array(); } if (empty($reshook)) { - // Mass actions. Controls on number of lines checked - $maxformassaction=1000; - if (! empty($massaction) && count($toselect) < 1) - { - $error++; - setEventMessages($langs->trans("NoLineChecked"), null, "warnings"); - } - if (! $error && count($toselect) > $maxformassaction) - { - setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); - $error++; - } + // Mass actions. Controls on number of lines checked + $maxformassaction=1000; + if (! empty($massaction) && count($toselect) < 1) + { + $error++; + setEventMessages($langs->trans("NoLineChecked"), null, "warnings"); + } + if (! $error && count($toselect) > $maxformassaction) + { + setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors'); + $error++; + } } @@ -213,6 +215,7 @@ if ($socid) if ($viewstatut <> '' && $viewstatut >= 0) { $sql.= " AND e.fk_statut = ".$viewstatut; } +if ($search_ref_customer != '') $sql.=natural_search('e.ref_customer', $search_ref_customer); if ($search_billed != '' && $search_billed >= 0) $sql.=' AND e.billed = '.$search_billed; if ($search_town) $sql.= natural_search('s.town', $search_town); if ($search_zip) $sql.= natural_search("s.zip",$search_zip); @@ -227,16 +230,16 @@ if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -246,8 +249,8 @@ $sql.=$hookmanager->resPrint; $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->order($sortfield,$sortorder); @@ -262,145 +265,146 @@ if ($resql) $expedition = new Expedition($db); $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall) $param.= "&sall=".$sall; - if ($search_ref_exp) $param.= "&search_ref_exp=".$search_ref_exp; - if ($search_ref_liv) $param.= "&search_ref_liv=".$search_ref_liv; - if ($search_company) $param.= "&search_company=".$search_company; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($sall) $param.= "&sall=".urlencode($sall); + if ($search_ref_exp) $param.= "&search_ref_exp=".urlencode($search_ref_exp); + if ($search_ref_liv) $param.= "&search_ref_liv=".urlencode($search_ref_liv); + if ($search_ref_customer) $param.= "&search_ref_customer=".urlencode($search_ref_customer); + if ($search_company) $param.= "&search_company=".urlencode($search_company); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } //$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); $i = 0; - print '
          '."\n"; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''."\n"; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print_barre_liste($langs->trans('ListOfSendings'), $page, $_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $nbtotalofrecords, '', 0, '', '', $limit); - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - $moreforfilter=''; - if (! empty($moreforfilter)) - { - print '
          '; - print $moreforfilter; - $parameters=array('type'=>$type); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '
          '; - } + $moreforfilter=''; + if (! empty($moreforfilter)) + { + print '
          '; + print $moreforfilter; + $parameters=array('type'=>$type); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '
          '; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - print '
          '; - print ''."\n"; + print '
          '; + print '
          '."\n"; // Lignes des champs de filtre print ''; // Ref if (! empty($arrayfields['e.ref']['checked'])) { - print ''; + print ''; } // Ref customer if (! empty($arrayfields['e.ref_customer']['checked'])) { - print ''; + print ''; } // Thirdparty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } // Town if (! empty($arrayfields['s.town']['checked'])) print ''; // Zip if (! empty($arrayfields['s.zip']['checked'])) print ''; // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print ''; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - } + if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + } // Company type - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - } + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + } // Date delivery planned if (! empty($arrayfields['e.date_delivery']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['l.ref']['checked'])) { - // Delivery ref + // Delivery ref print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -409,34 +413,34 @@ if ($resql) // Date creation if (! empty($arrayfields['e.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['e.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['e.fk_statut']['checked'])) { - print ''; + print ''; } // Status billed if (! empty($arrayfields['e.billed']['checked'])) { - print ''; + print ''; } // Action column print ''; + print ''; print "\n"; print ''; @@ -454,16 +458,16 @@ if ($resql) // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -483,135 +487,135 @@ if ($resql) { $obj = $db->fetch_object($resql); - $shipment->id=$obj->rowid; - $shipment->ref=$obj->ref; + $shipment->id=$obj->rowid; + $shipment->ref=$obj->ref; - $companystatic->id=$obj->socid; - $companystatic->ref=$obj->name; - $companystatic->name=$obj->name; + $companystatic->id=$obj->socid; + $companystatic->ref=$obj->name; + $companystatic->name=$obj->name; - print ''; + print ''; // Ref if (! empty($arrayfields['e.ref']['checked'])) { - print "\n"; - if (! $i) $totalarray['nbfield']++; + print "\n"; + if (! $i) $totalarray['nbfield']++; } // Ref customer if (! empty($arrayfields['e.ref_customer']['checked'])) { - print "\n"; - if (! $i) $totalarray['nbfield']++; + print "\n"; + if (! $i) $totalarray['nbfield']++; } // Third party if (! empty($arrayfields['s.nom']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Town if (! empty($arrayfields['s.town']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Zip if (! empty($arrayfields['s.zip']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print "\n"; - if (! $i) $totalarray['nbfield']++; + print "\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Type ent if (! empty($arrayfields['typent.code']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Date delivery planed if (! empty($arrayfields['e.date_delivery']['checked'])) { - print '\n"; + print "\n"; } if (! empty($arrayfields['l.ref']['checked']) || ! empty($arrayfields['l.date_delivery']['checked'])) - { - $shipment->fetchObjectLinked($shipment->id,$shipment->element); - $receiving=''; - if (count($shipment->linkedObjects['delivery']) > 0) $receiving=reset($shipment->linkedObjects['delivery']); + { + $shipment->fetchObjectLinked($shipment->id,$shipment->element); + $receiving=''; + if (count($shipment->linkedObjects['delivery']) > 0) $receiving=reset($shipment->linkedObjects['delivery']); - if (! empty($arrayfields['l.ref']['checked'])) - { - // Ref - print ''; - } + if (! empty($arrayfields['l.ref']['checked'])) + { + // Ref + print ''; + } - if (! empty($arrayfields['l.date_delivery']['checked'])) - { - // Date received - print ''."\n"; - } + if (! empty($arrayfields['l.date_delivery']['checked'])) + { + // Date received + print ''."\n"; + } } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); @@ -620,24 +624,24 @@ if ($resql) // Date creation if (! empty($arrayfields['e.datec']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['e.tms']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['e.fk_statut']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Billed if (! empty($arrayfields['e.billed']['checked'])) diff --git a/htdocs/expedition/note.php b/htdocs/expedition/note.php index c32ec5c5124..cb123360288 100644 --- a/htdocs/expedition/note.php +++ b/htdocs/expedition/note.php @@ -100,9 +100,9 @@ if ($id > 0 || ! empty($ref)) $head=shipping_prepare_head($object); dol_fiche_head($head, 'note', $langs->trans("Shipment"), -1, 'sending'); - + // Shipment card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
          '; // Ref customer shipment @@ -145,13 +145,13 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
          '; - - + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + + print '
          '; - + $cssclass='titlefield'; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index 849053c610c..80274f9b579 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -85,14 +85,14 @@ if (empty($reshook)) $object->fetch($id); $object->setProject(GETPOST('projectid','int')); } - + if ($action == 'confirm_cloture' && GETPOST('confirm','alpha') == 'yes') { $object = new Commande($db); $object->fetch($id); $result = $object->cloture($user); } - + // Positionne ref commande client else if ($action == 'setref_client' && $user->rights->commande->creer) { $result = $object->set_ref_client($user, GETPOST('ref_client')); @@ -101,12 +101,12 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - + if ($action == 'setdatedelivery' && $user->rights->commande->creer) { //print "x ".$_POST['liv_month'].", ".$_POST['liv_day'].", ".$_POST['liv_year']; $datelivraison=dol_mktime(0, 0, 0, GETPOST('liv_month','int'), GETPOST('liv_day','int'),GETPOST('liv_year','int')); - + $object = new Commande($db); $object->fetch($id); $result=$object->set_date_livraison($user,$datelivraison); @@ -131,7 +131,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + if ($action == 'setavailability' && $user->rights->commande->creer) { $object = new Commande($db); $object->fetch($id); @@ -139,7 +139,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + if ($action == 'setdemandreason' && $user->rights->commande->creer) { $object = new Commande($db); $object->fetch($id); @@ -147,7 +147,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + if ($action == 'setconditions' && $user->rights->commande->creer) { $object = new Commande($db); @@ -156,7 +156,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + // shipping method if ($action == 'setshippingmethod' && $user->rights->commande->creer) { $object = new Commande($db); @@ -165,7 +165,7 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + // warehouse if ($action == 'setwarehouse' && $user->rights->commande->creer) { $object = new Commande($db); @@ -174,14 +174,14 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } - + 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) { // Actions on extra fields (by external module or standard code) @@ -197,20 +197,20 @@ if (empty($reshook)) } else if ($reshook < 0) $error++; } - + if ($error) $action = 'edit_extras'; } - + if ($action == 'set_thirdparty' && $user->rights->commande->creer) { $object->fetch($id); $object->setValueFrom('fk_soc', $socid, '', '', 'date', '', $user, 'ORDER_MODIFY'); - + header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); exit(); } - + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; } @@ -243,13 +243,13 @@ if ($id > 0 || ! empty($ref)) $author->fetch($object->user_author_id); $res = $object->fetch_optionals($object->id, $extralabels); - + $head = commande_prepare_head($object); dol_fiche_head($head, 'shipping', $langs->trans("CustomerOrder"), -1, 'order'); - + $formconfirm = ''; - + // Confirm validation if ($action == 'cloture') { @@ -263,14 +263,14 @@ if ($id > 0 || ! empty($ref)) if (empty($reshook)) $formconfirm.=$hookmanager->resPrint; elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint; } - + // Print form confirm print $formconfirm; - - + + // Order card - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
          '; @@ -320,7 +320,7 @@ if ($id > 0 || ! empty($ref)) print '
          '; print '
          '; print '
          '; - + print '
          '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print '  '; print ''; } if (! empty($arrayfields['l.date_delivery']['checked'])) { - // Date received + // Date received print ' '; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; - print ''; + print ''; - print ''; + print ''; - print $form->selectarray('viewstatut', array('0'=>$langs->trans('StatusSendingDraftShort'),'1'=>$langs->trans('StatusSendingValidatedShort'),'2'=>$langs->trans('StatusSendingProcessedShort')),$viewstatut,1); - print ''; + print $form->selectarray('viewstatut', array('0'=>$langs->trans('StatusSendingDraftShort'),'1'=>$langs->trans('StatusSendingValidatedShort'),'2'=>$langs->trans('StatusSendingProcessedShort')),$viewstatut,1); + print ''; - print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); - print ''; + print $form->selectyesno('search_billed', $search_billed, 1, 0, 1); + print ''; $searchpicto=$form->showFilterAndCheckAddButtons(0); print $searchpicto; - print '
          "; - print $shipment->getNomUrl(1); - print ""; + print $shipment->getNomUrl(1); + print ""; - print $obj->ref_customer; - print ""; + print $obj->ref_customer; + print "'; - print $companystatic->getNomUrl(1); - print ''; + print $companystatic->getNomUrl(1); + print ''; - print $obj->town; - print ''; + print $obj->town; + print ''; - print $obj->zip; - print ''; + print $obj->zip; + print '".$obj->state_name."".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; - print dol_print_date($db->jdate($obj->date_livraison),"day"); - /*$now = time(); + print ''; + print dol_print_date($db->jdate($obj->date_livraison),"day"); + /*$now = time(); if ( ($now - $db->jdate($obj->date_expedition)) > $conf->warnings->lim && $obj->statutid == 1 ) { }*/ - print "'; - print !empty($receiving) ? $receiving->getNomUrl($db) : ''; - print ''; + print !empty($receiving) ? $receiving->getNomUrl($db) : ''; + print ''; - print dol_print_date($db->jdate($obj->date_reception),"day"); - print ''; + print dol_print_date($db->jdate($obj->date_reception),"day"); + print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$shipment->LibStatut($obj->fk_statut,5).''.$shipment->LibStatut($obj->fk_statut,5).'
          '; // Discounts for third party @@ -516,9 +516,9 @@ if ($id > 0 || ! empty($ref)) 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) - + // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -541,7 +541,7 @@ if ($id > 0 || ! empty($ref)) } print ''; } - + // Other attributes $cols = 2; include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; @@ -561,18 +561,18 @@ if ($id > 0 || ! empty($ref)) print ''; print ''; print ''; - + // Multicurrency Amount VAT print ''; print ''; print ''; - + // Multicurrency Amount TTC print ''; print ''; print ''; } - + // Total HT print ''; print ''; @@ -593,7 +593,7 @@ if ($id > 0 || ! empty($ref)) print ''; print ''; } - + // Total TTC print ''; print ''; @@ -603,11 +603,11 @@ if ($id > 0 || ! empty($ref)) print ''; print ''; print ''; - + print '

          '; - - - + + + /** * Lines or orders with quantity shipped and remain to ship * Note: Qty shipped are already available into $object->expeditions[fk_product] @@ -654,7 +654,7 @@ if ($id > 0 || ! empty($ref)) while ($i < $num) { $objp = $db->fetch_object($resql); - + // Show product and description $type=isset($objp->type)?$objp->type:$objp->product_type; @@ -866,14 +866,14 @@ if ($id > 0 || ! empty($ref)) { print $langs->trans("ValidateOrderFirstBeforeShipment"); } - + if (! empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) { if ($user->rights->expedition->creer) { //print load_fiche_titre($langs->trans("CreateShipment")); print '
          '; - + print ''; print ''; //print ''; @@ -910,7 +910,7 @@ if ($id > 0 || ! empty($ref)) //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('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)) . '
          '.$langs->trans('AmountHT').''.price($object->total_ht, 0, '', 1, -1, -1, $conf->currency).'
          ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '
          '.$langs->trans('AmountTTC').''.price($object->total_ttc, 0, '', 1, -1, -1, $conf->currency).'
          "; print "\n"; - + print '
          '; $somethingshown=1; diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index 1460d97323c..16dd8dbf8b1 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -1454,7 +1454,7 @@ else print ''; } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; print ''; @@ -1614,7 +1614,7 @@ else print $formconfirm; // Expense report card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
          '; /* @@ -1865,6 +1865,7 @@ else $sql.= " AND p.fk_expensereport = e.rowid"; $sql.= ' AND e.entity IN ('.getEntity('expensereport').')'; $sql.= " AND p.fk_typepayment = c.id"; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " ORDER BY dp"; $resql = $db->query($sql); diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index 58783ba69b3..3085c3659be 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -1,7 +1,7 @@ * 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 @@ -23,14 +23,14 @@ /** * API class for Expense Reports * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class ExpenseReports 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' @@ -41,7 +41,7 @@ class ExpenseReports extends DolibarrApi */ public $expensereport; - + /** * Constructor */ @@ -56,36 +56,36 @@ class ExpenseReports extends DolibarrApi * Get properties of a Expense Report object * * Return an array with Expense Report informations - * + * * @param int $id ID of Expense Report * @return array|mixed Data without useless information * * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->expensereport->lire) { throw new RestException(401); } - + $result = $this->expensereport->fetch($id); if( ! $result ) { throw new RestException(404, 'Expense report not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + $this->expensereport->fetchObjectLinked(); return $this->_cleanObjectDatas($this->expensereport); } /** * List Expense Reports - * + * * Get a list of Expense Reports - * + * * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -96,19 +96,19 @@ class ExpenseReports extends DolibarrApi */ function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); // case of external user, $societe param is ignored and replaced by user's socid //$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe; - + $sql = "SELECT t.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as t"; $sql.= ' WHERE t.entity IN ('.getEntity('expensereport').')'; if ($user_ids) $sql.=" AND t.fk_user_author IN (".$user_ids.")"; - + // Add sql filters - if ($sqlfilters) + if ($sqlfilters) { if (! DolibarrApi::_checkFilters($sqlfilters)) { @@ -117,7 +117,7 @@ class ExpenseReports extends DolibarrApi $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - + $sql.= $db->order($sortfield, $sortorder); if ($limit) { if ($page < 0) @@ -130,7 +130,7 @@ class ExpenseReports extends DolibarrApi } $result = $db->query($sql); - + if ($result) { $num = $db->num_rows($result); @@ -181,7 +181,7 @@ class ExpenseReports extends DolibarrApi if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); } - + return $this->expensereport->id; } @@ -189,22 +189,22 @@ class ExpenseReports extends DolibarrApi * Get lines of an Expense Report * * @param int $id Id of Expense Report - * + * * @url GET {id}/lines - * - * @return int + * + * @return int */ -/* +/* function getLines($id) { if(! DolibarrApiAccess::$user->rights->expensereport->lire) { throw new RestException(401); } - + $result = $this->expensereport->fetch($id); if( ! $result ) { throw new RestException(404, 'expensereport not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -216,28 +216,28 @@ class ExpenseReports extends DolibarrApi return $result; } */ - + /** * Add a line to given Expense Report * * @param int $id Id of Expense Report to update - * @param array $request_data Expense Report data - * + * @param array $request_data Expense Report data + * * @url POST {id}/lines - * - * @return int + * + * @return int */ -/* +/* function postLine($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->expensereport->creer) { throw new RestException(401); } - + $result = $this->expensereport->fetch($id); if( ! $result ) { throw new RestException(404, 'expensereport not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -271,35 +271,35 @@ class ExpenseReports extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; } */ - + /** * Update a line to given Expense Report * * @param int $id Id of Expense Report to update * @param int $lineid Id of line to update - * @param array $request_data Expense Report data - * + * @param array $request_data Expense Report data + * * @url PUT {id}/lines/{lineid} - * - * @return object + * + * @return object */ /* function putLine($id, $lineid, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->expensereport->creer) { throw new RestException(401); } - + $result = $this->expensereport->fetch($id); if( ! $result ) { throw new RestException(404, 'expensereport not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -342,22 +342,22 @@ class ExpenseReports extends DolibarrApi * * @param int $id Id of Expense Report to update * @param int $lineid Id of line to delete - * + * * @url DELETE {id}/lines/{lineid} - * - * @return int + * + * @return int */ /* - function delLine($id, $lineid) { + function deleteLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->expensereport->creer) { throw new RestException(401); } - + $result = $this->expensereport->fetch($id); if( ! $result ) { throw new RestException(404, 'expensereport not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -369,26 +369,26 @@ class ExpenseReports extends DolibarrApi return false; } */ - + /** * Update Expense Report general fields (won't touch lines of expensereport) * * @param int $id Id of Expense Report to update - * @param array $request_data Datas - * - * @return int + * @param array $request_data Datas + * + * @return int */ /* function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->expensereport->creer) { throw new RestException(401); } - + $result = $this->expensereport->fetch($id); if( ! $result ) { throw new RestException(404, 'expensereport not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -396,19 +396,19 @@ class ExpenseReports extends DolibarrApi if ($field == 'id') continue; $this->expensereport->$field = $value; } - + if($this->expensereport->update(DolibarrApiAccess::$user)) return $this->get($id); - + return false; } */ - + /** * Delete Expense Report * * @param int $id Expense Report ID - * + * * @return array */ function delete($id) @@ -420,31 +420,31 @@ class ExpenseReports extends DolibarrApi if( ! $result ) { throw new RestException(404, 'Expense Report not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if( ! $this->expensereport->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when delete Expense Report : '.$this->expensereport->error); } - + return array( 'success' => array( 'code' => 200, 'message' => 'Expense Report deleted' ) ); - + } - + /** * Validate an Expense Report - * + * * @param int $id Expense Report ID - * + * * @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." @@ -463,15 +463,15 @@ class ExpenseReports extends DolibarrApi if( ! $result ) { throw new RestException(404, 'expensereport not found'); } - + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { throw new RestException(500, 'Error when validate expensereport'); } - + return array( 'success' => array( 'code' => 200, @@ -479,12 +479,12 @@ class ExpenseReports extends DolibarrApi ) ); }*/ - + /** * Validate fields before create or update object - * + * * @param array $data Array with data to verify - * @return array + * @return array * @throws RestException */ function _validate($data) @@ -494,7 +494,7 @@ class ExpenseReports extends DolibarrApi if (!isset($data[$field])) throw new RestException(400, "$field field missing"); $expensereport[$field] = $data[$field]; - + } return $expensereport; } diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index a53fbfe21b9..63e4a3d351b 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -447,7 +447,8 @@ class ExpenseReport extends CommonObject $sql.= " d.fk_user_valid, d.fk_user_approve,"; $sql.= " d.fk_statut as status, d.fk_c_paiement,"; $sql.= " dp.libelle as libelle_paiement, dp.code as code_paiement"; // INNER JOIN paiement - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as dp ON d.fk_c_paiement = dp.id"; + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as dp ON d.fk_c_paiement = dp.id AND dp.entity = " . getEntity('c_paiement'); if ($ref) $sql.= " WHERE d.ref = '".$this->db->escape($ref)."'"; else $sql.= " WHERE d.rowid = ".$id; //$sql.= $restrict; @@ -828,7 +829,7 @@ class ExpenseReport extends CommonObject print '
          '; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -1525,14 +1526,15 @@ class ExpenseReport extends CommonObject /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $max Max length of shown ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @return string String with URL + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $max Max length of shown ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$max=0,$short=0,$moretitle='',$notooltip=0) + function getNomUrl($withpicto=0, $max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1) { global $langs, $conf; @@ -1554,6 +1556,14 @@ class ExpenseReport extends CommonObject $label.= '
          ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($moretitle) $label.=' - '.$moretitle; + //if ($option != 'nolink') + //{ + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + //} + $ref=$this->ref; if (empty($ref)) $ref=$this->id; diff --git a/htdocs/expensereport/class/expensereport_rule.class.php b/htdocs/expensereport/class/expensereport_rule.class.php index f1c5dc7136d..11bc480bf4f 100644 --- a/htdocs/expensereport/class/expensereport_rule.class.php +++ b/htdocs/expensereport/class/expensereport_rule.class.php @@ -21,7 +21,7 @@ * \ingroup expenseik * \brief File of class to manage expense ik */ - + require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php'; /** @@ -32,79 +32,79 @@ class ExpenseReportRule extends CoreObject public $element='expenserule'; public $table_element='expensereport_rules'; public $fk_element='fk_expense_rule'; - + /** * date start - * @var date + * @var int|string */ public $dates; - + /** * date end - * @var date + * @var int|string */ public $datee; - + /** * amount * @var double */ public $amount; - + /** * restrective * @var int */ public $restrictive; - + /** * rule for user * @var int */ public $fk_user; - + /** * rule for group * @var int */ public $fk_usergroup; - + /** * c_type_fees id * @var int */ public $fk_c_type_fees; - + /** * code type of expense report * @var string */ public $code_expense_rules_type; - - + + /** * rule for all * @var int */ public $is_for_all; - + /** * entity * @var int */ public $entity; - - - /** - * Attribute object linked with database - * @var array - */ + + + /** + * Attribute object linked with database + * @var array + */ protected $fields=array( 'rowid'=>array('type'=>'integer','index'=>true) ,'dates'=>array('type'=>'date') ,'datee'=>array('type'=>'date') - ,'amount'=>array('type'=>'double') + ,'amount'=>array('type'=>'double') ,'restrictive'=>array('type'=>'integer') ,'fk_user'=>array('type'=>'integer') ,'fk_usergroup'=>array('type'=>'integer') @@ -114,24 +114,24 @@ class ExpenseReportRule extends CoreObject ,'entity'=>array('type'=>'integer') ); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct(DoliDB &$db) + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB &$db) { global $conf; - parent::__construct($db); + parent::__construct($db); parent::init(); - + $this->errors = array(); } - + /** * Return all rules or filtered by something - * + * * @param int $fk_c_type_fees type of expense * @param date $date date of expense * @param type $fk_user user of expense @@ -140,7 +140,7 @@ class ExpenseReportRule extends CoreObject public static function getAllRule($fk_c_type_fees='', $date='', $fk_user='') { global $db; - + $rules = array(); $sql = 'SELECT er.rowid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'expensereport_rules er'; @@ -162,9 +162,9 @@ class ExpenseReportRule extends CoreObject $sql.= ' OR er.fk_usergroup IN (SELECT ugu.fk_usergroup FROM '.MAIN_DB_PREFIX.'usergroup_user ugu WHERE ugu.fk_user = '.$fk_user.') )'; } $sql.= ' ORDER BY er.is_for_all, er.fk_usergroup, er.fk_user'; - + dol_syslog("ExpenseReportRule::getAllRule sql=".$sql); - + $resql = $db->query($sql); if ($resql) { @@ -179,19 +179,19 @@ class ExpenseReportRule extends CoreObject { dol_print_error($db); } - + return $rules; } - + /** * Return the label of group for the current object - * + * * @return string */ public function getGroupLabel() { include_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; - + if ($this->fk_usergroup > 0) { $group = new UserGroup($this->db); @@ -205,19 +205,19 @@ class ExpenseReportRule extends CoreObject $this->errors[] = $this->error; } } - + return ''; } - + /** * Return the name of user for the current object - * + * * @return string */ public function getUserName() { include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - + if ($this->fk_user > 0) { $u = new User($this->db); @@ -231,7 +231,7 @@ class ExpenseReportRule extends CoreObject $this->errors[] = $this->error; } } - + return ''; } } diff --git a/htdocs/expensereport/class/paymentexpensereport.class.php b/htdocs/expensereport/class/paymentexpensereport.class.php index 4d2bc6b9b48..b836f410245 100644 --- a/htdocs/expensereport/class/paymentexpensereport.class.php +++ b/htdocs/expensereport/class/paymentexpensereport.class.php @@ -168,6 +168,7 @@ class PaymentExpenseReport extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."payment_expensereport as t)"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepayment = pt.id"; + $sql.= " AND pt.entity = " . getEntity('c_paiement'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -447,7 +448,7 @@ class PaymentExpenseReport extends CommonObject function LibStatut($statut,$mode=0) { global $langs; - + return ''; } diff --git a/htdocs/expensereport/document.php b/htdocs/expensereport/document.php index 2b8dd3ee0c6..ed588f3f961 100644 --- a/htdocs/expensereport/document.php +++ b/htdocs/expensereport/document.php @@ -93,15 +93,15 @@ if ($object->id) dol_fiche_head($head, 'documents', $langs->trans("ExpenseReport"), -1, 'trip'); - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
          '; $morehtmlref.='
          '; - - + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + + // Construit liste des fichiers $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); $totalsize=0; @@ -112,7 +112,7 @@ if ($object->id) print '
          '; print '
          '; - + print '
          '.$objp->ref_num.''.dol_print_date($objp->date,'day').''.$author->getNomUrl().''.$author->getNomUrl(1).''.$objp->comments.''.price($objp->total_ht).''.price($objp->total_ttc).'
          '; $linkback = ''.$langs->trans("BackToList").''; @@ -124,8 +124,8 @@ if ($object->id) print ''; dol_fiche_end(); - - + + $modulepart = 'expensereport'; $permission = $user->rights->expensereport->creer; $permtoedit = $user->rights->expensereport->creer; diff --git a/htdocs/expensereport/info.php b/htdocs/expensereport/info.php index 0c3f687519c..6c2410aaa98 100644 --- a/htdocs/expensereport/info.php +++ b/htdocs/expensereport/info.php @@ -56,25 +56,25 @@ if ($id > 0 || ! empty($ref)) dol_fiche_head($head, 'info', $langs->trans("ExpenseReport"), -1, 'trip'); - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
          '; $morehtmlref.='
          '; - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - + print '
          '; print '
          '; - + print '
          '; - + print '
          '; dol_print_object_info($object); print '
          '; print '
          '; - + dol_fiche_end(); } diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index 682ecf44839..0c34ff43ef0 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -120,7 +120,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); } } diff --git a/htdocs/expensereport/note.php b/htdocs/expensereport/note.php index 8c059b8b284..8376733d634 100644 --- a/htdocs/expensereport/note.php +++ b/htdocs/expensereport/note.php @@ -80,22 +80,22 @@ if ($id > 0 || ! empty($ref)) dol_fiche_head($head, 'note', $langs->trans("ExpenseReport"), -1, 'trip'); - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
          '; $morehtmlref.='
          '; - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - + print '
          '; print '
          '; - + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
          '; - + dol_fiche_end(); } diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 680ab2b6a7e..bc6fb9d3014 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -2,7 +2,7 @@ /* Copyright (C) 2002-2007 Rodolphe Quiedeville * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005-2015 Regis Houssin - * Copyright (C) 2011-2013 Juanjo Menent + * Copyright (C) 2011-2017 Juanjo Menent * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2015 Ferran Marcet * Copyright (C) 2014-2015 Charlie Benke @@ -60,6 +60,7 @@ $ref = GETPOST('ref','alpha'); $socid = GETPOST('socid','int'); $contratid = GETPOST('contratid','int'); $action = GETPOST('action','alpha'); +$cancel = GETPOST('cancel','alpha'); $confirm = GETPOST('confirm','alpha'); $mesg = GETPOST('msg','alpha'); $origin=GETPOST('origin','alpha'); @@ -105,6 +106,16 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { + if ($cancel) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action=''; + } + 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 @@ -201,11 +212,11 @@ if (empty($reshook)) else if ($action == 'add' && $user->rights->ficheinter->creer) { $object->socid = $socid; - $object->duration = GETPOST('duration','int'); + $object->duration = GETPOST('duration','int'); $object->fk_project = GETPOST('projectid','int'); $object->fk_contrat = GETPOST('contratid','int'); $object->author = $user->id; - $object->description = GETPOST('description'); + $object->description = GETPOST('description','none'); $object->ref = $ref; $object->modelpdf = GETPOST('model','alpha'); $object->note_private = GETPOST('note_private','none'); @@ -276,7 +287,7 @@ if (empty($reshook)) $fk_parent_line=0; $num=count($lines); - for ($i=0;$i<$num;$i++) + for ($i=0; $i<$num; $i++) { $product_type=($lines[$i]->product_type?$lines[$i]->product_type:Product::TYPE_PRODUCT); @@ -743,7 +754,8 @@ if (empty($reshook)) $parameters=array('id'=>$object->id); $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) - { $result=$object->updateExtraField($_POST["attribute"]); + { + $result=$object->insertExtraFields(); if ($result < 0) { $error++; @@ -828,7 +840,7 @@ if ($action == 'create') $soc=new Societe($db); - print load_fiche_titre($langs->trans("AddIntervention")); + print load_fiche_titre($langs->trans("AddIntervention"), '', 'title_commercial'); dol_htmloutput_mesg($mesg); @@ -1007,6 +1019,30 @@ if ($action == 'create') $newclassname=$classname; if ($newclassname=='Propal') $newclassname='CommercialProposal'; print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; + + // Amount + /* Hide amount because we only copy services so amount may differ than source + 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 + { + print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1) . ""; + } + + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF + { + print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2) . ""; + } + + print '' . $langs->trans('TotalTTC') . '' . price($objectsrc->total_ttc) . ""; + + if (!empty($conf->multicurrency->enabled)) + { + print '' . $langs->trans('MulticurrencyTotalHT') . '' . price($objectsrc->multicurrency_total_ht) . ''; + print '' . $langs->trans('MulticurrencyTotalVAT') . '' . price($objectsrc->multicurrency_total_tva) . ""; + print '' . $langs->trans('MulticurrencyTotalTTC') . '' . price($objectsrc->multicurrency_total_ttc) . ""; + } + */ } print ''; @@ -1028,6 +1064,18 @@ if ($action == 'create') print '
    '; print ''; + + // Show origin lines + if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) { + $title = $langs->trans('Services'); + print load_fiche_titre($title); + + print ''; + + $objectsrc->printOriginLinesList(empty($conf->global->FICHINTER_PRINT_PRODUCTS)?'services':''); // Show only service, except if option FICHINTER_PRINT_PRODUCTS is on + + print '
    '; + } } else { @@ -1148,7 +1196,7 @@ else if ($id > 0 || ! empty($ref)) // Intervention card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; @@ -1603,22 +1651,8 @@ else if ($id > 0 || ! empty($ref)) else print ''; } - // Event agenda - if (! empty($conf->global->FICHINTER_ADDLINK_TO_EVENT)) - { - if (! empty($conf->agenda->enabled) && $object->statut > Fichinter::STATUS_DRAFT) - { - $langs->load("agenda"); - if ($object->statut < Fichinter::STATUS_BILLED) - { - if ($user->rights->agenda->myactions->create) print ''; - else print ''; - } - } - } - // Proposal - if (! empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) + if ($conf->service->enabled && ! empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) { $langs->load("propal"); if ($object->statut < Fichinter::STATUS_BILLED) @@ -1683,18 +1717,11 @@ else if ($id > 0 || ! empty($ref)) * Built documents */ $filename=dol_sanitizeFileName($object->ref); - $filedir=$conf->ficheinter->dir_output . "/".$object->ref; + $filedir=$conf->ficheinter->dir_output . "/".$filename; $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed=$user->rights->ficheinter->creer; $delallowed=$user->rights->ficheinter->supprimer; - $genallowed=1; - $delallowed=1; - - $var=true; - - //print "
    \n"; - print $somethingshown=$formfile->showdocuments('ficheinter',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang); - + print $formfile->showdocuments('ficheinter',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('fichinter')); diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 1c023415de0..68096eea8e9 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -38,7 +38,7 @@ class Fichinter extends CommonObject public $table_element='fichinter'; public $fk_element='fk_fichinter'; public $table_element_line='fichinterdet'; - public $picto = 'intervention'; + public $picto = 'intervention'; /** * {@inheritdoc} @@ -83,7 +83,7 @@ class Fichinter extends CommonObject * Constructor * * @param DoliDB $db Database handler - */ + */ function __construct($db) { $this->db = $db; @@ -152,7 +152,7 @@ class Fichinter extends CommonObject * Create an intervention into data base * * @param User $user Objet user that make creation - * @param int $notrigger Disable all triggers + * @param int $notrigger Disable all triggers * @return int <0 if KO, >0 if OK */ function create($user, $notrigger=0) @@ -237,13 +237,13 @@ class Fichinter extends CommonObject } if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } // Add linked object if (! $error && $this->origin && $this->origin_id) @@ -253,13 +253,13 @@ class Fichinter extends CommonObject } - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('FICHINTER_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('FICHINTER_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } if (! $error) { @@ -287,7 +287,7 @@ class Fichinter extends CommonObject * Update an intervention * * @param User $user Objet user that make creation - * @param int $notrigger Disable all triggers + * @param int $notrigger Disable all triggers * @return int <0 if KO, >0 if OK */ function update($user, $notrigger=0) @@ -316,10 +316,10 @@ class Fichinter extends CommonObject if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('FICHINTER_MODIFY',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('FICHINTER_MODIFY',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } $this->db->commit(); @@ -446,7 +446,7 @@ class Fichinter extends CommonObject * Validate a intervention * * @param User $user User that validate - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function setValid($user, $notrigger=0) @@ -471,7 +471,7 @@ class Fichinter extends CommonObject { $num = $this->ref; } - $this->newref = $num; + $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql.= " SET fk_statut = 1"; @@ -492,10 +492,10 @@ class Fichinter extends CommonObject if (! $error && ! $notrigger) { - // Call trigger - $result=$this->call_trigger('FICHINTER_VALIDATE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('FICHINTER_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -517,17 +517,17 @@ class Fichinter extends CommonObject if (@rename($dirsource, $dirdest)) { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); - foreach($listoffiles as $fileentry) - { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -647,7 +647,7 @@ class Fichinter extends CommonObject if ($mode == 5) return ''.$langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]); if ($mode == 6) - return ''.$langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]); + return ''.$langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]); return ''; } @@ -655,28 +655,52 @@ class Fichinter extends CommonObject /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=_No picto, 1=Includes the picto in the linkn, 2=Picto only - * @param string $option Options - * @return string String with URL + * @param int $withpicto 0=_No picto, 1=Includes the picto in the linkn, 2=Picto only + * @param string $option Options + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - function getNomUrl($withpicto=0,$option='') + function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1) { - global $langs; + global $conf, $langs; $result=''; - $label = '' . $langs->trans("ShowIntervention") . ''; - if (! empty($this->ref)) - $label .= '
    ' . $langs->trans('Ref') . ': '.$this->ref; - $link = ''; - $linkend=''; + $label = '' . $langs->trans("ShowIntervention") . ''; + if (! empty($this->ref)) + $label .= '
    ' . $langs->trans('Ref') . ': '.$this->ref; $picto='intervention'; + $url = DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } - if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowIntervention"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart = ''; + $linkend=''; + + if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$link.$this->ref.$linkend; + if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend; return $result; } @@ -809,7 +833,7 @@ class Fichinter extends CommonObject function delete($user, $notrigger=0) { global $conf,$langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; @@ -875,10 +899,10 @@ class Fichinter extends CommonObject if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('FICHINTER_DELETE',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('FICHINTER_DELETE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } $this->db->commit(); @@ -1000,98 +1024,98 @@ class Fichinter extends CommonObject - /** - * Load an object from its id and create a new one in database - * - * @param int $socid Id of thirdparty - * @return int New id of clone - */ - function createFromClone($socid=0) - { - global $user,$hookmanager; + /** + * Load an object from its id and create a new one in database + * + * @param int $socid Id of thirdparty + * @return int New id of clone + */ + function createFromClone($socid=0) + { + global $user,$hookmanager; - $error=0; + $error=0; - $this->context['createfromclone'] = 'createfromclone'; + $this->context['createfromclone'] = 'createfromclone'; - $this->db->begin(); + $this->db->begin(); // get extrafields so they will be clone foreach($this->lines as $line) $line->fetch_optionals($line->rowid); - // Load source object - $objFrom = clone $this; + // Load source object + $objFrom = clone $this; - // Change socid if needed - if (! empty($socid) && $socid != $this->socid) - { - $objsoc = new Societe($this->db); + // Change socid if needed + if (! empty($socid) && $socid != $this->socid) + { + $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid)>0) - { - $this->socid = $objsoc->id; - //$this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); - //$this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); - $this->fk_project = ''; - $this->fk_delivery_address = ''; - } + if ($objsoc->fetch($socid)>0) + { + $this->socid = $objsoc->id; + //$this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); + //$this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); + $this->fk_project = ''; + $this->fk_delivery_address = ''; + } - // TODO Change product price if multi-prices - } + // TODO Change product price if multi-prices + } - $this->id=0; + $this->id=0; $this->ref = ''; - $this->statut=0; + $this->statut=0; - // Clear fields - $this->user_author_id = $user->id; - $this->user_valid = ''; - $this->date_creation = ''; - $this->date_validation = ''; - $this->ref_client = ''; + // Clear fields + $this->user_author_id = $user->id; + $this->user_valid = ''; + $this->date_creation = ''; + $this->date_validation = ''; + $this->ref_client = ''; - // Create clone - $result=$this->create($user); - if ($result < 0) $error++; + // Create clone + $result=$this->create($user); + if ($result < 0) $error++; - if (! $error) - { - // Add lines because it is not included into create function - foreach ($this->lines as $line) - { - $this->addline($user, $this->id, $line->desc, $line->datei, $line->duration); - } + if (! $error) + { + // Add lines because it is not included into create function + foreach ($this->lines as $line) + { + $this->addline($user, $this->id, $line->desc, $line->datei, $line->duration); + } - // Hook of thirdparty module - if (is_object($hookmanager)) - { - $parameters=array('objFrom'=>$objFrom); - $action=''; - $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; - } + // Hook of thirdparty module + if (is_object($hookmanager)) + { + $parameters=array('objFrom'=>$objFrom); + $action=''; + $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) $error++; + } - // Call trigger - $result=$this->call_trigger('INTERVENTION_CLONE',$user); - if ($result < 0) $error++; - // End call triggers - } + // Call trigger + $result=$this->call_trigger('INTERVENTION_CLONE',$user); + if ($result < 0) $error++; + // End call triggers + } - unset($this->context['createfromclone']); + unset($this->context['createfromclone']); - // End - if (! $error) - { - $this->db->commit(); - return $this->id; - } - else - { - $this->db->rollback(); - return -1; - } - } + // End + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1; + } + } /** @@ -1314,7 +1338,7 @@ class FichinterLigne extends CommonObjectLine * Insert the line into database * * @param User $user Objet user that make creation - * @param int $notrigger Disable all triggers + * @param int $notrigger Disable all triggers * @return int <0 if ko, >0 if ok */ function insert($user, $notrigger=0) @@ -1362,14 +1386,14 @@ class FichinterLigne extends CommonObjectLine $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet'); if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } $result=$this->update_total(); @@ -1380,10 +1404,10 @@ class FichinterLigne extends CommonObjectLine if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('LINEFICHINTER_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('LINEFICHINTER_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } } @@ -1410,7 +1434,7 @@ class FichinterLigne extends CommonObjectLine * Update intervention into database * * @param User $user Objet user that make creation - * @param int $notrigger Disable all triggers + * @param int $notrigger Disable all triggers * @return int <0 if ko, >0 if ok */ function update($user,$notrigger=0) @@ -1433,14 +1457,14 @@ class FichinterLigne extends CommonObjectLine { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $this->id=$this->rowid; - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } $result=$this->update_total(); if ($result > 0) @@ -1448,10 +1472,10 @@ class FichinterLigne extends CommonObjectLine if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('LINEFICHINTER_UPDATE',$user); - if ($result < 0) { $error++; } - // End call triggers + // Call trigger + $result=$this->call_trigger('LINEFICHINTER_UPDATE',$user); + if ($result < 0) { $error++; } + // End call triggers } } @@ -1531,13 +1555,15 @@ class FichinterLigne extends CommonObjectLine * Delete a intervention line * * @param User $user Objet user that make creation - * @param int $notrigger Disable all triggers + * @param int $notrigger Disable all triggers * @return int >0 if ok, <0 if ko */ function deleteline($user,$notrigger=0) { global $langs,$conf; + $error=0; + if ($this->statut == 0) { dol_syslog(get_class($this)."::deleteline lineid=".$this->rowid); @@ -1553,14 +1579,14 @@ class FichinterLigne extends CommonObjectLine { if (! $notrigger) { - // Call trigger - $result=$this->call_trigger('LINEFICHINTER_DELETE',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('LINEFICHINTER_DELETE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } - $this->db->commit(); - return $result; + $this->db->commit(); + return $result; } else { diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php index 2b40553a3d9..d7be9c95cec 100644 --- a/htdocs/fichinter/contact.php +++ b/htdocs/fichinter/contact.php @@ -126,9 +126,9 @@ if ($id > 0 || ! empty($ref)) // Intervention card - $linkback = ''.$langs->trans("BackToList").''; - - + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -169,13 +169,13 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
    '; - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); - + dol_fiche_end(); - + print '
    '; - + if (! empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_USER)) $hideaddcontactforuser=1; if (! empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_THIPARTY)) $hideaddcontactforthirdparty=1; diff --git a/htdocs/fichinter/document.php b/htdocs/fichinter/document.php index 3d5a3c544e8..33db56a6e78 100644 --- a/htdocs/fichinter/document.php +++ b/htdocs/fichinter/document.php @@ -102,9 +102,9 @@ if ($object->id) // Intervention card - $linkback = ''.$langs->trans("BackToList").''; - - + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -145,13 +145,13 @@ if ($object->id) } } $morehtmlref.='
    '; - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + + print '
    '; print '
    '; - + print ''; print ''; print ''; @@ -160,7 +160,7 @@ if ($object->id) print ''; dol_fiche_end(); - + $modulepart = 'ficheinter'; $permission = $user->rights->ficheinter->creer; $permtoedit = $user->rights->ficheinter->creer; diff --git a/htdocs/fichinter/info.php b/htdocs/fichinter/info.php index a32cda9bb57..c8520a6645f 100644 --- a/htdocs/fichinter/info.php +++ b/htdocs/fichinter/info.php @@ -63,7 +63,7 @@ $head = fichinter_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans('InterventionCard'), -1, 'intervention'); // Intervention card -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index 9dca5d1badb..d806923a241 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -92,34 +92,34 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.ref'=>'Ref', - 's.nom'=>"ThirdParty", - 'f.description'=>'Description', - 'f.note_public'=>'NotePublic', + 'f.ref'=>'Ref', + 's.nom'=>"ThirdParty", + 'f.description'=>'Description', + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; if (! empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['f.description']); // Definition of fields for list $arrayfields=array( - 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), 'f.fk_project'=>array('label'=>$langs->trans("Project"), 'checked'=>1), - 'f.fk_contrat'=>array('label'=>$langs->trans("Contract"), 'checked'=>1), - 'f.description'=>array('label'=>$langs->trans("Description"), 'checked'=>1), - 'fd.description'=>array('label'=>"xx", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), - 'fd.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), - 'fd.duree'=>array('label'=>$langs->trans("Duration"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'f.fk_contrat'=>array('label'=>$langs->trans("Contract"), 'checked'=>1), + 'f.description'=>array('label'=>$langs->trans("Description"), 'checked'=>1), + 'fd.description'=>array('label'=>"xx", 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'fd.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), + 'fd.duree'=>array('label'=>$langs->trans("Duration"), 'checked'=>1, 'enabled'=>empty($conf->global->FICHINTER_DISABLE_DETAILS)?1:0), 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); } } @@ -137,10 +137,10 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // 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'; - // Purge search criteria + // Purge search criteria if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { $search_ref=""; @@ -149,7 +149,7 @@ if (empty($reshook)) $search_contract=""; $search_desc=""; $search_status=""; - $toselect=''; + $toselect=''; $search_array_options=array(); } @@ -197,17 +197,17 @@ $sql.= ", ".MAIN_DB_PREFIX."societe as s"; $sql.= " WHERE f.fk_soc = s.rowid "; $sql.= " AND f.entity = ".$conf->entity; if ($search_ref) { - $sql .= natural_search('f.ref', $search_ref); + $sql .= natural_search('f.ref', $search_ref); } if ($search_company) { - $sql .= natural_search('s.nom', $search_company); + $sql .= natural_search('s.nom', $search_company); } if ($search_desc) { - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); - else $sql .= natural_search(array('f.description'), $search_desc); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); + else $sql .= natural_search(array('f.description'), $search_desc); } if ($search_status != '' && $search_status >= 0) { - $sql .= ' AND f.fk_statut = '.$search_status; + $sql .= ' AND f.fk_statut = '.$search_status; } if (! $user->rights->societe->client->voir && empty($socid)) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; @@ -219,16 +219,16 @@ if ($sall) { // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -262,7 +262,7 @@ if ($resql) } $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $urlparam.="&sall=".$sall; if ($socid) $param.="&socid=".$socid; @@ -270,97 +270,97 @@ if ($resql) if ($search_company) $param.="&search_company=".urlencode($search_company); if ($search_desc) $param.="&search_desc=".urlencode($search_desc); if ($search_status != '' && $search_status > -1) $param.="&search_status=".urlencode($search_status); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } + // Add $param from extra fields + foreach ($search_array_options as $key => $val) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), - ); - //if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); - if ($user->rights->ficheinter->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - //if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), + ); + //if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); + if ($user->rights->ficheinter->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + //if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); // Lines of title fields - print '
    '."\n"; - if ($optioncss != '') print ''; - print ''; + print ''."\n"; + if ($optioncss != '') print ''; + print ''; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit); if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - $moreforfilter=''; + $moreforfilter=''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; - if (! empty($moreforfilter)) - { - print '
    '; - print $moreforfilter; - print '
    '; - } + if (! empty($moreforfilter)) + { + print '
    '; + print $moreforfilter; + print '
    '; + } $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
    '; - print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '."\n"; + print '
    '; + print '
    '."\n"; print ''; - if (! empty($arrayfields['f.ref']['checked'])) - { + if (! empty($arrayfields['f.ref']['checked'])) + { print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['f.description']['checked'])) - { + } + if (! empty($arrayfields['f.description']['checked'])) + { print ''; - } - if (! empty($arrayfields['fd.description']['checked'])) - { - // Desc of line + } + if (! empty($arrayfields['fd.description']['checked'])) + { + // Desc of line + print ''; + } + if (! empty($arrayfields['fd.date']['checked'])) + { + print ''; + } + if (! empty($arrayfields['fd.duree']['checked'])) + { print ''; - } - if (! empty($arrayfields['fd.date']['checked'])) - { - print ''; - } - if (! empty($arrayfields['fd.duree']['checked'])) - { - print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -369,84 +369,84 @@ if ($resql) { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; } } } - // Fields from hook + // Fields from hook $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) - { - // Date creation - print ''; - } - if (! empty($arrayfields['f.tms']['checked'])) - { - // Date modification - print ''; - } - // Status + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) + { + // Date creation + print ''; + } + if (! empty($arrayfields['f.tms']['checked'])) + { + // Date modification + print ''; + } + // Status if (! empty($arrayfields['f.fk_statut']['checked'])) - { + { print ''; - } + } print ''; - print "\n"; + print "\n"; - print ''; - if (! empty($arrayfields['f.ref']['checked'])) print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"f.ref","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['f.description']['checked'])) print_liste_field_titre("Description",$_SERVER["PHP_SELF"],"f.description","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['fd.description']['checked'])) print_liste_field_titre('',$_SERVER["PHP_SELF"],''); - if (! empty($arrayfields['fd.date']['checked'])) print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"fd.date","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['fd.duree']['checked'])) print_liste_field_titre("Duration",$_SERVER["PHP_SELF"],"fd.duree","",$param,'align="right"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre("DateCreationShort",$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre("DateModificationShort",$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"f.fk_statut","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; + print ''; + if (! empty($arrayfields['f.ref']['checked'])) print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"f.ref","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"s.nom","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.description']['checked'])) print_liste_field_titre("Description",$_SERVER["PHP_SELF"],"f.description","",$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['fd.description']['checked'])) print_liste_field_titre('',$_SERVER["PHP_SELF"],''); + if (! empty($arrayfields['fd.date']['checked'])) print_liste_field_titre("Date",$_SERVER["PHP_SELF"],"fd.date","",$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['fd.duree']['checked'])) print_liste_field_titre("Duration",$_SERVER["PHP_SELF"],"fd.duree","",$param,'align="right"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre("DateCreationShort",$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre("DateModificationShort",$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"f.fk_statut","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); + print "\n"; $total = 0; $i = 0; @@ -461,44 +461,44 @@ if ($resql) print ''; - if (! empty($arrayfields['f.ref']['checked'])) + if (! empty($arrayfields['f.ref']['checked'])) { print "
    '; print ''; print ''; + } + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; print ''; print ''; - print ''; + print ''; print '     '; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; } print ''; - print ''; - print ''; + print ''; + print ''; $liststatus=$objectstatic->statuts_short; if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1); print ''; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
    "; print ''; - // Picto + Ref - print ''; - // Warning - $warnornote=''; - //if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->fichinter->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (! empty($obj->note_private)) - { - $warnornote.=($warnornote?' ':''); - $warnornote.= ''; - $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - $warnornote.= ''; - } - if ($warnornote) - { - print ''; - } + // Picto + Ref + print ''; + // Warning + $warnornote=''; + //if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->fichinter->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); + if (! empty($obj->note_private)) + { + $warnornote.=($warnornote?' ':''); + $warnornote.= ''; + $warnornote.= ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + $warnornote.= ''; + } + if ($warnornote) + { + print ''; + } - // Other picto tool - print '
    '; - print $objectstatic->getNomUrl(1); - print ''; - print $warnornote; - print ''; + print $objectstatic->getNomUrl(1); + print ''; + print $warnornote; + print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->ficheinter->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - print '
    '; + // Other picto tool + print '
    '; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->ficheinter->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + print '
    '; print "\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['s.nom']['checked'])) + if (! empty($arrayfields['s.nom']['checked'])) { print ''; $companystatic->name=$obj->name; @@ -506,33 +506,33 @@ if ($resql) $companystatic->client=$obj->client; print $companystatic->getNomUrl(1,'',44); print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['f.description']['checked'])) + if (! empty($arrayfields['f.description']['checked'])) { print ''.dol_trunc(dolGetFirstLineOfText($obj->description),48).''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['fd.description']['checked'])) + if (! empty($arrayfields['fd.description']['checked'])) { //print ''.dol_trunc(dol_escape_htmltag(dolGetFirstLineOfText($obj->descriptiondetail)),48).''; print ''.dolGetFirstLineOfText($obj->descriptiondetail).''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['fd.date']['checked'])) + if (! empty($arrayfields['fd.date']['checked'])) { print ''.dol_print_date($db->jdate($obj->dp),'dayhour')."\n"; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['fd.duree']['checked'])) + if (! empty($arrayfields['fd.duree']['checked'])) { print ''.convertSecondToTime($obj->duree, 'allhourmin').''; if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totaldurationfield']=$totalarray['nbfield']; - $totalarray['totalduration']+=$obj->duree; + if (! $i) $totalarray['totaldurationfield']=$totalarray['nbfield']; + $totalarray['totalduration']+=$obj->duree; } - // Extra fields + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { foreach($extrafields->attribute_label as $key => $val) @@ -546,46 +546,46 @@ if ($resql) $tmpkey='options_'.$key; print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; } } } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['f.datec']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['f.datec']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { print ''.$objectstatic->LibStatut($obj->fk_statut,5).''; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; - } - print ''; - if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; @@ -596,20 +596,20 @@ if ($resql) // Show total line if (isset($totalarray['totalduration'])) { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; - else print ''.$langs->trans("Totalforthispage").''; - } - elseif ($totalarray['totaldurationfield'] == $i) print ''.convertSecondToTime($totalarray['totalduration'], 'allhourmin').''; - else print ''; - } - print ''; + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; + else print ''.$langs->trans("Totalforthispage").''; + } + elseif ($totalarray['totaldurationfield'] == $i) print ''.convertSecondToTime($totalarray['totalduration'], 'allhourmin').''; + else print ''; + } + print ''; } $db->free($resql); @@ -625,21 +625,21 @@ if ($resql) if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->ficheinter->lire; - $delallowed=$user->rights->ficheinter->supprimer; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->ficheinter->lire; + $delallowed=$user->rights->ficheinter->supprimer; - print $formfile->showdocuments('massfilesarea_interventions','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_interventions','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; + print '
    '.$langs->trans("ShowTempMassFilesArea").''; } } diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php index 43a2654d1fd..a5a9675eb43 100644 --- a/htdocs/fichinter/note.php +++ b/htdocs/fichinter/note.php @@ -61,14 +61,14 @@ $form = new Form($db); if ($id > 0 || ! empty($ref)) { $object->fetch_thirdparty(); - + $head = fichinter_prepare_head($object); dol_fiche_head($head, 'note', $langs->trans('InterventionCard'), -1, 'intervention'); // Intervention card - $linkback = ''.$langs->trans("BackToList").''; - - + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; // Ref customer //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); @@ -109,17 +109,17 @@ if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
    '; - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - + print '
    '; print '
    '; - + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; print '
    '; - + dol_fiche_end(); } diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index abd2d85d723..e835130de4a 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke * Copyright (C) 2010-2014 Juanjo Menent @@ -60,9 +60,9 @@ class CommandeFournisseur extends CommonOrder public $ref; public $ref_supplier; public $brouillon; - public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially - // -> 7=Canceled/Never received -> (reopen) 3=Process runing - // -> 6=Canceled -> (reopen) 2=Approved + public $statut; // 0=Draft -> 1=Validated -> 2=Approved -> 3=Ordered/Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially + // -> 7=Canceled/Never received -> (reopen) 3=Process runing + // -> 6=Canceled -> (reopen) 2=Approved // -> 9=Refused -> (reopen) 1=Validated // Note: billed or not is on another field "billed" public $statuts; // List of status @@ -128,10 +128,43 @@ class CommandeFournisseur extends CommonOrder public $multicurrency_total_tva; public $multicurrency_total_ttc; - /** - * Draft status - */ - const STATUS_DRAFT = 0; + /** + * Draft status + */ + const STATUS_DRAFT = 0; + /** + * Validated status + */ + const STATUS_VALIDATED = 1; + /** + * Accepted + */ + const STATUS_ACCEPTED = 2; + /** + * Order sent, shipment on process + */ + const STATUS_ORDERSENT = 3; + /** + * Received partially + */ + const STATUS_RECEIVED_PARTIALLY = 4; + /** + * Received completely + */ + const STATUS_RECEIVED_COMPLETELY = 5; + /** + * Order canceled + */ + const STATUS_CANCELED = 6; + /** + * Order canceled/never received + */ + const STATUS_CANCELED_AFTER_ORDER = 7; + /** + * Refused + */ + const STATUS_REFUSED = 9; + @@ -190,8 +223,8 @@ class CommandeFournisseur extends CommonOrder $sql.= ', c.fk_incoterms, c.location_incoterms'; $sql.= ', i.libelle as libelle_incoterms'; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid)"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (c.fk_mode_reglement = p.id)"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (c.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (c.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; $sql.= " WHERE c.entity = ".$conf->entity; @@ -418,11 +451,11 @@ class CommandeFournisseur extends CommonOrder $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur"; $sql.= " SET ref='".$this->db->escape($num)."',"; - $sql.= " fk_statut = 1,"; + $sql.= " fk_statut = ".self::STATUS_VALIDATED.","; $sql.= " date_valid='".$this->db->idate(dol_now())."',"; $sql.= " fk_user_valid = ".$user->id; $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND fk_statut = 0"; + $sql.= " AND fk_statut = ".self::STATUS_DRAFT; $resql=$this->db->query($sql); if (! $resql) @@ -450,8 +483,8 @@ class CommandeFournisseur extends CommonOrder // in order not to lose the attached files $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); - $dirsource = $conf->fournisseur->dir_output.'/commande/'.$oldref; - $dirdest = $conf->fournisseur->dir_output.'/commande/'.$newref; + $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref; + $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); @@ -460,7 +493,7 @@ class CommandeFournisseur extends CommonOrder { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->fournisseur->dir_output.'/commande/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + $listoffiles=dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); foreach($listoffiles as $fileentry) { $dirsource=$fileentry['name']; @@ -477,7 +510,7 @@ class CommandeFournisseur extends CommonOrder if (! $error) { $result = 1; - $this->statut = 1; + $this->statut = self::STATUS_VALIDATED; $this->ref = $num; } @@ -537,7 +570,6 @@ class CommandeFournisseur extends CommonOrder $statutshort[5] = 'StatusOrderReceivedAllShort'; $statutshort[6] = 'StatusOrderCanceledShort'; $statutshort[7] = 'StatusOrderCanceledShort'; - //$statutshort[8] = 'StatusOrderBilledShort'; $statutshort[9] = 'StatusOrderRefusedShort'; if ($mode == 0) @@ -561,7 +593,6 @@ class CommandeFournisseur extends CommonOrder if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3'); if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6'); if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5'); - if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6'); if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5'); } if ($mode == 4) @@ -573,7 +604,6 @@ class CommandeFournisseur extends CommonOrder if ($statut==4) return img_picto($langs->trans($this->statuts[$statut]),'statut3').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:''); if ($statut==5) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:''); if ($statut==6 || $statut==7) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:''); - if ($statut==8) return img_picto($langs->trans($this->statuts[$statut]),'statut6').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:''); if ($statut==9) return img_picto($langs->trans($this->statuts[$statut]),'statut5').' '.$langs->trans($this->statuts[$statut]).($billedtext?' - '.$billedtext:''); } if ($mode == 5) @@ -585,7 +615,6 @@ class CommandeFournisseur extends CommonOrder if ($statut==4) return ''.$langs->trans($statutshort[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut3'); if ($statut==5) return ''.$langs->trans($statutshort[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut6'); if ($statut==6 || $statut==7) return ''.$langs->trans($statutshort[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut5'); - if ($statut==8) return ''.$langs->trans($statutshort[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut6'); if ($statut==9) return ''.$langs->trans($statutshort[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut5'); } } @@ -594,12 +623,13 @@ class CommandeFournisseur extends CommonOrder /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option On what the link points - * @param int $notooltip 1=Disable tooltip - * @return string Chain with URL + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option On what the link points + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chain with URL */ - public function getNomUrl($withpicto=0,$option='',$notooltip=0) + public function getNomUrl($withpicto=0, $option='', $notooltip=0, $save_lastsearch_value=-1) { global $langs, $conf; @@ -619,6 +649,14 @@ class CommandeFournisseur extends CommonOrder $picto='order'; $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $linkclose=''; if (empty($notooltip)) { @@ -709,7 +747,7 @@ class CommandeFournisseur extends CommonOrder $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1'; - $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0 '; + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; if ($this->db->query($sql)) { if (! $error) @@ -807,10 +845,10 @@ class CommandeFournisseur extends CommonOrder $comment=' (second level)'; } // If double approval is required and first approval, we keep status to 1 = validated - if ($movetoapprovestatus) $sql.= ", fk_statut = 2"; - else $sql.= ", fk_statut = 1"; + if ($movetoapprovestatus) $sql.= ", fk_statut = ".self::STATUS_ACCEPTED; + else $sql.= ", fk_statut = ".self::STATUS_VALIDATED; $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND fk_statut = 1"; + $sql.= " AND fk_statut = ".self::STATUS_VALIDATED; if ($this->db->query($sql)) { @@ -860,8 +898,8 @@ class CommandeFournisseur extends CommonOrder { $this->ref = $this->newref; - if ($movetoapprovestatus) $this->statut = 2; - else $this->statut = 1; + if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED; + else $this->statut = self::STATUS_VALIDATED; if (empty($secondlevel)) // standard or first level approval { $this->date_approve = $now; @@ -914,7 +952,7 @@ class CommandeFournisseur extends CommonOrder { $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 9"; + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED; $sql .= " WHERE rowid = ".$this->id; if ($this->db->query($sql)) @@ -968,7 +1006,7 @@ class CommandeFournisseur extends CommonOrder $result = 0; if ($user->rights->fournisseur->commande->commander) { - $statut = 6; + $statut = self::STATUS_CANCELED; $this->db->begin(); @@ -1029,13 +1067,13 @@ class CommandeFournisseur extends CommonOrder { $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 3, fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."'"; + $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."'"; $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::commande", LOG_DEBUG); if ($this->db->query($sql)) { - $this->statut = 3; + $this->statut = self::STATUS_ORDERSENT; $this->methode_commande_id = $methode; $this->date_commande = $date; @@ -1136,7 +1174,7 @@ class CommandeFournisseur extends CommonOrder $sql.= ", '".$this->db->idate($now)."'"; $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null"); $sql.= ", ".$user->id; - $sql.= ", 0"; + $sql.= ", ".self::STATUS_DRAFT; $sql.= ", ".$this->db->escape($this->source); $sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'"; $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null'); @@ -1271,7 +1309,7 @@ class CommandeFournisseur extends CommonOrder $objFrom = clone $this; $this->id=0; - $this->statut=0; + $this->statut=self::STATUS_DRAFT; // Clear fields $this->user_author_id = $user->id; @@ -1411,7 +1449,7 @@ class CommandeFournisseur extends CommonOrder $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->fk_soc); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc if ($result > 0) { - $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it if ($remise_percent == 0 && $prod->remise_percent !=0) @@ -1620,7 +1658,7 @@ class CommandeFournisseur extends CommonOrder $now=dol_now(); - if (($this->statut == 3 || $this->statut == 4 || $this->statut == 5)) + if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) { $this->db->begin(); @@ -1943,10 +1981,16 @@ class CommandeFournisseur extends CommonOrder if ($user->rights->fournisseur->commande->receptionner) { - if ($type == 'par') $statut = 4; - if ($type == 'tot') $statut = 5; - if ($type == 'nev') $statut = 7; - if ($type == 'can') $statut = 7; + // Define the new status + if ($type == 'par') $statut = self::STATUS_RECEIVED_PARTIALLY; + elseif ($type == 'tot') $statut = self::STATUS_RECEIVED_COMPLETELY; + elseif ($type == 'nev') $statut = self::STATUS_CANCELED_AFTER_ORDER; + elseif ($type == 'can') $statut = self::STATUS_CANCELED_AFTER_ORDER; + else { + $error++; + dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR); + return -2; + } // Some checks to accept the record if (! empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) @@ -1980,13 +2024,6 @@ class CommandeFournisseur extends CommonOrder // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty). - if (! $error && ! ($statut == 4 or $statut == 5 or $statut == 7)) - { - $error++; - dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR); - $result = -2; - } - if (! $error) { $this->db->begin(); @@ -1994,7 +2031,7 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql.= " SET fk_statut = ".$statut; $sql.= " WHERE rowid = ".$this->id; - $sql.= " AND fk_statut IN (3,4)"; // Process running or Partially received + $sql.= " AND fk_statut IN (".self::STATUS_ORDERSENT.",".self::STATUS_RECEIVED_PARTIALLY.")"; // Process running or Partially received dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); $resql=$this->db->query($sql); @@ -2217,7 +2254,7 @@ class CommandeFournisseur extends CommonOrder * @param int $status New status * @return int <0 if KO, >0 if OK */ - public function setStatus($user,$status) + public function setStatus($user, $status) { global $conf,$langs; $error=0; @@ -2236,12 +2273,11 @@ class CommandeFournisseur extends CommonOrder $trigger_name[0] = 'DRAFT'; $trigger_name[1] = 'VALIDATED'; $trigger_name[2] = 'APPROVED'; - $trigger_name[3] = 'ONPROCESS'; + $trigger_name[3] = 'ORDERED'; // Ordered $trigger_name[4] = 'RECEIVED_PARTIALLY'; - $trigger_name[5] = 'RECEIVED_ALL'; + $trigger_name[5] = 'RECEIVED_COMPLETELY'; $trigger_name[6] = 'CANCELED'; $trigger_name[7] = 'CANCELED'; - $trigger_name[8] = 'BILLED'; $trigger_name[9] = 'REFUSED'; // Call trigger @@ -2606,7 +2642,7 @@ class CommandeFournisseur extends CommonOrder * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * * @param User $user Objet user - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK + * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK */ function load_board($user) { @@ -2623,7 +2659,7 @@ class CommandeFournisseur extends CommonOrder $clause = " AND"; } $sql.= $clause." c.entity = ".$conf->entity; - $sql.= " AND (c.fk_statut BETWEEN 1 AND 2)"; + $sql.= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")"; if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id; $resql=$this->db->query($sql); diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index e124730b568..e813268b8b2 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -517,8 +517,8 @@ class FactureFournisseur extends CommonInvoice $sql.= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid)"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id)"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON (t.fk_cond_reglement = cr.rowid AND cr.entity = " . getEntity('c_payment_term') . ")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON (t.fk_mode_reglement = p.id AND p.entity = " . getEntity('c_paiement') . ")"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid'; if ($id) $sql.= " WHERE t.rowid=".$id; if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'"; @@ -1090,6 +1090,10 @@ class FactureFournisseur extends CommonInvoice $error=0; dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse); + // Force to have object complete for checks + $this->fetch_thirdparty(); + $this->fetch_lines(); + // Check parameters if ($this->statut > self::STATUS_DRAFT) // This is to avoid to validate twice (avoid errors on logs and stock management) { @@ -1808,7 +1812,7 @@ class FactureFournisseur extends CommonInvoice $response->warning_delay=$conf->facture->fournisseur->warning_delay/60/60/24; $response->label=$langs->trans("SupplierBillsToPay"); - $response->url=DOL_URL_ROOT.'/fourn/facture/list.php?filtre=fac.fk_statut:1,paye:0&mainmenu=accountancy&leftmenu=suppliers_bills'; + $response->url=DOL_URL_ROOT.'/fourn/facture/list.php?search_status=1&mainmenu=accountancy&leftmenu=suppliers_bills'; $response->img=img_object($langs->trans("Bills"),"bill"); $facturestatic = new FactureFournisseur($this->db); @@ -1839,15 +1843,16 @@ class FactureFournisseur extends CommonInvoice /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param string $option Where point the link - * @param int $max Max length of shown ref - * @param int $short 1=Return just URL - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip - * @return string String with URL + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param string $option Where point the link + * @param int $max Max length of shown ref + * @param int $short 1=Return just URL + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL */ - public function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='',$notooltip=0) + public function getNomUrl($withpicto=0, $option='',$max=0, $short=0, $moretitle='', $notooltip=0, $save_lastsearch_value=-1) { global $langs, $conf; @@ -1858,6 +1863,14 @@ class FactureFournisseur extends CommonInvoice if ($short) return $url; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + $picto='bill'; if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note @@ -2541,15 +2554,10 @@ class SupplierInvoiceLine extends CommonObjectLine } // Clean parameters - if (empty($this->tva_tx)) { - $this->tva_tx = 0; - } - if (empty($this->localtax1_tx)) { - $this->localtax1_tx = 0; - } - if (empty($this->localtax2_tx)) { - $this->localtax2_tx = 0; - } + if (empty($this->remise_percent)) $this->remise_percent = 0; + if (empty($this->tva_tx)) $this->tva_tx = 0; + if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; + if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; $this->db->begin(); diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 5a63cb3f1ff..504147adff3 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -180,16 +180,18 @@ class ProductFournisseur extends Product * @param Societe $fourn Supplier * @param int $availability Product availability * @param string $ref_fourn Supplier ref - * @param float $tva_tx VAT rate + * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string) * @param string $charges costs affering to product * @param float $remise_percent Discount regarding qty (percent) * @param float $remise Discount regarding qty (amount) * @param int $newnpr Set NPR or not * @param int $delivery_time_days Delay in days for delivery (max). May be '' if not defined. * @param string $supplier_reputation Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER) + * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function). + * @param string $newdefaultvatcode Default vat code * @return int <0 if KO, >=0 if OK */ - function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges=0, $remise_percent=0, $remise=0, $newnpr=0, $delivery_time_days=0, $supplier_reputation='') + function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges=0, $remise_percent=0, $remise=0, $newnpr=0, $delivery_time_days=0, $supplier_reputation='', $localtaxes_array=array(), $newdefaultvatcode='') { global $conf, $langs; //global $mysoc; @@ -217,6 +219,25 @@ class ProductFournisseur extends Product $now=dol_now(); + $newvat = $tva_tx; + + if (count($localtaxes_array) > 0) + { + $localtaxtype1=$localtaxes_array['0']; + $localtax1=$localtaxes_array['1']; + $localtaxtype2=$localtaxes_array['2']; + $localtax2=$localtaxes_array['3']; + } + else // old method. deprecated because ot can't retreive type + { + $localtaxtype1='0'; + $localtax1=get_localtax($newvat,1); + $localtaxtype2='0'; + $localtax2=get_localtax($newvat,2); + } + if (empty($localtax1)) $localtax1=0; // If = '' then = 0 + if (empty($localtax2)) $localtax2=0; // If = '' then = 0 + $this->db->begin(); if ($this->product_fourn_price_id > 0) @@ -230,9 +251,15 @@ class ProductFournisseur extends Product $sql.= " remise = ".$remise.","; $sql.= " unitprice = ".$unitBuyPrice.","; $sql.= " unitcharges = ".$unitCharges.","; // deprecated - $sql.= " tva_tx = ".$tva_tx.","; $sql.= " fk_availability = ".$availability.","; $sql.= " entity = ".$conf->entity.","; + $sql.= " tva_tx = ".price2num($tva_tx).","; + // TODO Add localtax1 and localtax2 + //$sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').","; + //$sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').","; + //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$localtaxtype1."'":"'0'").","; + //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$localtaxtype2."'":"'0'").","; + $sql.= " default_vat_code=".($newdefaultvatcode?"'".$this->db->escape($newdefaultvatcode)."'":"null").","; $sql.= " info_bits = ".$newnpr.","; $sql.= " charges = ".$charges.","; // deprecated $sql.= " delivery_time_days = ".($delivery_time_days != '' ? $delivery_time_days : 'null').","; @@ -279,7 +306,7 @@ class ProductFournisseur extends Product if ($resql) { // Add price for this quantity to supplier $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_fournisseur_price("; - $sql .= "datec, fk_product, fk_soc, ref_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, unitcharges, fk_availability, info_bits, entity, delivery_time_days,supplier_reputation)"; + $sql .= "datec, fk_product, fk_soc, ref_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, unitcharges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation)"; $sql .= " values('" . $this->db->idate($now) . "',"; $sql .= " " . $this->id . ","; $sql .= " " . $fourn->id . ","; @@ -294,6 +321,7 @@ class ProductFournisseur extends Product $sql .= " " . $charges . ","; $sql .= " " . $unitCharges . ","; $sql .= " " . $availability . ","; + $sql .= " ".($newdefaultvatcode?"'".$this->db->escape($newdefaultvatcode)."'":"null").","; $sql .= " " . $newnpr . ","; $sql .= $conf->entity . ","; $sql .= $delivery_time_days . ","; @@ -364,9 +392,9 @@ class ProductFournisseur extends Product function fetch_product_fournisseur_price($rowid, $ignore_expression = 0) { global $conf; - $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability,"; + $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.default_vat_code, pfp.fk_availability,"; $sql.= " pfp.fk_soc, pfp.ref_fourn, pfp.fk_product, pfp.charges, pfp.unitcharges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,"; // , pfp.recuperableonly as fourn_tva_npr"; FIXME this field not exist in llx_product_fournisseur_price - $sql.=" pfp.supplier_reputation"; + $sql.= " pfp.supplier_reputation"; $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql.= " WHERE pfp.rowid = ".$rowid; @@ -392,11 +420,14 @@ class ProductFournisseur extends Product $this->fourn_unitprice = $obj->unitprice; $this->fourn_unitcharges = $obj->unitcharges; // deprecated $this->fourn_tva_tx = $obj->tva_tx; - //$this->fourn_tva_npr = $obj->fourn_tva_npr; // TODO this field not exist in llx_product_fournisseur_price. We should add it ? + // TODO + // $this->fourn_tva_npr = $obj->fourn_tva_npr; // TODO this field not exist in llx_product_fournisseur_price. We should add it ? + // Add also localtaxes $this->fk_availability = $obj->fk_availability; $this->delivery_time_days = $obj->delivery_time_days; $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression; - $this->supplier_reputation = $obj->supplier_reputation; + $this->supplier_reputation = $obj->supplier_reputation; + $this->default_vat_code = $obj->default_vat_code; if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) { diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php index 25639bfd3f9..43f39ce2287 100644 --- a/htdocs/fourn/class/paiementfourn.class.php +++ b/htdocs/fourn/class/paiementfourn.class.php @@ -34,11 +34,11 @@ require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; */ class PaiementFourn extends Paiement { - public $element='payment_supplier'; - public $table_element='paiementfourn'; - public $picto = 'payment'; - - var $statut; //Status of payment. 0 = unvalidated; 1 = validated + public $element='payment_supplier'; + public $table_element='paiementfourn'; + public $picto = 'payment'; + + var $statut; //Status of payment. 0 = unvalidated; 1 = validated // fk_paiement dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...) // fk_paiement dans llx_paiement_facture est le rowid du paiement @@ -74,14 +74,15 @@ class PaiementFourn extends Paiement */ function fetch($id, $ref='', $fk_bank='') { - $error=0; - + $error=0; + $sql = 'SELECT p.rowid, p.ref, p.entity, p.datep as dp, p.amount, p.statut, p.fk_bank,'; $sql.= ' c.code as paiement_code, c.libelle as paiement_type,'; $sql.= ' p.num_paiement, p.note, b.fk_account'; $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiementfourn as p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid '; $sql.= ' WHERE p.fk_paiement = c.id'; + $sql.= ' AND c.entity IN (' . getEntity('c_paiement').')'; if ($id > 0) $sql.= ' AND p.rowid = '.$id; else if ($ref) @@ -141,9 +142,9 @@ class PaiementFourn extends Paiement // Clean parameters $totalamount = 0; $totalamount_converted = 0; - + dol_syslog(get_class($this)."::create", LOG_DEBUG); - + if ($way == 'dolibarr') { $amounts = &$this->amounts; @@ -154,13 +155,13 @@ class PaiementFourn extends Paiement $amounts = &$this->multicurrency_amounts; $amounts_to_update = &$this->amounts; } - + foreach ($amounts as $key => $value) { $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value, $way, 'facture_fourn'); $totalamount_converted += $value_converted; $amounts_to_update[$key] = price2num($value_converted, 'MT'); - + $newvalue = price2num($value,'MT'); $amounts[$key] = $newvalue; $totalamount += $newvalue; @@ -174,7 +175,7 @@ class PaiementFourn extends Paiement { $ref = $this->getNextNumRef(''); $now=dol_now(); - + if ($way == 'dolibarr') { $total = $totalamount; @@ -185,7 +186,7 @@ class PaiementFourn extends Paiement $total = $totalamount_converted; // Maybe use price2num with MT for the converted value $mtotal = $totalamount; } - + $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn ('; $sql.= 'ref, entity, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, fk_user_author, fk_bank)'; $sql.= " VALUES ('".$this->db->escape($ref)."', ".$conf->entity.", '".$this->db->idate($now)."',"; @@ -209,22 +210,22 @@ class PaiementFourn extends Paiement if ($resql) { // If we want to closed payed invoices - if ($closepaidinvoices) - { - $invoice=new FactureFournisseur($this->db); - $invoice->fetch($facid); - $paiement = $invoice->getSommePaiement(); - //$creditnotes=$invoice->getSumCreditNotesUsed(); - $creditnotes=0; - //$deposits=$invoice->getSumDepositsUsed(); - $deposits=0; - $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); - $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); - if ($remaintopay == 0) - { - $result=$invoice->set_paid($user, '', ''); - } - else dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing."); + if ($closepaidinvoices) + { + $invoice=new FactureFournisseur($this->db); + $invoice->fetch($facid); + $paiement = $invoice->getSommePaiement(); + //$creditnotes=$invoice->getSumCreditNotesUsed(); + $creditnotes=0; + //$deposits=$invoice->getSumDepositsUsed(); + $deposits=0; + $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT'); + $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT'); + if ($remaintopay == 0) + { + $result=$invoice->set_paid($user, '', ''); + } + else dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing."); } } else @@ -242,10 +243,10 @@ class PaiementFourn extends Paiement if (! $error) { - // Call trigger - $result=$this->call_trigger('PAYMENT_SUPPLIER_CREATE',$user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result=$this->call_trigger('PAYMENT_SUPPLIER_CREATE',$user); + if ($result < 0) $error++; + // End call triggers } } else @@ -264,7 +265,7 @@ class PaiementFourn extends Paiement if ($totalamount <> 0 && $error == 0) // On accepte les montants negatifs { $this->amount=$total; - $this->total=$total; + $this->total=$total; $this->multicurrency_amount=$mtotal; $this->db->commit(); dol_syslog('PaiementFourn::Create Ok Total = '.$this->total); @@ -288,8 +289,8 @@ class PaiementFourn extends Paiement */ function delete($notrigger=0) { - global $conf, $user, $langs; - + global $conf, $user, $langs; + $bank_line_id = $this->bank_line; $this->db->begin(); @@ -345,32 +346,32 @@ class PaiementFourn extends Paiement // Supprimer l'ecriture bancaire si paiement lie a ecriture if ($bank_line_id) { - $accline = new AccountLine($this->db); - $result=$accline->fetch($bank_line_id); - if ($result > 0) // If result = 0, record not found, we don't try to delete - { - $result=$accline->delete($user); - } - if ($result < 0) - { - $this->error=$accline->error; - $this->db->rollback(); - return -4; - } + $accline = new AccountLine($this->db); + $result=$accline->fetch($bank_line_id); + if ($result > 0) // If result = 0, record not found, we don't try to delete + { + $result=$accline->delete($user); + } + if ($result < 0) + { + $this->error=$accline->error; + $this->db->rollback(); + return -4; + } } - + if (! $notrigger) { - // Appel des triggers - $result=$this->call_trigger('PAYMENT_SUPPLIER_DELETE', $user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } - // Fin appel triggers + // Appel des triggers + $result=$this->call_trigger('PAYMENT_SUPPLIER_DELETE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // Fin appel triggers } - + $this->db->commit(); return 1; } @@ -465,23 +466,23 @@ class PaiementFourn extends Paiement } /** - * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) - * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle - */ + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle + */ function getLibStatut($mode=0) { return $this->LibStatut($this->statut,$mode); } /** - * Renvoi le libelle d'un statut donne - * - * @param int $status Statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut - */ + * Renvoi le libelle d'un statut donne + * + * @param int $status Statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ function LibStatut($status,$mode=0) { global $langs; @@ -539,24 +540,24 @@ class PaiementFourn extends Paiement global $langs; $result=''; - $text=$this->ref; // Sometimes ref contains label - if (preg_match('/^\((.*)\)$/i',$text,$reg)) { - // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1]=='paiement') $reg[1]='Payment'; - $text=$langs->trans($reg[1]); - } - $label = $langs->trans("ShowPayment").': '.$text; + $text=$this->ref; // Sometimes ref contains label + if (preg_match('/^\((.*)\)$/i',$text,$reg)) { + // Label generique car entre parentheses. On l'affiche en le traduisant + if ($reg[1]=='paiement') $reg[1]='Payment'; + $text=$langs->trans($reg[1]); + } + $label = $langs->trans("ShowPayment").': '.$text; - $link = ''; - $linkend=''; + $link = ''; + $linkend=''; - if ($withpicto) $result.=($link.img_object($langs->trans("ShowPayment"), 'payment', 'class="classfortooltip"').$linkend); + if ($withpicto) $result.=($link.img_object($langs->trans("ShowPayment"), 'payment', 'class="classfortooltip"').$linkend); if ($withpicto && $withpicto != 2) $result.=' '; if ($withpicto != 2) $result.=$link.$text.$linkend; return $result; } - + /** * Initialise an instance with random values. * Used to build previews or test instances. @@ -580,7 +581,7 @@ class PaiementFourn extends Paiement $this->facid = 1; $this->datepaye = $nownotime; } - + /** * Return next reference of supplier invoice not already used (or last reference) * according to numbering module defined into constant SUPPLIER_PAYMENT_ADDON @@ -698,13 +699,13 @@ class PaiementFourn extends Paiement if (empty($modele)) { - return 0; + return 0; } else { - $modelpath = "core/modules/supplier_payment/pdf/"; + $modelpath = "core/modules/supplier_payment/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); } } @@ -712,13 +713,13 @@ class PaiementFourn extends Paiement /** * get the right way of payment - * + * * @return string 'dolibarr' if standard comportment or paid in dolibarr currency, 'customer' if payment received from multicurrency inputs */ function getWay() { global $conf; - + $way = 'dolibarr'; if (!empty($conf->multicurrency->enabled)) { @@ -731,7 +732,7 @@ class PaiementFourn extends Paiement } } } - + return $way; } } diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index f121a9e371f..31a40658251 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -45,8 +45,8 @@ if (! empty($conf->supplier_proposal->enabled)) if (!empty($conf->produit->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.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 NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -54,16 +54,7 @@ if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -$langs->load('admin'); -$langs->load('orders'); -$langs->load('sendings'); -$langs->load('companies'); -$langs->load('bills'); -$langs->load('propal'); -$langs->load('supplier_proposal'); -$langs->load('deliveries'); -$langs->load('products'); -$langs->load('stocks'); +$langs->loadLangs(array('admin','orders','sendings','companies','bills','propal','supplier_proposal','deliveries','products','stocks','productbatch')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); $id = GETPOST('id','int'); @@ -104,8 +95,8 @@ $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Load object if ($id > 0 || ! empty($ref)) { - $ret = $object->fetch($id, $ref); - if ($ret < 0) dol_print_error($db,$object->error); + $ret = $object->fetch($id, $ref); + if ($ret < 0) dol_print_error($db,$object->error); $ret = $object->fetch_thirdparty(); if ($ret < 0) dol_print_error($db,$object->error); } @@ -152,7 +143,7 @@ if (empty($reshook)) if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) { - $result=$object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); + $result=$object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -166,14 +157,14 @@ if (empty($reshook)) // payment conditions if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // payment mode if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) { - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -190,7 +181,7 @@ if (empty($reshook)) // bank account if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -204,72 +195,72 @@ if (empty($reshook)) // Set project if ($action == 'classin' && $user->rights->fournisseur->commande->creer) { - $result=$object->setProject($projectid); + $result=$object->setProject($projectid); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } if ($action == 'setremisepercent' && $user->rights->fournisseur->commande->creer) { - $result = $object->set_remise($user, $_POST['remise_percent']); + $result = $object->set_remise($user, $_POST['remise_percent']); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } if ($action == 'reopen') // no test on permission here, permission to use will depends on status { - if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) - { - if ($object->statut == 1) $newstatus=0; // Validated->Draft - else if ($object->statut == 2) $newstatus=0; // Approved->Draft - else if ($object->statut == 3) $newstatus=2; // Ordered->Approved - else if ($object->statut == 4) $newstatus=3; - else if ($object->statut == 5) - { - //$newstatus=2; // Ordered - // TODO Can we set it to submited ? - //$newstatus=3; // Submited - // TODO If there is at least one reception, we can set to Received->Received partially - $newstatus=4; // Received partially + if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) + { + if ($object->statut == 1) $newstatus=0; // Validated->Draft + else if ($object->statut == 2) $newstatus=0; // Approved->Draft + else if ($object->statut == 3) $newstatus=2; // Ordered->Approved + else if ($object->statut == 4) $newstatus=3; + else if ($object->statut == 5) + { + //$newstatus=2; // Ordered + // TODO Can we set it to submited ? + //$newstatus=3; // Submited + // TODO If there is at least one reception, we can set to Received->Received partially + $newstatus=4; // Received partially - } - else if ($object->statut == 6) $newstatus=2; // Canceled->Approved - else if ($object->statut == 7) $newstatus=3; // Canceled->Process running - else if ($object->statut == 9) $newstatus=1; // Refused->Validated - else $newstatus = 2; + } + else if ($object->statut == 6) $newstatus=2; // Canceled->Approved + else if ($object->statut == 7) $newstatus=3; // Canceled->Process running + else if ($object->statut == 9) $newstatus=1; // Refused->Validated + else $newstatus = 2; - //print "old status = ".$object->statut.' new status = '.$newstatus; - $db->begin(); + //print "old status = ".$object->statut.' new status = '.$newstatus; + $db->begin(); - $result = $object->setStatus($user, $newstatus); - if ($result > 0) - { - // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet. - $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql.= ' SET billed = 0'; - $sql.= ' WHERE rowid = '.$object->id; + $result = $object->setStatus($user, $newstatus); + if ($result > 0) + { + // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet. + $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; + $sql.= ' SET billed = 0'; + $sql.= ' WHERE rowid = '.$object->id; - $resql=$db->query($sql); + $resql=$db->query($sql); - if ($newstatus == 0) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql.= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; - $sql.= ' WHERE rowid = '.$object->id; + if ($newstatus == 0) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; + $sql.= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; + $sql.= ' WHERE rowid = '.$object->id; - $resql=$db->query($sql); - } + $resql=$db->query($sql); + } - $db->commit(); + $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - else + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else { $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } - } + setEventMessages($object->error, $object->errors, 'errors'); + } + } } /* @@ -286,10 +277,10 @@ if (empty($reshook)) // Add a product line if ($action == 'addline' && $user->rights->fournisseur->commande->creer) { - $db->begin(); + $db->begin(); - $langs->load('errors'); - $error = 0; + $langs->load('errors'); + $error = 0; // Set if we used free entry or predefined product $predef=''; @@ -314,43 +305,43 @@ if (empty($reshook)) $remise_percent=GETPOST('remise_percent'.$predef); $price_ht_devise = GETPOST('multicurrency_price_ht'); - // 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')) { @@ -367,14 +358,14 @@ if (empty($reshook)) } // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $txtva par celui du produit - 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); + // Ecrase $desc par celui du produit + // Ecrase $txtva par celui du produit + 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); - if (empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED)) // TODO this test seems useless - { + if (empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED)) // TODO this test seems useless + { $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, ...) } @@ -386,67 +377,67 @@ 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); + } - if ($idprod > 0) - { - $label = $productsupplier->label; + 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); - $type = $productsupplier->type; + $type = $productsupplier->type; - $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); - $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('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); - $result=$object->addline( - $desc, - $productsupplier->fourn_pu, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $idprod, - $productsupplier->product_fourn_price_id, - $productsupplier->fourn_ref, - $remise_percent, - 'HT', - $pu_ttc, - $type, - $tva_npr, - '', - $date_start, - $date_end, - $array_options, - $productsupplier->fk_unit - ); - } - if ($idprod == -99 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); - } - } - else if (empty($error)) + $result=$object->addline( + $desc, + $productsupplier->fourn_pu, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $idprod, + $productsupplier->product_fourn_price_id, + $productsupplier->fourn_ref, + $remise_percent, + 'HT', + $pu_ttc, + $type, + $tva_npr, + '', + $date_start, + $date_end, + $array_options, + $productsupplier->fk_unit + ); + } + if ($idprod == -99 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); + } + } + else if (empty($error)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); @@ -458,93 +449,93 @@ 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 (GETPOST('price_ht')!=='') - { - $price_base_type = 'HT'; - $ht = price2num(GETPOST('price_ht')); - $ttc = 0; - } - else - { - $ttc = price2num(GETPOST('price_ttc')); - $ht = $ttc / (1 + ($tva_tx / 100)); - $price_base_type = 'HT'; - } + if (GETPOST('price_ht')!=='') + { + $price_base_type = 'HT'; + $ht = price2num(GETPOST('price_ht')); + $ttc = 0; + } + else + { + $ttc = price2num(GETPOST('price_ttc')); + $ht = $ttc / (1 + ($tva_tx / 100)); + $price_base_type = 'HT'; + } $pu_ht_devise = price2num($price_ht_devise, 'MU'); $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end, $array_options, $fk_unit, $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(); - $ret=$object->fetch($object->id); // Reload to get new records + $ret=$object->fetch($object->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 + // 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['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 = ''; } /* @@ -555,128 +546,135 @@ if (empty($reshook)) $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0); if ($lineid) - { - $line = new CommandeFournisseurLigne($db); - $res = $line->fetch($lineid); - if (!$res) dol_print_error($db); - } - - $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('/\*/', $vat_rate)) - $info_bits |= 0x01; - - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); - $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); - - if (GETPOST('price_ht') != '') - { - $price_base_type = 'HT'; - $ht = price2num(GETPOST('price_ht')); - } - else - { - $vatratecleaned = $vat_rate; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" - { - $vatratecleaned = trim($reg[1]); - $vatratecode = $reg[2]; - } - - $ttc = price2num(GETPOST('price_ttc')); - $ht = $ttc / (1 + ($vatratecleaned / 100)); - $price_base_type = 'HT'; - } - - $pu_ht_devise = GETPOST('multicurrency_subprice'); - - // Extrafields Lines - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - // Unset extrafield POST Data - if (is_array($extralabelsline)) { - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } + { + $line = new CommandeFournisseurLigne($db); + $res = $line->fetch($lineid); + if (!$res) dol_print_error($db); } - $result = $object->updateline( - $lineid, - $_POST['product_desc'], - $ht, - $_POST['qty'], - $_POST['remise_percent'], - $vat_rate, - $localtax1_rate, - $localtax2_rate, - $price_base_type, - 0, - isset($_POST["type"])?$_POST["type"]:$line->product_type, - false, - $date_start, - $date_end, - $array_options, - $_POST['units'], - $pu_ht_devise - ); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['idprodfournprice']); - unset($_POST['remmise_percent']); - unset($_POST['dp_desc']); - unset($_POST['np_desc']); - unset($_POST['pu']); - unset($_POST['tva_tx']); - unset($_POST['date_start']); - unset($_POST['date_end']); - unset($_POST['units']); - unset($localtax1_tx); - unset($localtax2_tx); + $productsupplier = new ProductFournisseur($db); + if ($productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid','int')) < 0 ) + { + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); + } - 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']); + $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')); - if ($result >= 0) - { - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->modelpdf; - $ret = $object->fetch($id); // Reload to get new records + // 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, $mysoc, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); + + if (GETPOST('price_ht') != '') + { + $price_base_type = 'HT'; + $ht = price2num(GETPOST('price_ht')); + } + else + { + $vatratecleaned = $vat_rate; + if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" + { + $vatratecleaned = trim($reg[1]); + $vatratecode = $reg[2]; + } + + $ttc = price2num(GETPOST('price_ttc')); + $ht = $ttc / (1 + ($vatratecleaned / 100)); + $price_base_type = 'HT'; + } + + $pu_ht_devise = GETPOST('multicurrency_subprice'); + + // Extrafields Lines + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Unset extrafield POST Data + if (is_array($extralabelsline)) { + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + $result = $object->updateline( + $lineid, + $_POST['product_desc'], + $ht, + $_POST['qty'], + $_POST['remise_percent'], + $vat_rate, + $localtax1_rate, + $localtax2_rate, + $price_base_type, + 0, + isset($_POST["type"])?$_POST["type"]:$line->product_type, + false, + $date_start, + $date_end, + $array_options, + $_POST['units'], + $pu_ht_devise + ); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['idprodfournprice']); + unset($_POST['remmise_percent']); + unset($_POST['dp_desc']); + unset($_POST['np_desc']); + unset($_POST['pu']); + unset($_POST['tva_tx']); + unset($_POST['date_start']); + unset($_POST['date_end']); + unset($_POST['units']); + unset($localtax1_tx); + unset($localtax2_tx); + + 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']); + + if ($result >= 0) + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->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); + } + } + else + { + dol_print_error($db,$object->error); + exit; + } - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - } - else - { - dol_print_error($db,$object->error); - exit; - } } // Remove a product line @@ -714,49 +712,49 @@ if (empty($reshook)) // Validate if ($action == 'confirm_valid' && $confirm == 'yes' && - ((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))) + ((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))) ) { - $object->date_commande=dol_now(); - $result = $object->valid($user); - if ($result >= 0) - { - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model=$object->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); - } - } - else + $object->date_commande=dol_now(); + $result = $object->valid($user); + if ($result >= 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + // 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 we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) - { - $action='confirm_approve'; // can make standard or first level approval also if permission is set - } + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + + // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step + if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) + { + $action='confirm_approve'; // can make standard or first level approval also if permission is set + } } if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) { - $idwarehouse=GETPOST('idwarehouse', 'int'); + $idwarehouse=GETPOST('idwarehouse', 'int'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -766,95 +764,95 @@ if (empty($reshook)) $qualified_for_stock_change=$object->hasProductsOrServices(1); } - // Check parameters - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER - { - if (! $idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; - } - } - - if (! $error) - { - $result = $object->approve($user, $idwarehouse, ($action=='confirm_approve2'?1:0)); - if ($result > 0) - { - 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); - } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER + { + if (! $idwarehouse || $idwarehouse == -1) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $error++; + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action=''; + } + } + + if (! $error) + { + $result = $object->approve($user, $idwarehouse, ($action=='confirm_approve2'?1:0)); + if ($result > 0) + { + 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); + } + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) { - $result = $object->refuse($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->refuse($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) { - $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); - if ($result > 0) - { - 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); - } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - $action = ''; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); + if ($result > 0) + { + 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); + } + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + $action = ''; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->commande->supprimer) { - $result=$object->delete($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->delete($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Action clone object @@ -876,7 +874,7 @@ if (empty($reshook)) } else { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $action=''; } } @@ -886,44 +884,44 @@ if (empty($reshook)) // Set status of reception (complete, partial, ...) if ($action == 'livraison' && $user->rights->fournisseur->commande->receptionner) { - if (GETPOST("type") != '') - { - $date_liv = dol_mktime(GETPOST('rehour'),GETPOST('remin'),GETPOST('resec'),GETPOST("remonth"),GETPOST("reday"),GETPOST("reyear")); + if (GETPOST("type") != '') + { + $date_liv = dol_mktime(GETPOST('rehour'),GETPOST('remin'),GETPOST('resec'),GETPOST("remonth"),GETPOST("reday"),GETPOST("reyear")); - $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($result > 0) - { - $langs->load("deliveries"); - setEventMessages($langs->trans("DeliveryStateSaved"), null); - $action = ''; - } - else if($result == -3) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - else - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors'); - } + $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($result > 0) + { + $langs->load("deliveries"); + setEventMessages($langs->trans("DeliveryStateSaved"), null); + $action = ''; + } + else if($result == -3) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + else + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors'); + } } if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) { - $result = $object->cancel($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->cancel($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Actions when printing a doc from card @@ -985,25 +983,25 @@ if (empty($reshook)) { $error=0; - if ($socid <1) - { - setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors'); - $action='create'; - $error++; - } + if ($socid <1) + { + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors'); + $action='create'; + $error++; + } - if (! $error) - { - $db->begin(); + if (! $error) + { + $db->begin(); - // Creation commande - $object->ref_supplier = GETPOST('refsupplier'); - $object->socid = $socid; + // Creation commande + $object->ref_supplier = GETPOST('refsupplier'); + $object->socid = $socid; $object->cond_reglement_id = GETPOST('cond_reglement_id'); - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); - $object->note_private = GETPOST('note_private','none'); - $object->note_public = GETPOST('note_public','none'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); + $object->note_private = GETPOST('note_private','none'); + $object->note_public = GETPOST('note_public','none'); $object->date_livraison = $datelivraison; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); @@ -1012,23 +1010,23 @@ if (empty($reshook)) $object->fk_project = GETPOST('projectid'); // Fill array 'array_options' with data from add form - if (! $error) - { + if (! $error) + { $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if ($ret < 0) $error++; - } + } - if (! $error) - { - // If creation from another object of another module (Example: origin=propal, originid=1) + if (! $error) + { + // If creation from another object of another module (Example: origin=propal, originid=1) if (! empty($origin) && ! empty($originid)) { if ($origin == 'order' || $origin == 'commande') { - $element = $subelement = 'commande'; - } - else - { + $element = $subelement = 'commande'; + } + else + { $element = 'supplier_proposal'; $subelement = 'supplier_proposal'; } @@ -1087,7 +1085,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_option = $lines[$i]->array_options; @@ -1096,14 +1094,14 @@ if (empty($reshook)) $result = $productsupplier->find_min_price_product_fournisseur($lines[$i]->fk_product, $lines[$i]->qty, $srcobject->socid); if ($result>=0) { - $tva_tx = $lines[$i]->tva_tx; + $tva_tx = $lines[$i]->tva_tx; - if ($origin=="commande") - { - $soc=new societe($db); - $soc->fetch($socid); - $tva_tx=get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $productsupplier->product_fourn_price_id); - } + if ($origin=="commande") + { + $soc=new societe($db); + $soc->fetch($socid); + $tva_tx=get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $productsupplier->product_fourn_price_id); + } $result = $object->addline( $desc, @@ -1152,132 +1150,132 @@ if (empty($reshook)) if ($reshook < 0) $error ++; } else { - setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); $error ++; } } else { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $error ++; } } else { - $id = $object->create($user); - if ($id < 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } + $id = $object->create($user); + if ($id < 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } } - } + } - if ($error) - { - $langs->load("errors"); - $db->rollback(); - $action='create'; - $_GET['socid']=$_POST['socid']; - } - else + if ($error) { - $db->commit(); - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); - exit; - } - } + $langs->load("errors"); + $db->rollback(); + $action='create'; + $_GET['socid']=$_POST['socid']; + } + else + { + $db->commit(); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + exit; + } + } } if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && ! GETPOST('cancel','alpha')) { - $ws_url = $object->thirdparty->webservices_url; - $ws_key = $object->thirdparty->webservices_key; - $ws_user = GETPOST('ws_user','alpha'); - $ws_password = GETPOST('ws_password','alpha'); - $ws_entity = GETPOST('ws_entity','int'); - $ws_thirdparty = GETPOST('ws_thirdparty','int'); + $ws_url = $object->thirdparty->webservices_url; + $ws_key = $object->thirdparty->webservices_key; + $ws_user = GETPOST('ws_user','alpha'); + $ws_password = GETPOST('ws_password','alpha'); + $ws_entity = GETPOST('ws_entity','int'); + $ws_thirdparty = GETPOST('ws_thirdparty','int'); - // NS and Authentication parameters - $ws_ns='http://www.dolibarr.org/ns/'; - $ws_authentication=array( - 'dolibarrkey'=>$ws_key, - 'sourceapplication'=>'DolibarrWebServiceClient', - 'login'=>$ws_user, - 'password'=>$ws_password, - 'entity'=>$ws_entity - ); + // NS and Authentication parameters + $ws_ns='http://www.dolibarr.org/ns/'; + $ws_authentication=array( + 'dolibarrkey'=>$ws_key, + 'sourceapplication'=>'DolibarrWebServiceClient', + 'login'=>$ws_user, + 'password'=>$ws_password, + 'entity'=>$ws_entity + ); - //Is sync supplier web services module activated? and everything filled? - if (empty($conf->syncsupplierwebservices->enabled)) { - setEventMessages($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name")), null, 'mesgs'); - } else if (empty($ws_url) || empty($ws_key)) { - setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors'); - } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { - setEventMessages($langs->trans("ErrorFieldsRequired"),null, 'errors'); - } - else - { - //Create SOAP client and connect it to order - $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); - $soapclient_order->soap_defencoding='UTF-8'; - $soapclient_order->decodeUTF8(false); + //Is sync supplier web services module activated? and everything filled? + if (empty($conf->syncsupplierwebservices->enabled)) { + setEventMessages($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name")), null, 'mesgs'); + } else if (empty($ws_url) || empty($ws_key)) { + setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors'); + } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { + setEventMessages($langs->trans("ErrorFieldsRequired"),null, 'errors'); + } + else + { + //Create SOAP client and connect it to order + $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); + $soapclient_order->soap_defencoding='UTF-8'; + $soapclient_order->decodeUTF8(false); - //Create SOAP client and connect it to product/service - $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); - $soapclient_product->soap_defencoding='UTF-8'; - $soapclient_product->decodeUTF8(false); + //Create SOAP client and connect it to product/service + $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); + $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->decodeUTF8(false); - //Prepare the order lines from order - $order_lines = array(); - foreach ($object->lines as $line) - { - $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); - $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); + //Prepare the order lines from order + $order_lines = array(); + foreach ($object->lines as $line) + { + $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); + $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - if ($result_product["result"]["result_code"] == "OK") - { - $order_lines[] = array( - 'desc' => $line->product_desc, - 'type' => $line->product_type, - 'product_id' => $result_product["product"]["id"], - 'vat_rate' => $line->tva_tx, - 'qty' => $line->qty, - 'price' => $line->price, - 'unitprice' => $line->subprice, - 'total_net' => $line->total_ht, - 'total_vat' => $line->total_tva, - 'total' => $line->total_ttc, - 'date_start' => $line->date_start, - 'date_end' => $line->date_end, - ); - } - } + if ($result_product["result"]["result_code"] == "OK") + { + $order_lines[] = array( + 'desc' => $line->product_desc, + 'type' => $line->product_type, + 'product_id' => $result_product["product"]["id"], + 'vat_rate' => $line->tva_tx, + 'qty' => $line->qty, + 'price' => $line->price, + 'unitprice' => $line->subprice, + 'total_net' => $line->total_ht, + 'total_vat' => $line->total_tva, + 'total' => $line->total_ttc, + 'date_start' => $line->date_start, + 'date_end' => $line->date_end, + ); + } + } - //Prepare the order header - $order = array( - 'thirdparty_id' => $ws_thirdparty, - 'date' => dol_print_date(dol_now(),'dayrfc'), - 'total_net' => $object->total_ht, - 'total_var' => $object->total_tva, - 'total' => $object->total_ttc, - 'lines' => $order_lines - ); + //Prepare the order header + $order = array( + 'thirdparty_id' => $ws_thirdparty, + 'date' => dol_print_date(dol_now(),'dayrfc'), + 'total_net' => $object->total_ht, + 'total_var' => $object->total_tva, + 'total' => $object->total_ttc, + 'lines' => $order_lines + ); - $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); - $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); + $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); + $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); - if (empty($result_order["result"]["result_code"])) //No result, check error str - { - setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); - } - else if ($result_order["result"]["result_code"] != "OK") //Something went wrong - { - setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors'); - } - else - { - setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs'); - } - } + if (empty($result_order["result"]["result_code"])) //No result, check error str + { + setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); + } + else if ($result_order["result"]["result_code"] != "OK") //Something went wrong + { + setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors'); + } + else + { + setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs'); + } + } } if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) @@ -1397,9 +1395,9 @@ if ($action=='create') $soc = $objectsrc->client; $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)); $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)); + $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_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)); @@ -1463,10 +1461,10 @@ if ($action=='create') else { print $form->select_company((empty($socid)?'':$socid), 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); - // reload page to retrieve customer informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { - print ''; - } - print ' '.$langs->trans("AddThirdParty").''; + } + print ' '.$langs->trans("AddThirdParty").''; } print ''; @@ -1506,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 '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; - } + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) + { + $langs->load("bank"); + print '' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; + } // Project if (! empty($conf->projet->enabled)) @@ -1526,13 +1524,13 @@ if ($action=='create') print ''; } - // Incoterms + // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; print ''; - 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 ''; } @@ -1541,8 +1539,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 ''; } @@ -1597,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 "\n"; + print "\n"; - dol_fiche_end(); + dol_fiche_end(); print '
    '; print ''; @@ -1636,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); @@ -1681,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; @@ -1708,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) @@ -1785,7 +1783,7 @@ elseif (! empty($object->id)) // Supplier order card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; // Ref supplier @@ -1796,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.='
    '; @@ -1943,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 @@ -1988,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 ''; @@ -2003,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); @@ -2019,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 @@ -2036,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 @@ -2125,7 +2123,7 @@ elseif (! empty($object->id)) include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print ''; // Add free products/services form @@ -2155,7 +2153,7 @@ elseif (! empty($object->id)) } } print '
    '; - print '
    '; + print '
    '; print ''; dol_fiche_end(); @@ -2177,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"); @@ -2271,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))) { @@ -2312,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 @@ -2337,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 @@ -2385,57 +2383,57 @@ 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 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 '
    '; + //print ''; + 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("OrderMode").''; - $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); - print '
    '.$langs->trans("OrderMode").''; + $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); + print '
    '.$langs->trans("Comment").'
    '; - print ''; - print '     '; - print ''; - print '
    '; - print '
    '; - 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->creer; + $delallowed=$user->rights->fournisseur->commande->supprimer; - 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)) { @@ -2470,10 +2468,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/dispatch.php b/htdocs/fourn/commande/dispatch.php index f4f05f96b78..67b22c6767c 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -547,6 +547,9 @@ if ($id > 0 || ! empty($ref)) { print "\n"; print '' . "\n"; + // hidden fields for js function + print ''; + print ''; print ''; $linktoprod = '' . img_object($langs->trans("ShowProduct"), 'product') . ' ' . $objp->ref . ''; @@ -607,9 +610,6 @@ if ($id > 0 || ! empty($ref)) { print ''; } - // hidden fields for js function - print ''; - print ''; print ''; print ''; @@ -649,16 +649,13 @@ if ($id > 0 || ! empty($ref)) { print ''; } - // hidden fields for js function - print ''; - print ''; print ''; } // Qty to dispatch print ''; print ''; - print ''; + print ''; print ''; if (! empty($conf->productbatch->enabled) && $objp->tobatch == 1) { diff --git a/htdocs/fourn/commande/document.php b/htdocs/fourn/commande/document.php index 700ce7a770a..49d739be811 100644 --- a/htdocs/fourn/commande/document.php +++ b/htdocs/fourn/commande/document.php @@ -71,7 +71,7 @@ if ($object->fetch($id,$ref) < 0) exit; } -$upload_dir = $conf->fournisseur->dir_output.'/commande/'.dol_sanitizeFileName($object->ref); +$upload_dir = $conf->fournisseur->commande->dir_output.'/'.dol_sanitizeFileName($object->ref); $object->fetch_thirdparty(); diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index 5f1e564e30b..3894cf28cc4 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -123,43 +123,43 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'cf.ref'=>'Ref', - 'cf.ref_supplier'=>'RefSupplierOrder', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'cf.note_public'=>'NotePublic', + 'cf.ref'=>'Ref', + 'cf.ref_supplier'=>'RefSupplierOrder', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'cf.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["cf.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'cf.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'cf.ref_supplier'=>array('label'=>$langs->trans("RefOrderSupplierShort"), 'checked'=>1, 'enabled'=>1), - 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), - 'u.login'=>array('label'=>$langs->trans("AuthorRequest"), 'checked'=>1), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'cf.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), - 'cf.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), - 'cf.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'cf.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'cf.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'cf.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'cf.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'cf.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), - 'cf.billed'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>1) + 'cf.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'cf.ref_supplier'=>array('label'=>$langs->trans("RefOrderSupplierShort"), 'checked'=>1, 'enabled'=>1), + 'p.project_ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>0, 'enabled'=>1), + 'u.login'=>array('label'=>$langs->trans("AuthorRequest"), 'checked'=>1), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'cf.date_commande'=>array('label'=>$langs->trans("OrderDateShort"), 'checked'=>1), + 'cf.date_delivery'=>array('label'=>$langs->trans("DateDeliveryPlanned"), 'checked'=>1, 'enabled'=>empty($conf->global->ORDER_DISABLE_DELIVERY_DATE)), + 'cf.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'cf.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'cf.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'cf.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'cf.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'cf.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'cf.billed'=>array('label'=>$langs->trans("Billed"), 'checked'=>1, 'position'=>1000, 'enabled'=>1) ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -177,277 +177,277 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - // 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'; - // Purge search criteria - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers - { - $ordermonth=''; - $orderyear=''; - $orderday=''; - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_refsupp=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_request_author=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $search_project_ref=''; - $search_status=-1; - $orderyear=''; - $ordermonth=''; - $orderday=''; - $deliveryday=''; - $deliverymonth=''; - $deliveryyear=''; - $billed=''; - $toselect=''; - $search_array_options=array(); - } - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') - || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) - { - $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation - } + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $ordermonth=''; + $orderyear=''; + $orderday=''; + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_refsupp=''; + $search_company=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_request_author=''; + $search_total_ht=''; + $search_total_vat=''; + $search_total_ttc=''; + $search_project_ref=''; + $search_status=-1; + $orderyear=''; + $ordermonth=''; + $orderday=''; + $deliveryday=''; + $deliverymonth=''; + $deliveryyear=''; + $billed=''; + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } - // Mass actions - $objectclass='CommandeFournisseur'; - $objectlabel='SupplierOrders'; - $permtoread = $user->rights->fournisseur->commande->lire; - $permtodelete = $user->rights->fournisseur->commande->supprimer; - $uploaddir = $conf->fournisseur->commande->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='CommandeFournisseur'; + $objectlabel='SupplierOrders'; + $permtoread = $user->rights->fournisseur->commande->lire; + $permtodelete = $user->rights->fournisseur->commande->supprimer; + $uploaddir = $conf->fournisseur->commande->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - // TODO Move this into mass action include - if ($massaction == 'confirm_createbills') - { - $orders = GETPOST('toselect'); - $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); - $validate_invoices = GETPOST('valdate_invoices', 'int'); + // TODO Move this into mass action include + if ($massaction == 'confirm_createbills') + { + $orders = GETPOST('toselect','array'); + $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); + $validate_invoices = GETPOST('valdate_invoices', 'int'); - $TFact = array(); - $TFactThird = array(); + $TFact = array(); + $TFactThird = array(); - $nb_bills_created = 0; + $nb_bills_created = 0; - $db->begin(); + $db->begin(); - foreach($orders as $id_order) { + foreach($orders as $id_order) { - $cmd = new Commande($db); - if($cmd->fetch($id_order) <= 0) continue; + $cmd = new Commande($db); + if($cmd->fetch($id_order) <= 0) continue; - $object = new Facture($db); - if(!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. - else { + $object = new Facture($db); + if(!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + else { - $object->socid = $cmd->socid; - $object->type = Facture::TYPE_STANDARD; - $object->cond_reglement_id = $cmd->cond_reglement_id; - $object->mode_reglement_id = $cmd->mode_reglement_id; - $object->fk_project = $cmd->fk_project; + $object->socid = $cmd->socid; + $object->type = Facture::TYPE_STANDARD; + $object->cond_reglement_id = $cmd->cond_reglement_id; + $object->mode_reglement_id = $cmd->mode_reglement_id; + $object->fk_project = $cmd->fk_project; - $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); - if (empty($datefacture)) - { - $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); - } + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + if (empty($datefacture)) + { + $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + } - $object->date = $datefacture; - $object->origin = 'commande'; - $object->origin_id = $id_order; + $object->date = $datefacture; + $object->origin = 'commande'; + $object->origin_id = $id_order; - $res = $object->create($user); + $res = $object->create($user); - if($res > 0) $nb_bills_created++; + if($res > 0) $nb_bills_created++; - } + } - if($object->id > 0) { + if ($object->id > 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $id_order; + $sql.= ", '".$object->origin."'"; + $sql.= ", ".$object->id; + $sql.= ", '".$object->element."'"; + $sql.= ")"; - $db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; - $sql.= "fk_source"; - $sql.= ", sourcetype"; - $sql.= ", fk_target"; - $sql.= ", targettype"; - $sql.= ") VALUES ("; - $sql.= $id_order; - $sql.= ", '".$object->origin."'"; - $sql.= ", ".$object->id; - $sql.= ", '".$object->element."'"; - $sql.= ")"; + if (! $db->query($sql)) + { + $erorr++; + } - if ($db->query($sql)) - { - $db->commit(); - } - else - { - $db->rollback(); - } + if (! $error) + { + $lines = $cmd->lines; + if (empty($lines) && method_exists($cmd, 'fetch_lines')) + { + $cmd->fetch_lines(); + $lines = $cmd->lines; + } - $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { - $cmd->fetch_lines(); - $lines = $cmd->lines; - } + $fk_parent_line=0; + $num=count($lines); - $fk_parent_line=0; - $num=count($lines); + for ($i=0;$i<$num;$i++) + { + $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + if ($lines[$i]->subprice < 0) + { + // Negative line, we create a discount line + $discount = new DiscountAbsolute($db); + $discount->fk_soc=$object->socid; + $discount->amount_ht=abs($lines[$i]->total_ht); + $discount->amount_tva=abs($lines[$i]->total_tva); + $discount->amount_ttc=abs($lines[$i]->total_ttc); + $discount->tva_tx=$lines[$i]->tva_tx; + $discount->fk_user=$user->id; + $discount->description=$desc; + $discountid=$discount->create($user); + if ($discountid > 0) + { + $result=$object->insert_discount($discountid); + //$result=$discount->link_to_invoice($lineid,$id); + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $error++; + break; + } + } + else + { + // Positive line + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + // Date start + $date_start=false; + if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; + //Date end + $date_end=false; + if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) + { + $fk_parent_line = 0; + } + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $lines[$i]->tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $product_type, + $ii, + $lines[$i]->special_code, + $object->origin, + $lines[$i]->rowid, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $lines[$i]->label + ); + if ($result > 0) + { + $lineid=$result; + } + else + { + $lineid=0; + $error++; + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) + { + $fk_parent_line = $result; + } + } + } + } + } - for ($i=0;$i<$num;$i++) - { - $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { - // Negative line, we create a discount line - $discount = new DiscountAbsolute($db); - $discount->fk_soc=$object->socid; - $discount->amount_ht=abs($lines[$i]->total_ht); - $discount->amount_tva=abs($lines[$i]->total_tva); - $discount->amount_ttc=abs($lines[$i]->total_ttc); - $discount->tva_tx=$lines[$i]->tva_tx; - $discount->fk_user=$user->id; - $discount->description=$desc; - $discountid=$discount->create($user); - if ($discountid > 0) - { - $result=$object->insert_discount($discountid); - //$result=$discount->link_to_invoice($lineid,$id); - } - else - { - setEventMessages($discount->error, $discount->errors, 'errors'); - $error++; - break; - } - } - else - { - // Positive line - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); - // Date start - $date_start=false; - if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; - //Date end - $date_end=false; - if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; - // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { - $fk_parent_line = 0; - } - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $lines[$i]->tva_tx, - $lines[$i]->localtax1_tx, - $lines[$i]->localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $date_start, - $date_end, - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_remise_except, - 'HT', - 0, - $product_type, - $ii, - $lines[$i]->special_code, - $object->origin, - $lines[$i]->rowid, - $fk_parent_line, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - $lines[$i]->label - ); - if ($result > 0) - { - $lineid=$result; - } - else - { - $lineid=0; - $error++; - break; - } - // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { - $fk_parent_line = $result; - } - } - } + $cmd->classifyBilled($user); // TODO Move this in workflow like done for customer orders - } + if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; + else $TFact[$object->id] = $object; + } - $cmd->classifyBilled($user); + // Build doc with all invoices + $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; + $toselect = array(); - if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; - else $TFact[$object->id] = $object; - } + if (! $error && $validate_invoices) { - // Build doc with all invoices - $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; - $toselect = array(); + $massaction = $action = 'builddoc'; - if(!empty($validate_invoices)) { + foreach($TAllFact as &$object) + { + $object->validate($user); + if ($result <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + break; + } - $massaction = $action = 'builddoc'; + $id = $object->id; // For builddoc action - foreach($TAllFact as &$object) { - $object->validate($user); - $toselect[] = $object->id; // For builddoc action + // Fac builddoc + $donotredirect = 1; + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + } - // Fac builddoc - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - } + $massaction = $action = 'confirm_createbills'; + } - $objectclass='Facture'; - $objectlabel='Invoice'; - $permtoread = $user->rights->facture->lire; - $permtodelete = $user->rights->facture->supprimer; - $uploaddir = $conf->facture->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - - } - - if (! $error) - { - $db->commit(); - setEventMessage($langs->trans('BillCreated', $nb_bills_created)); - } - else - { - $db->rollback(); - $action='create'; - $_GET["origin"]=$_POST["origin"]; - $_GET["originid"]=$_POST["originid"]; - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } + if (! $error) + { + $db->commit(); + setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + } + else + { + $db->rollback(); + $action='create'; + $_GET["origin"]=$_POST["origin"]; + $_GET["originid"]=$_POST["originid"]; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } } @@ -474,9 +474,9 @@ if ($socid > 0) } if ($status) { - if ($status == '1,2,3') $title.=' - '.$langs->trans("StatusOrderToProcessShort"); - if ($status == '6,7') $title.=' - '.$langs->trans("StatusOrderCanceled"); - else $title.=' - '.$langs->trans($commandestatic->statuts[$status]); + if ($status == '1,2,3') $title.=' - '.$langs->trans("StatusOrderToProcessShort"); + if ($status == '6,7') $title.=' - '.$langs->trans("StatusOrderCanceled"); + else $title.=' - '.$langs->trans($commandestatic->statuts[$status]); } if ($billed > 0) $title.=' - '.$langs->trans("Billed"); @@ -513,8 +513,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = cf.fk_projet"; if ($search_sale > 0 || (!$user->rights->societe->client->voir && ! $socid)) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE cf.fk_soc = s.rowid'; $sql.= ' AND cf.entity IN ('.getEntity('supplier_order').')'; @@ -538,29 +538,29 @@ if ($search_status != '' && $search_status >= 0) } if ($ordermonth > 0) { - if ($orderyear > 0 && empty($orderday)) - $sql.= " AND cf.date_commande BETWEEN '".$db->idate(dol_get_first_day($orderyear,$ordermonth,false))."' AND '".$db->idate(dol_get_last_day($orderyear,$ordermonth,false))."'"; - else if ($orderyear > 0 && ! empty($orderday)) - $sql.= " AND cf.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $ordermonth, $orderday, $orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $ordermonth, $orderday, $orderyear))."'"; - else - $sql.= " AND date_format(cf.date_commande, '%m') = '".$ordermonth."'"; + if ($orderyear > 0 && empty($orderday)) + $sql.= " AND cf.date_commande BETWEEN '".$db->idate(dol_get_first_day($orderyear,$ordermonth,false))."' AND '".$db->idate(dol_get_last_day($orderyear,$ordermonth,false))."'"; + else if ($orderyear > 0 && ! empty($orderday)) + $sql.= " AND cf.date_commande BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $ordermonth, $orderday, $orderyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $ordermonth, $orderday, $orderyear))."'"; + else + $sql.= " AND date_format(cf.date_commande, '%m') = '".$ordermonth."'"; } else if ($orderyear > 0) { - $sql.= " AND cf.date_commande BETWEEN '".$db->idate(dol_get_first_day($orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($orderyear,12,false))."'"; + $sql.= " AND cf.date_commande BETWEEN '".$db->idate(dol_get_first_day($orderyear,1,false))."' AND '".$db->idate(dol_get_last_day($orderyear,12,false))."'"; } if ($deliverymonth > 0) { - if ($deliveryyear > 0 && empty($deliveryday)) - $sql.= " AND cf.date_livraison BETWEEN '".$db->idate(dol_get_first_day($deliveryyear,$deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($deliveryyear,$deliverymonth,false))."'"; - else if ($deliveryyear > 0 && ! empty($deliveryday)) - $sql.= " AND cf.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $deliverymonth, $deliveryday, $deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $deliverymonth, $deliveryday, $deliveryyear))."'"; - else - $sql.= " AND date_format(cf.date_livraison, '%m') = '".$deliverymonth."'"; + if ($deliveryyear > 0 && empty($deliveryday)) + $sql.= " AND cf.date_livraison BETWEEN '".$db->idate(dol_get_first_day($deliveryyear,$deliverymonth,false))."' AND '".$db->idate(dol_get_last_day($deliveryyear,$deliverymonth,false))."'"; + else if ($deliveryyear > 0 && ! empty($deliveryday)) + $sql.= " AND cf.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $deliverymonth, $deliveryday, $deliveryyear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $deliverymonth, $deliveryday, $deliveryyear))."'"; + else + $sql.= " AND date_format(cf.date_livraison, '%m') = '".$deliverymonth."'"; } else if ($deliveryyear > 0) { - $sql.= " AND cf.date_livraison BETWEEN '".$db->idate(dol_get_first_day($deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($deliveryyear,12,false))."'"; + $sql.= " AND cf.date_livraison BETWEEN '".$db->idate(dol_get_first_day($deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($deliveryyear,12,false))."'"; } if ($search_town) $sql.= natural_search('s.town', $search_town); if ($search_zip) $sql.= natural_search("s.zip",$search_zip); @@ -577,16 +577,16 @@ if ($search_project_ref != '') $sql.= natural_search("p.ref",$search_project_ref // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -624,7 +624,7 @@ if ($resql) $param=''; if ($socid > 0) $param.='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($sall) $param.="&search_all=".$sall; if ($orderday) $param.='&orderday='.$orderday; @@ -644,20 +644,20 @@ if ($resql) if ($search_status >= 0) $param.="&search_status=".$search_status; if ($search_project_ref >= 0) $param.="&search_project_ref=".$search_project_ref; if ($billed != '') $param.="&billed=".$billed; - if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($show_files) $param.='&show_files=' .$show_files; + if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); @@ -666,13 +666,13 @@ if ($resql) // Lignes des champs de filtre print '
    '; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -690,97 +690,97 @@ if ($resql) if ($massaction == 'createbills') { - //var_dump($_REQUEST); - print ''; + //var_dump($_REQUEST); + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
    '; - print $langs->trans('DateInvoice'); - print ''; - print $form->select_date('', '', '', '', '', '', 1, 1); - print '
    '; - print $langs->trans('CreateOneBillByThird'); - print ''; - print $form->selectyesno('createbills_onebythird', '', 1); - print '
    '; - print $langs->trans('ValidateInvoices'); - print ''; - print $form->selectyesno('valdate_invoices', 1, 1); - print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print $langs->trans('DateInvoice'); + print ''; + print $form->select_date('', '', '', '', '', '', 1, 1); + print '
    '; + print $langs->trans('CreateOneBillByThird'); + print ''; + print $form->selectyesno('createbills_onebythird', '', 1); + print '
    '; + print $langs->trans('ValidateInvoices'); + print ''; + print $form->selectyesno('valdate_invoices', 1, 1); + print '
    '; - print '
    '; - print '
    '; - print ' '; - print ''; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print ' '; + print ''; + print '
    '; + print '
    '; } if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } - $moreforfilter=''; + $moreforfilter=''; - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; - $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); - $moreforfilter.='
    '; - } - // If the user can view other users - if ($user->rights->user->user->lire) - { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter.='
    '; - } - // If the user can view prospects other than his' - if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) - { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); - $moreforfilter.='
    '; - } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { + $langs->load("commercial"); + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; + $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter.='
    '; + } + // If the user can view other users + if ($user->rights->user->user->lire) + { + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.='
    '; + } + // If the user can view prospects other than his' + if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) + { + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); + $moreforfilter.='
    '; + } + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; - if (! empty($moreforfilter)) - { - print '
    '; - print $moreforfilter; - print '
    '; - } + if (! empty($moreforfilter)) + { + print '
    '; + print $moreforfilter; + print '
    '; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
    '; - print ''."\n"; + print '
    '; + print '
    '."\n"; print ''; // Ref @@ -817,23 +817,23 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print ''; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + print ''; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + print ''; } // Date order if (! empty($arrayfields['cf.date_commande']['checked'])) @@ -847,55 +847,55 @@ if ($resql) // Date delivery if (! empty($arrayfields['cf.date_delivery']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['cf.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['cf.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['cf.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -904,14 +904,14 @@ if ($resql) // Date creation if (! empty($arrayfields['cf.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['cf.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['cf.fk_statut']['checked'])) @@ -955,16 +955,16 @@ if ($resql) // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -980,9 +980,9 @@ if ($resql) $total=0; $subtotal=0; - $productstat_cache=array(); + $productstat_cache=array(); - $userstatic = new User($db); + $userstatic = new User($db); $objectstatic=new CommandeFournisseur($db); $projectstatic=new Project($db); @@ -994,56 +994,56 @@ if ($resql) $obj = $db->fetch_object($resql); - $objectstatic->id=$obj->rowid; - $objectstatic->ref=$obj->ref; - $objectstatic->ref_supplier = $obj->ref_supplier; - $objectstatic->total_ht = $obj->total_ht; - $objectstatic->total_tva = $obj->total_tva; - $objectstatic->total_ttc = $obj->total_ttc; - $objectstatic->date_delivery = $db->jdate($obj->date_delivery); - $objectstatic->statut = $obj->fk_statut; + $objectstatic->id=$obj->rowid; + $objectstatic->ref=$obj->ref; + $objectstatic->ref_supplier = $obj->ref_supplier; + $objectstatic->total_ht = $obj->total_ht; + $objectstatic->total_tva = $obj->total_tva; + $objectstatic->total_ttc = $obj->total_ttc; + $objectstatic->date_delivery = $db->jdate($obj->date_delivery); + $objectstatic->statut = $obj->fk_statut; print ''; // Ref - if (! empty($arrayfields['cf.ref']['checked'])) - { - print '
    '; - print ''; - print ''; + print ''; + print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($deliveryyear?$deliveryyear:-1,'deliveryyear',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($deliveryyear?$deliveryyear:-1,'deliveryyear',1, 20, 5); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; - print ''; + print ''; - print ''; + print '
    '; + if (! empty($arrayfields['cf.ref']['checked'])) + { + print ''; - print ''; - // Picto + Ref - print ''; - // Warning - //print ''; - // Other picto tool - print ''."\n"; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } // Ref Supplier - if (! empty($arrayfields['cf.ref_supplier']['checked'])) - { - print ''."\n"; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['cf.ref_supplier']['checked'])) + { + print ''."\n"; + if (! $i) $totalarray['nbfield']++; + } // Project - if (! empty($arrayfields['p.project_ref']['checked'])) - { + if (! empty($arrayfields['p.project_ref']['checked'])) + { $projectstatic->id=$obj->project_id; $projectstatic->ref=$obj->project_ref; print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } // Author $userstatic->id = $obj->fk_user_author; $userstatic->lastname = $obj->lastname; @@ -1052,169 +1052,169 @@ if ($resql) $userstatic->photo = $obj->photo; if (! empty($arrayfields['u.login']['checked'])) { - print ""; - if (! $i) $totalarray['nbfield']++; + print ""; + if (! $i) $totalarray['nbfield']++; } - // Thirdparty - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''."\n"; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! $i) $totalarray['nbfield']++; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Order date if (! empty($arrayfields['cf.date_commande']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; } // Plannned date of delivery if (! empty($arrayfields['cf.date_delivery']['checked'])) { - print ''; - if (! $i) $totalarray['nbfield']++; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Amount HT + if (! empty($arrayfields['cf.total_ht']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['cf.total_vat']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_tva; + } + // Amount TTC + if (! empty($arrayfields['cf.total_ttc']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; } - // Amount HT - if (! empty($arrayfields['cf.total_ht']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['cf.total_vat']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_tva; - } - // Amount TTC - if (! empty($arrayfields['cf.total_ttc']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['cf.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['cf.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['cf.fk_statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['cf.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['cf.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['cf.fk_statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Billed - if (! empty($arrayfields['cf.billed']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['cf.billed']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; $i++; @@ -1225,21 +1225,21 @@ if ($resql) if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { - /* + /* * Show list of available documents */ - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->fournisseur->commande->lire; - $delallowed=$user->rights->fournisseur->commande->lire; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->fournisseur->commande->lire; + $delallowed=$user->rights->fournisseur->commande->lire; - print $formfile->showdocuments('massfilesarea_supplier_order','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_supplier_order','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; + print '
    '.$langs->trans("ShowTempMassFilesArea").''; } $db->free($resql); diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 820768ac7bd..99fe95d0ec0 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; } } @@ -816,42 +816,42 @@ if (empty($reshook)) $db->begin(); $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $tva_tx = GETPOST('tva_tx'); + $tva_tx = GETPOST('tva_tx'); 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')); - $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'); + $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'); // Extrafields Lines @@ -865,10 +865,10 @@ 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); - if ($result >= 0) - { - unset($_POST['label']); + $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); + if ($result >= 0) + { + unset($_POST['label']); unset($_POST['date_starthour']); unset($_POST['date_startmin']); unset($_POST['date_startsec']); @@ -882,28 +882,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 +930,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 +983,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 +997,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 +1069,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 +1088,135 @@ 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) { - $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) - { - $object->set_draft($user); + // On verifie si aucun paiement n'a ete effectue + if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) + { + $object->set_draft($user); - // 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); + } - $action=''; - } + $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 +1239,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 +1371,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 +1385,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 +1435,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 $objectstatic->getNomUrl(1); - print ''; - //print ''; + print ''; + // Picto + Ref + print ''; + // Warning + //print ''; + // Other picto tool + print '
    '; + print $objectstatic->getNomUrl(1); + print ''; + //print ''; $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->fournisseur->dir_output.'/commande/' . dol_sanitizeFileName($obj->ref); + $filedir=$conf->fournisseur->commande->dir_output.'/' . dol_sanitizeFileName($obj->ref); print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); print '
    '; print '
    '.$obj->ref_supplier.''.$obj->ref_supplier.''; if ($obj->project_id > 0) print $projectstatic->getNomUrl(1); print '"; - if ($userstatic->id) print $userstatic->getNomUrl(1); - else print " "; - print ""; + if ($userstatic->id) print $userstatic->getNomUrl(1); + else print " "; + print "'; + // Thirdparty + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; $thirdpartytmp->id = $obj->socid; $thirdpartytmp->name = $obj->name; print $thirdpartytmp->getNomUrl(1,'supplier'); print ''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; - if ($obj->date_commande) print dol_print_date($db->jdate($obj->date_commande), 'day'); - else print ''; - print ''; + if ($obj->date_commande) print dol_print_date($db->jdate($obj->date_commande), 'day'); + else print ''; + print ''; - print dol_print_date($db->jdate($obj->date_delivery), 'day'); - if ($objectstatic->hasDelay() && ! empty($objectstatic->date_delivery)) { - print ' '.img_picto($langs->trans("Late").' : '.$objectstatic->showDelay(), "warning"); - } - print ''; + print dol_print_date($db->jdate($obj->date_delivery), 'day'); + if ($objectstatic->hasDelay() && ! empty($objectstatic->date_delivery)) { + print ' '.img_picto($langs->trans("Late").' : '.$objectstatic->showDelay(), "warning"); + } + print ''.price($obj->total_ht)."'.price($obj->total_tva)."'.price($obj->total_ttc)."'.price($obj->total_ht)."'.price($obj->total_tva)."'.price($obj->total_ttc)."'; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$objectstatic->LibStatut($obj->fk_statut, 5, $obj->billed, 1).''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''.$objectstatic->LibStatut($obj->fk_statut, 5, $obj->billed, 1).''.yn($obj->billed).''.yn($obj->billed).''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; - } - print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '; + print '
    '; - // 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 +1645,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 +1671,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 +1732,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 +1786,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 +1860,168 @@ 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 +1755,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))); - } + 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))); + } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1, 240); - } + } - // Confirmation set paid - if ($action == 'paid') - { + // 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; @@ -2028,7 +2033,7 @@ else // Supplier invoice card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; // Ref supplier @@ -2036,6 +2041,7 @@ else $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; // Project if (! empty($conf->projet->enabled)) { @@ -2214,9 +2220,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); @@ -2229,35 +2235,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); @@ -2266,142 +2272,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'; - $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)) { @@ -2412,28 +2418,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) @@ -2448,12 +2454,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) { @@ -2465,7 +2471,7 @@ else print $langs->trans('AlreadyPaid'); print ' :'; - $resteapayer = $object->total_ttc - $totalpaye; + $resteapayer = $object->total_ttc - $totalpaye; $resteapayeraffiche = $resteapayer; $cssforamountpaymentcomplete = 'amountpaymentcomplete'; @@ -2584,29 +2590,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 '
    '; @@ -2620,7 +2626,7 @@ else include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print ''; global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; @@ -2633,7 +2639,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') { @@ -2645,76 +2651,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 + // Modify a validated invoice with no payments if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != '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) - { - print ''; // must use facid because id is for payment id not invoice - } + // Make payments + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != '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) - { - print ''; + // Classify paid + if ($action != '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) { @@ -2742,24 +2748,24 @@ else } } - // Validate - if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) - { - if (count($object->lines)) - { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) - { - print ''; - } - else - { - print ''; - } - } - } + // Validate + if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) + { + if (count($object->lines)) + { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) + { + print ''; + } + else + { + print ''; + } + } + } // Create event if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page. @@ -2767,11 +2773,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) @@ -2782,67 +2788,67 @@ else } } - // Delete - if ($action != 'edit' && $user->rights->fournisseur->facture->supprimer) - { - if ($object->getSommePaiement()) { - print ''; - } else { - print ''; - } - } - print '
    '; + // Delete + if ($action != 'edit' && $user->rights->fournisseur->facture->supprimer) + { + if ($object->getSommePaiement()) { + print ''; + } else { + print ''; + } + } + print '
    '; - if ($action != 'edit') - { + if ($action != '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->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)); - 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/contact.php b/htdocs/fourn/facture/contact.php index 0f56c5f7bae..ffc58195e26 100644 --- a/htdocs/fourn/facture/contact.php +++ b/htdocs/fourn/facture/contact.php @@ -135,12 +135,12 @@ if ($id > 0 || ! empty($ref)) $object->fetch_thirdparty(); $alreadypaid=$object->getSommePaiement(); - + $head = facturefourn_prepare_head($object); dol_fiche_head($head, 'contact', $langs->trans('SupplierInvoice'), -1, 'bill'); - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref supplier @@ -186,7 +186,7 @@ if ($id > 0 || ! empty($ref)) $object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - + print '
    '; print '
    '; diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 6926770bd91..77c0559aeca 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -90,10 +90,10 @@ if ($object->id > 0) { $head = facturefourn_prepare_head($object); dol_fiche_head($head, 'documents', $langs->trans('SupplierInvoice'), -1, 'bill'); - + $totalpaye = $object->getSommePaiement(); - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref supplier @@ -231,7 +231,7 @@ if ($object->id > 0) print '
    '; print '
    '; - + print ''; // Nb of files @@ -241,9 +241,9 @@ if ($object->id > 0) print '
    '; print '
    '; - + dol_fiche_end(); - + $modulepart = 'facture_fournisseur'; $permission = $user->rights->fournisseur->facture->creer; diff --git a/htdocs/fourn/facture/info.php b/htdocs/fourn/facture/info.php index 73d6b94a0d6..ffda7e2f4cd 100644 --- a/htdocs/fourn/facture/info.php +++ b/htdocs/fourn/facture/info.php @@ -63,7 +63,7 @@ $head = facturefourn_prepare_head($object); $titre=$langs->trans('SupplierInvoice'); dol_fiche_head($head, 'info', $langs->trans('SupplierInvoice'), -1, 'bill'); -$linkback = '' . $langs->trans("BackToList") . ''; +$linkback = '' . $langs->trans("BackToList") . ''; $morehtmlref='
    '; // Ref supplier diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index c11b914c45d..e6c8023496c 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -54,6 +54,7 @@ $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$optioncss = GETPOST('optioncss','alpha'); $socid = GETPOST('socid','int'); @@ -61,12 +62,17 @@ $socid = GETPOST('socid','int'); if ($user->societe_id > 0) { $action=''; - $_GET["action"] = ''; + $_GET["action"] = ''; $socid = $user->societe_id; } $mode=GETPOST("mode"); +$search_all = GETPOST('sall', 'alphanohtml'); +$search_label = GETPOST("search_label","alpha"); +$search_company = GETPOST("search_company","alpha"); +$search_amount_no_tax = GETPOST("search_amount_no_tax","alpha"); +$search_amount_all_tax = GETPOST("search_amount_all_tax","alpha"); $search_product_category=GETPOST('search_product_category','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); $search_refsupplier=GETPOST('search_refsupplier','alpha'); @@ -93,20 +99,12 @@ $day_lim = GETPOST('day_lim','int'); $month_lim = GETPOST('month_lim','int'); $year_lim = GETPOST('year_lim','int'); $toselect = GETPOST('toselect', 'array'); -$filter = GETPOST('filtre','alpha'); $option = GETPOST('option'); if ($option == 'late') { - $filter = 'paye:0'; + $search_status = '1'; } - -$search_all = GETPOST('sall', 'alphanohtml'); -$search_label = GETPOST("search_label","alpha"); -$search_company = GETPOST("search_company","alpha"); -$search_amount_no_tax = GETPOST("search_amount_no_tax","alpha"); -$search_amount_all_tax = GETPOST("search_amount_all_tax","alpha"); -$search_status=GETPOST('search_status','alpha'); -$optioncss = GETPOST('optioncss','alpha'); +$filter = GETPOST('filtre','alpha'); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -138,47 +136,47 @@ $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search // List of fields to search into when doing a "search in all" $fieldstosearchall = array( - 'f.ref'=>'Ref', - 'f.ref_supplier'=>'RefSupplier', - 'pd.description'=>'Description', - 's.nom'=>"ThirdParty", - 'f.note_public'=>'NotePublic', + 'f.ref'=>'Ref', + 'f.ref_supplier'=>'RefSupplier', + 'pd.description'=>'Description', + 's.nom'=>"ThirdParty", + 'f.note_public'=>'NotePublic', ); if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate"; $checkedtypetiers=0; $arrayfields=array( - 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), - 'f.label'=>array('label'=>$langs->trans("Label"), 'checked'=>0), - 'f.datef'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), - 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), + 'f.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'f.ref_supplier'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1), + 'f.label'=>array('label'=>$langs->trans("Label"), 'checked'=>0), + 'f.datef'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), + 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), 'p.ref'=>array('label'=>$langs->trans("Project"), 'checked'=>0), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), - 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), - 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), - 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), - 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), - 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), - 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), - 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), - 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), - 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), - 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), - 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), - 'dynamount_payed'=>array('label'=>$langs->trans("Payed"), 'checked'=>0), - 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), - 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), - 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), - 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), + 's.town'=>array('label'=>$langs->trans("Town"), 'checked'=>1), + 's.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>1), + 'state.nom'=>array('label'=>$langs->trans("StateShort"), 'checked'=>0), + 'country.code_iso'=>array('label'=>$langs->trans("Country"), 'checked'=>0), + 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), + 'f.fk_mode_reglement'=>array('label'=>$langs->trans("PaymentMode"), 'checked'=>1), + 'f.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), + 'f.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), + 'f.total_localtax1'=>array('label'=>$langs->transcountry("AmountLT1", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax1_assuj=="1"), + 'f.total_localtax2'=>array('label'=>$langs->transcountry("AmountLT2", $mysoc->country_code), 'checked'=>0, 'enabled'=>$mysoc->localtax2_assuj=="1"), + 'f.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), + 'dynamount_payed'=>array('label'=>$langs->trans("Payed"), 'checked'=>0), + 'rtp'=>array('label'=>$langs->trans("Rest"), 'checked'=>0), + 'f.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'f.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'f.fk_statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } } @@ -195,55 +193,55 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests must be present to be compatible with all browsers - { - $search_all=""; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=""; - $search_refsupplier=""; - $search_label=""; - $search_project=''; - $search_societe=""; - $search_company=""; - $search_amount_no_tax=""; - $search_amount_all_tax=""; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_localtax1=''; - $search_montant_localtax2=''; - $search_montant_ttc=''; - $search_status=''; - $search_paymentmode=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $year=""; - $month=""; - $day=""; - $year_lim=""; - $month_lim=""; - $day_lim=""; - $toselect=''; - $search_array_options=array(); - $filter=''; - $option=''; - } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_removefilter.x','alpha')) // All tests must be present to be compatible with all browsers + { + $search_all=""; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=""; + $search_refsupplier=""; + $search_label=""; + $search_project=''; + $search_societe=""; + $search_company=""; + $search_amount_no_tax=""; + $search_amount_all_tax=""; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_localtax1=''; + $search_montant_localtax2=''; + $search_montant_ttc=''; + $search_status=''; + $search_paymentmode=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $year=""; + $month=""; + $day=""; + $year_lim=""; + $month_lim=""; + $day_lim=""; + $toselect=''; + $search_array_options=array(); + $filter=''; + $option=''; + } - // Mass actions - $objectclass='FactureFournisseur'; - $objectlabel='SupplierInvoices'; - $permtoread = $user->rights->fournisseur->facture->lire; - $permtocreate = $user->rights->fournisseur->facture->creer; - $permtodelete = $user->rights->fournisseur->facture->supprimer; - $uploaddir = $conf->fournisseur->facture->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + // Mass actions + $objectclass='FactureFournisseur'; + $objectlabel='SupplierInvoices'; + $permtoread = $user->rights->fournisseur->facture->lire; + $permtocreate = $user->rights->fournisseur->facture->creer; + $permtodelete = $user->rights->fournisseur->facture->supprimer; + $uploaddir = $conf->fournisseur->facture->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -292,8 +290,8 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet"; if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) { - $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; - $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql.=", ".MAIN_DB_PREFIX."element_contact as ec"; + $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; $sql.= ' AND f.entity IN ('.getEntity('facture_fourn').')'; @@ -349,7 +347,6 @@ else if ($year_lim > 0) $sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,1,false))."' AND '".$db->idate(dol_get_last_day($year_lim,12,false))."'"; } if ($option == 'late') $sql.=" AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; -if ($filter == 'paye:0') $sql.= " AND f.fk_statut = 1"; if ($search_label) $sql .= natural_search('f.libelle', $search_label); if ($search_status != '' && $search_status >= 0) { @@ -361,27 +358,27 @@ if ($filter && $filter != -1) foreach ($aFilter as $fil) { $filt = explode(':', $fil); - $sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]); + $sql .= ' AND ' . $db->escape(trim($filt[0])) . ' = ' . $db->escape(trim($filt[1])); } } -if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; +if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); if ($search_user > 0) { - $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; + $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $typ=$extrafields->attribute_type[$tmpkey]; - $mode=0; - if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric - if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int - if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) - { - $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); - } + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double','real'))) $mode=1; // Search on a numeric + if (in_array($typ, array('sellist')) && $crit != '0' && $crit != '-1') $mode=2; // Search on a foreign key int + if ($crit != '' && (! in_array($typ, array('select','sellist')) || $crit != '0')) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } } // Add where from hooks $parameters=array(); @@ -390,22 +387,22 @@ $sql.=$hookmanager->resPrint; if (! $search_all) { - $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; - $sql.= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; - $sql.= " f.localtax1, f.localtax2,"; - $sql.= " s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.client, s.code_client,"; - $sql.= " typent.code,"; - $sql.= " state.code_departement, state.nom,"; - $sql.= " p.rowid, p.ref"; + $sql.= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.datef, f.date_lim_reglement, f.fk_mode_reglement,"; + $sql.= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; + $sql.= " f.localtax1, f.localtax2,"; + $sql.= " s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.client, s.code_client,"; + $sql.= " typent.code,"; + $sql.= " state.code_departement, state.nom,"; + $sql.= " p.rowid, p.ref"; - foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by - { - $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); - } + foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by + { + $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + } } else { - $sql.= natural_search(array_keys($fieldstosearchall), $search_all); + $sql.= natural_search(array_keys($fieldstosearchall), $search_all); } $sql.= $db->order($sortfield,$sortorder); @@ -435,10 +432,10 @@ if ($resql) } $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($search_all) $param.='&search_all='.urlencode($search_all); - if ($day) $param.='&day='.urlencode($day); + if ($day) $param.='&day='.urlencode($day); if ($month) $param.='&month='.urlencode($month); if ($year) $param.='&year=' .urlencode($year); if ($day_lim) $param.='&day_lim='.urlencode($day_lim); @@ -448,30 +445,30 @@ if ($resql) if ($search_refsupplier) $param.='&search_refsupplier='.urlencode($search_refsupplier); if ($search_label) $param.='&search_label='.urlencode($search_label); if ($search_company) $param.='&search_company='.urlencode($search_company); - if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); + if ($search_montant_vat != '') $param.='&search_montant_vat='.urlencode($search_montant_vat); + if ($search_montant_localtax1 != '') $param.='&search_montant_localtax1='.urlencode($search_montant_localtax1); + if ($search_montant_localtax2 != '') $param.='&search_montant_localtax2='.urlencode($search_montant_localtax2); + if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_amount_no_tax) $param.='&search_amount_no_tax='.urlencode($search_amount_no_tax); if ($search_amount_all_tax) $param.='&search_amount_all_tax='.urlencode($search_amount_all_tax); if ($search_status >= 0) $param.="&search_status=".urlencode($search_status); - if ($show_files) $param.='&show_files=' .$show_files; + if ($show_files) $param.='&show_files=' .$show_files; if ($option) $param.="&option=".$option; if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } // List of mass actions available $arrayofmassactions = array( - 'validate'=>$langs->trans("Validate"), + 'validate'=>$langs->trans("Validate"), //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), + //'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->fournisseur->facture->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); @@ -480,13 +477,13 @@ if ($resql) $i = 0; print '
    '."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -504,52 +501,52 @@ if ($resql) if ($massaction == 'createbills') { - //var_dump($_REQUEST); - print ''; + //var_dump($_REQUEST); + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
    '; - print $langs->trans('DateInvoice'); - print ''; - print $form->select_date('', '', '', '', '', '', 1, 1); - print '
    '; - print $langs->trans('CreateOneBillByThird'); - print ''; - print $form->selectyesno('createbills_onebythird', '', 1); - print '
    '; - print $langs->trans('ValidateInvoices'); - print ''; - print $form->selectyesno('valdate_invoices', 1, 1); - print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print $langs->trans('DateInvoice'); + print ''; + print $form->select_date('', '', '', '', '', '', 1, 1); + print '
    '; + print $langs->trans('CreateOneBillByThird'); + print ''; + print $form->selectyesno('createbills_onebythird', '', 1); + print '
    '; + print $langs->trans('ValidateInvoices'); + print ''; + print $form->selectyesno('valdate_invoices', 1, 1); + print '
    '; - print '
    '; - print '
    '; - print ' '; - print ''; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print ' '; + print ''; + print '
    '; + print '
    '; } if ($search_all) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); - } + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); + } // If the user can view prospects other than his' - $moreforfilter=''; + $moreforfilter=''; if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); @@ -558,14 +555,14 @@ if ($resql) $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); $moreforfilter.='
    '; } - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) + { $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter.='
    '; - } + } // If the user can view prospects other than his' if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { @@ -576,76 +573,76 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.='
    '; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; else $moreforfilter = $hookmanager->resPrint; - if ($moreforfilter) - { + if ($moreforfilter) + { print '
    '; - print $moreforfilter; - print '
    '; - } + print $moreforfilter; + print '
    '; + } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - print '
    '; - print ''."\n"; + print '
    '; + print '
    '."\n"; // Line for filters print ''; // Ref if (! empty($arrayfields['f.ref']['checked'])) { - print ''; + print ''; } // Ref supplier if (! empty($arrayfields['f.ref_supplier']['checked'])) { - print ''; + print ''; } // Label if (! empty($arrayfields['f.label']['checked'])) { - print ''; + print ''; } // Date invoice if (! empty($arrayfields['f.datef']['checked'])) { - print ''; + print ''; } // Date due if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { - print ''; + print ''; } // Project if (! empty($arrayfields['p.ref']['checked'])) { - print ''; + print ''; } // Thirpdarty if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } // Town if (! empty($arrayfields['s.town']['checked'])) print ''; @@ -654,98 +651,98 @@ if ($resql) // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print ''; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + print ''; } // Company type if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + print ''; } // Payment mode if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['f.total_ht']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_vat']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_localtax1']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_localtax2']['checked'])) { - // Amount - print ''; + // Amount + print ''; } if (! empty($arrayfields['f.total_ttc']['checked'])) { - // Amount - print ''; + // Amount + print ''; + } + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print ''; + } + if (! empty($arrayfields['rtp']['checked'])) + { + print ''; } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print ''; - } - if (! empty($arrayfields['rtp']['checked'])) - { - print ''; - } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } } // Fields from hook $parameters=array('arrayfields'=>$arrayfields); @@ -754,22 +751,22 @@ if ($resql) // Date creation if (! empty($arrayfields['f.datec']['checked'])) { - print ''; + print ''; } // Date modification if (! empty($arrayfields['f.tms']['checked'])) { - print ''; + print ''; } // Status if (! empty($arrayfields['f.fk_statut']['checked'])) { - print ''; + print ''; } // Action column print '\n"; - $facturestatic=new FactureFournisseur($db); + $facturestatic=new FactureFournisseur($db); $supplierstatic=new Fournisseur($db); $projectstatic=new Project($db); if ($num > 0) - { + { $i=0; $var=true; - $totalarray=array(); + $totalarray=array(); while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); @@ -841,7 +838,7 @@ if ($resql) $datelimit=$db->jdate($obj->datelimite); $facturestatic->id=$obj->facid; $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; + $facturestatic->type=$obj->type; $facturestatic->ref_supplier=$obj->ref_supplier; $facturestatic->date_echeance = $db->jdate($obj->datelimite); $facturestatic->statut = $obj->fk_statut; @@ -852,271 +849,271 @@ if ($resql) $totalpay = $paiement + $totalcreditnotes + $totaldeposits; $remaintopay = $obj->total_ttc - $totalpay; - print ''; - if (! empty($arrayfields['f.ref']['checked'])) - { - print ''; + if (! empty($arrayfields['f.ref']['checked'])) + { + print ''; print ''; diff --git a/htdocs/fourn/js/lib_dispatch.js b/htdocs/fourn/js/lib_dispatch.js index 84f74c30c54..2b39c18cbb2 100644 --- a/htdocs/fourn/js/lib_dispatch.js +++ b/htdocs/fourn/js/lib_dispatch.js @@ -1,5 +1,5 @@ // Copyright (C) 2014 Cedric GROSS -// Copyright (C) 2015 Francis Appels +// Copyright (C) 2017 Francis Appels // // 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 @@ -24,7 +24,7 @@ * addDispatchLine * Adds new table row for dispatching to multiple stock locations * - * @param index int index of produt line. 0 = first product line + * @param index int index of product line. 0 = first product line * @param type string type of dispatch (batch = batch dispatch, dispatch = non batch dispatch) * @param mode string 'qtymissing' will create new line with qty missing, 'lessone' will keep 1 in old line and the rest in new one */ @@ -35,17 +35,17 @@ function addDispatchLine(index, type, mode) console.log("Split line type="+type+" index="+index+" mode="+mode); var $row = $("tr[name='"+type+'_0_'+index+"']").clone(true), // clone first batch line to jQuery object nbrTrs = $("tr[name^='"+type+"_'][name$='_"+index+"']").length, // position of line for batch - qtyOrdered = parseFloat($("#qty_ordered_"+(nbrTrs - 1)+"_"+index).val()), + qtyOrdered = parseFloat($("#qty_ordered_0_"+index).val()), // Qty ordered is same for all rows qty = parseFloat($("#qty_"+(nbrTrs - 1)+"_"+index).val()), qtyDispatched; if (mode === 'lessone') { - qtyDispatched = parseFloat($("#qty_dispatched_"+(nbrTrs - 1)+"_"+index).val()) + 1; + qtyDispatched = parseFloat($("#qty_dispatched_0_"+index).val()) + 1; } else { - qtyDispatched = parseFloat($("#qty_dispatched_"+(nbrTrs - 1)+"_"+index).val()) + qty; + qtyDispatched = parseFloat($("#qty_dispatched_0_"+index).val()) + qty; } if (qtyDispatched < qtyOrdered) @@ -63,10 +63,10 @@ function addDispatchLine(index, type, mode) //insert new row before last row $("tr[name^='"+type+"_'][name$='_"+index+"']:last").after($row); //remove cloned select2 with duplicate id. - $("#s2id_entrepot_"+nbrTrs+'_'+index).detach(); + $("#s2id_entrepot_"+nbrTrs+'_'+index).detach(); /* Suffix of lines are: _ trs.length _ index */ $("#qty_"+nbrTrs+"_"+index).focus(); - $("#qty_dispatched_"+(nbrTrs)+"_"+index).val(qtyDispatched); + $("#qty_dispatched_0_"+index).val(qtyDispatched); //hide all buttons then show only the last one $("tr[name^='"+type+"_'][name$='_"+index+"'] .splitbutton").hide(); @@ -74,15 +74,51 @@ function addDispatchLine(index, type, mode) if (mode === 'lessone') { - $("#qty_"+(nbrTrs)+"_"+index).val(qty-1); - $("#qty_"+(nbrTrs-1)+"_"+index).val(1); + qty = 1; // keep 1 in old line + $("#qty_"+(nbrTrs-1)+"_"+index).val(qty); } - else - { - $("#qty_"+nbrTrs+"_"+index).val(qtyOrdered - qtyDispatched); - } - + $("#qty_"+nbrTrs+"_"+index).val(qtyOrdered - qtyDispatched); + // Store arbitrary data for dispatch qty input field change event + $("#qty_"+(nbrTrs-1)+"_"+index).data('qty', qty); + $("#qty_"+(nbrTrs-1)+"_"+index).data('type', type); + $("#qty_"+(nbrTrs-1)+"_"+index).data('index', index); + // Update dispatched qty when value dispatch qty input field changed + $("#qty_"+(nbrTrs-1)+"_"+index).change(this.onChangeDispatchLineQty); //set focus on lot of new line (if it exists) $("#lot_number_"+(nbrTrs)+"_"+index).focus(); } +} + +/** + * onChangeDispatchLineQty + * + * Change event handler for dispatch qty input field, + * recalculate qty dispatched when qty input has changed. + * If qty is more then qty ordered reset input qty to max qty to dispatch. + * + * element requires arbitrary data qty (value before change), type (type of dispatch) and index (index of product line) + */ + +function onChangeDispatchLineQty() { + var index = $(this).data('index'), + type = $(this).data('type'), + qty = parseFloat($(this).data('qty')), + changedQty, nbrTrs, dispatchingQty, qtyOrdered, qtyDispatched; + + if (index >= 0 && type && qty >= 0) { + nbrTrs = $("tr[name^='"+type+"_'][name$='_"+index+"']").length; + qtyChanged = parseFloat($(this).val()) - qty; // qty changed + qtyDispatching = parseFloat($("#qty_"+(nbrTrs-1)+"_"+index).val()); // qty currently being dispatched + qtyOrdered = parseFloat($("#qty_ordered_0_"+index).val()); // qty ordered + qtyDispatched = parseFloat($("#qty_dispatched_0_"+index).val()); // qty already dispatched + + console.log("onChangeDispatchLineQty qtyChanged: " + qtyChanged + " qtyDispatching: " + qtyDispatching + " qtyOrdered: " + qtyOrdered + " qtyDispatched: "+ qtyDispatched); + + if ((qtyChanged) <= (qtyOrdered - (qtyDispatched + qtyDispatching))) { + $("#qty_dispatched_0_"+index).val(qtyDispatched + qtyChanged); + } else { + $(this).val($(this).data('qty')); + } + $(this).data('qty', $(this).val()); + } } \ No newline at end of file diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index a1104eeaceb..36749977927 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -54,20 +54,20 @@ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($co if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) { - $db->begin(); + $db->begin(); - $object->fetch($id); - $result = $object->update_note(GETPOST('note','none')); - if ($result > 0) - { - $db->commit(); - $action=''; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $db->rollback(); - } + $object->fetch($id); + $result = $object->update_note(GETPOST('note','none')); + if ($result > 0) + { + $db->commit(); + $action=''; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } } if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) @@ -90,8 +90,8 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse } if ($action == 'confirm_valide' && $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))) ) { $db->begin(); @@ -113,7 +113,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && if ($action == 'setnum_paiement' && ! empty($_POST['num_paiement'])) { $object->fetch($id); - $res = $object->update_num($_POST['num_paiement']); + $res = $object->update_num($_POST['num_paiement']); if ($res === 0) { setEventMessages($langs->trans('PaymentNumberUpdateSucceeded'), null, 'mesgs'); @@ -127,7 +127,7 @@ if ($action == 'setnum_paiement' && ! empty($_POST['num_paiement'])) if ($action == 'setdatep' && ! empty($_POST['datepday'])) { $object->fetch($id); - $datepaye = dol_mktime(12, 0, 0, $_POST['datepmonth'], $_POST['datepday'], $_POST['datepyear']); + $datepaye = dol_mktime(12, 0, 0, $_POST['datepmonth'], $_POST['datepday'], $_POST['datepyear']); $res = $object->update_date($datepaye); if ($res === 0) { @@ -140,30 +140,10 @@ if ($action == 'setdatep' && ! empty($_POST['datepday'])) } // Build document -if ($action == 'builddoc') -{ - // Save modele used - $object->fetch($id); - $object->fetch_thirdparty(); - - // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); - - $outputlangs = $langs; - $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); - } - $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $action=''; - } -} +$upload_dir = $conf->fournisseur->payment->dir_output; +// TODO: get the appropriate permisson +$permissioncreate = true; +include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; /* @@ -217,18 +197,18 @@ if ($result > 0) print '';*/ // Date payment - print ''; + print ''; // Payment mode $labeltype=$langs->trans("PaymentType".$object->type_code)!=("PaymentType".$object->type_code)?$langs->trans("PaymentType".$object->type_code):$object->type_libelle; print ''; // Payment numero - print ''; + print ''; // Amount print ''; @@ -239,41 +219,41 @@ if ($result > 0) } // Note - print ''; + print ''; $allow_delete = 1 ; - // Bank account + // Bank account if (! empty($conf->banque->enabled)) { if ($object->bank_account) { - $bankline=new AccountLine($db); - $bankline->fetch($object->bank_line); - if ($bankline->rappro) - { - $allow_delete=0; - $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); - } + $bankline=new AccountLine($db); + $bankline->fetch($object->bank_line); + if ($bankline->rappro) + { + $allow_delete=0; + $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); + } - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; print ''; - print ''; - } - } + print $accountstatic->getNomUrl(1); + print ''; + print ''; + } + } print '
    '; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); - print '
    '.$langs->trans("Late"); - print '
    '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5); + print '
    '.$langs->trans("Late"); + print '
    '; - print ''; - print ''; + print ''; + print ''; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); - print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); - print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); - print ''; + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; - print ''; + print ''; - print ''; + print ''; - $liststatus=array('0'=>$langs->trans("Draft"),'1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); - print $form->selectarray('search_status', $liststatus, $search_status, 1); - print ''; + $liststatus=array('0'=>$langs->trans("Draft"),'1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print ''; @@ -798,21 +795,21 @@ if ($resql) if (! empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'],$_SERVER['PHP_SELF'],'f.localtax1','',$param,'align="right"',$sortfield,$sortorder); if (! empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'],$_SERVER['PHP_SELF'],'f.localtax2','',$param,'align="right"',$sortfield,$sortorder); if (! empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'],$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $sortonfield = "ef.".$key; - if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } } // Hook fields $parameters=array('arrayfields'=>$arrayfields); @@ -824,16 +821,16 @@ if ($resql) print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "
    '; + print '
    '; - print ''; - // Picto + Ref - print ''; - // Warning - //print ''; - // Other picto tool - print '\n"; + print "\n"; if (! $i) $totalarray['nbfield']++; - } + } // Customer ref - if (! empty($arrayfields['f.ref_supplier']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.ref_supplier']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Label - if (! empty($arrayfields['f.label']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.label']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Date - if (! empty($arrayfields['f.datef']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + if (! empty($arrayfields['f.datef']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Date limit - if (! empty($arrayfields['f.date_lim_reglement']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Date limit + if (! empty($arrayfields['f.date_lim_reglement']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Project - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Project + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Third party - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Town + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Zip + if (! empty($arrayfields['s.zip']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // State + if (! empty($arrayfields['state.nom']['checked'])) + { + print "\n"; + if (! $i) $totalarray['nbfield']++; + } + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Type ent + if (! empty($arrayfields['typent.code']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Payment mode - if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } + // Payment mode + if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - // Amount HT - if (! empty($arrayfields['f.total_ht']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; - $totalarray['totalht'] += $obj->total_ht; - } - // Amount VAT - if (! empty($arrayfields['f.total_vat']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; - $totalarray['totalvat'] += $obj->total_vat; - } - // Amount LocalTax1 - if (! empty($arrayfields['f.total_localtax1']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; - $totalarray['totallocaltax1'] += $obj->total_localtax1; - } - // Amount LocalTax2 - if (! empty($arrayfields['f.total_localtax2']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; - $totalarray['totallocaltax2'] += $obj->total_localtax2; - } - // Amount TTC - if (! empty($arrayfields['f.total_ttc']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; - $totalarray['totalttc'] += $obj->total_ttc; - } + // Amount HT + if (! empty($arrayfields['f.total_ht']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalhtfield']=$totalarray['nbfield']; + $totalarray['totalht'] += $obj->total_ht; + } + // Amount VAT + if (! empty($arrayfields['f.total_vat']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['totalvat'] += $obj->total_vat; + } + // Amount LocalTax1 + if (! empty($arrayfields['f.total_localtax1']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax1field']=$totalarray['nbfield']; + $totalarray['totallocaltax1'] += $obj->total_localtax1; + } + // Amount LocalTax2 + if (! empty($arrayfields['f.total_localtax2']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totallocaltax2field']=$totalarray['nbfield']; + $totalarray['totallocaltax2'] += $obj->total_localtax2; + } + // Amount TTC + if (! empty($arrayfields['f.total_ttc']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalttcfield']=$totalarray['nbfield']; + $totalarray['totalttc'] += $obj->total_ttc; + } - if (! empty($arrayfields['dynamount_payed']['checked'])) - { - print ''; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; - $totalarray['totalam'] += $totalpay; - } + if (! empty($arrayfields['dynamount_payed']['checked'])) + { + print ''; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalamfield']=$totalarray['nbfield']; + $totalarray['totalam'] += $totalpay; + } - if (! empty($arrayfields['rtp']['checked'])) - { - print ''; // TODO Use a denormalized field - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; - $totalarray['totalrtp'] += $remaintopay; - } + if (! empty($arrayfields['rtp']['checked'])) + { + print ''; // TODO Use a denormalized field + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; + $totalarray['totalrtp'] += $remaintopay; + } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['f.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['f.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['f.fk_statut']['checked'])) - { - print '"; - if (! $i) $totalarray['nbfield']++; - } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['f.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['f.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['f.fk_statut']['checked'])) + { + print '"; + if (! $i) $totalarray['nbfield']++; + } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; $i++; } - // Show total line - if (isset($totalarray['totalhtfield']) + // Show total line + if (isset($totalarray['totalhtfield']) || isset($totalarray['totalvatfield']) || isset($totalarray['totallocaltax1field']) || isset($totalarray['totallocaltax2field']) @@ -1124,29 +1121,29 @@ if ($resql) || isset($totalarray['totalamfield']) || isset($totalarray['totalrtpfield']) ) - { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''; - elseif ($totalarray['totalvatfield'] == $i) print ''; - elseif ($totalarray['totallocaltax1field'] == $i) print ''; - elseif ($totalarray['totallocaltax2field'] == $i) print ''; - elseif ($totalarray['totalttcfield'] == $i) print ''; - elseif ($totalarray['totalamfield'] == $i) print ''; - elseif ($totalarray['totalrtpfield'] == $i) print ''; - else print ''; - } - print ''; + { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''; + elseif ($totalarray['totalvatfield'] == $i) print ''; + elseif ($totalarray['totallocaltax1field'] == $i) print ''; + elseif ($totalarray['totallocaltax2field'] == $i) print ''; + elseif ($totalarray['totalttcfield'] == $i) print ''; + elseif ($totalarray['totalamfield'] == $i) print ''; + elseif ($totalarray['totalrtpfield'] == $i) print ''; + else print ''; + } + print ''; - } + } } $db->free($resql); @@ -1156,11 +1153,11 @@ if ($resql) print $hookmanager->resPrint; print "
    '; - print $facturestatic->getNomUrl(1); - print ''; - //print ''; - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid,2,0,0,$facturestatic,'invoice_supplier').dol_sanitizeFileName($obj->ref); + print ''; + // Picto + Ref + print ''; + // Warning + //print ''; + // Other picto tool + print '
    '; + print $facturestatic->getNomUrl(1); + print ''; + //print ''; + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid,2,0,0,$facturestatic,'invoice_supplier').dol_sanitizeFileName($obj->ref); $subdir = get_exdir($obj->facid,2,0,0,$facturestatic,'invoice_supplier').dol_sanitizeFileName($obj->ref); print $formfile->getDocumentsLink('facture_fournisseur', $subdir, $filedir); print '
    '; - print "
    '; - print $obj->ref_supplier; - print ''; + print $obj->ref_supplier; + print ''; - print $obj->label; - print ''; + print $obj->label; + print ''; - print dol_print_date($db->jdate($obj->datef),'day'); - print ''; + print dol_print_date($db->jdate($obj->datef),'day'); + print ''.dol_print_date($datelimit,'day'); - if ($facturestatic->hasDelay()) - { - print img_warning($langs->trans('Late')); - } - print ''.dol_print_date($datelimit,'day'); + if ($facturestatic->hasDelay()) + { + print img_warning($langs->trans('Late')); + } + print ''; - if ($obj->project_id > 0) - { - $projectstatic->id=$obj->project_id; - $projectstatic->ref=$obj->project_ref; - print $projectstatic->getNomUrl(1); - } - print ''; + if ($obj->project_id > 0) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print $projectstatic->getNomUrl(1); + } + print ''; - $thirdparty=new Societe($db); - $thirdparty->id=$obj->socid; - $thirdparty->name=$obj->name; - $thirdparty->client=$obj->client; - $thirdparty->code_client=$obj->code_client; - print $thirdparty->getNomUrl(1,'supplier'); - print ''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; + $thirdparty=new Societe($db); + $thirdparty->id=$obj->socid; + $thirdparty->name=$obj->name; + $thirdparty->client=$obj->client; + $thirdparty->code_client=$obj->code_client; + print $thirdparty->getNomUrl(1,'supplier'); + print ''; + print $obj->town; + print ''; + print $obj->zip; + print '".$obj->state_name."'; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; + print ''; - $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); - print ''; + $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); + print ''.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_localtax1)."'.price($obj->total_localtax2)."'.price($obj->total_ttc)."'.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_localtax1)."'.price($obj->total_localtax2)."'.price($obj->total_ttc)."'.(! empty($totalpay)?price($totalpay,0,$langs):' ').''.(! empty($totalpay)?price($totalpay,0,$langs):' ').''.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').''.(! empty($remaintopay)?price($remaintopay,0,$langs):' ').''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; - // TODO $paiement is not yet defined - print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); - print "'; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); + print ''; + // TODO $paiement is not yet defined + print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5,$paiement,$obj->type); + print "'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->facid, $arrayofselected)) $selected=1; - print ''; - } - print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->facid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totallocaltax1']).''.price($totalarray['totallocaltax2']).''.price($totalarray['totalttc']).''.price($totalarray['totalam']).''.price($totalarray['totalrtp']).'
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totallocaltax1']).''.price($totalarray['totallocaltax2']).''.price($totalarray['totalttc']).''.price($totalarray['totalam']).''.price($totalarray['totalrtp']).'
    \n"; - print ''; + print ''; print "\n"; - /* + /* if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { // Show list of available documents diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php index 9df425040e1..6afe9f37c8c 100644 --- a/htdocs/fourn/facture/note.php +++ b/htdocs/fourn/facture/note.php @@ -76,14 +76,14 @@ if ($object->id > 0) $object->fetch_thirdparty(); $alreadypaid=$object->getSommePaiement(); - + $head = facturefourn_prepare_head($object); $titre=$langs->trans('SupplierInvoice'); dol_fiche_head($head, 'note', $titre, -1, 'bill'); // Supplier invoice card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
    '; // Ref supplier @@ -128,7 +128,7 @@ if ($object->id > 0) $object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); print '
    '; print '
    '; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index d6fd80e47fe..000bf0b9743 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -745,7 +745,7 @@ if (empty($action)) $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; @@ -913,7 +913,7 @@ if (empty($action)) print '
    '.$objp->num_paiement.''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.dol_trunc($objp->label,24).''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.dol_trunc($objp->label,24).''; else print ' '; print '
    '.$form->editfieldkey("Date",'datep',$object->date,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; - print $form->editfieldval("Date",'datep',$object->date,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'datepicker','',null,$langs->trans('PaymentDateUpdateSucceeded')); - print '
    '.$form->editfieldkey("Date",'datep',$object->date,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; + print $form->editfieldval("Date",'datep',$object->date,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'datepicker','',null,$langs->trans('PaymentDateUpdateSucceeded')); + print '
    '.$langs->trans('PaymentMode').''.$labeltype.'
    '.$form->editfieldkey("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; - print $form->editfieldval("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded')); - print '
    '.$form->editfieldkey("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; + print $form->editfieldval("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded')); + print '
    '.$langs->trans('Amount').''.price($object->montant,'',$langs,0,0,-1,$conf->currency).'
    '.$form->editfieldkey("Note",'note',$object->note,$object,$user->rights->fournisseur->facture->creer).''; - print $form->editfieldval("Note",'note',$object->note,$object,$user->rights->fournisseur->facture->creer,'textarea'); - print '
    '.$form->editfieldkey("Note",'note',$object->note,$object,$user->rights->fournisseur->facture->creer).''; + print $form->editfieldval("Note",'note',$object->note,$object,$user->rights->fournisseur->facture->creer,'textarea'); + print '
    '.$langs->trans('BankTransactionLine').''; - print $bankline->getNomUrl(1,0,'showconciliated'); - print '
    '.$langs->trans('BankTransactionLine').''; + print $bankline->getNomUrl(1,0,'showconciliated'); + print '
    '.$langs->trans('BankAccount').'
    '.$langs->trans('BankAccount').''; $accountstatic=new Account($db); $accountstatic->fetch($bankline->fk_account); - print $accountstatic->getNomUrl(1); - print '
    '; @@ -335,7 +315,7 @@ if ($result > 0) if ($objp->paye == 1) { $allow_delete = 0; - $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemovePaymentWithOneInvoicePaid")); + $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemovePaymentWithOneInvoicePaid")); } $total = $total + $objp->amount; $i++; @@ -363,8 +343,8 @@ if ($result > 0) { if ($user->societe_id == 0 && $object->statut == 0 && $action == '') { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) { print ''.$langs->trans('Valid').''; @@ -375,45 +355,44 @@ if ($result > 0) { if ($user->rights->fournisseur->facture->supprimer) { - if ($allow_delete) - { + if ($allow_delete) + { print ''.$langs->trans('Delete').''; - } - else - { - print ''.$langs->trans('Delete').''; - } + } + else + { + print ''.$langs->trans('Delete').''; + } } } print '
    '; + /* print '
    '; - /* - * Documents generes - */ - $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; - $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF)?'':$conf->global->SUPPLIER_PAYMENT_ADDON_PDF)); + // Documents generes + $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; + $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); - $somethingshown=$formfile->numoffiles; + print $formfile->showdocuments('supplier_payment',$ref,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang); + $somethingshown=$formfile->numoffiles; 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,'supplier_payment',$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,'supplier_payment',$socid,1,'listaction'.($genallowed?'largetitle':'')); print '
    '; - //print ''; - + //print ''; + */ } else { diff --git a/htdocs/fourn/paiement/info.php b/htdocs/fourn/paiement/info.php index 24263106052..eafc4f2decc 100644 --- a/htdocs/fourn/paiement/info.php +++ b/htdocs/fourn/paiement/info.php @@ -32,9 +32,12 @@ $langs->load("bills"); $langs->load("suppliers"); $langs->load("companies"); -$paiement = new PaiementFourn($db); -$paiement->fetch($_GET["id"], $user); -$paiement->info($_GET["id"]); +$id = GETPOST('id','int'); + +$object = new PaiementFourn($db); +$object->fetch($id); +$object->info($id); + /* * View @@ -42,15 +45,17 @@ $paiement->info($_GET["id"]); llxHeader(); -$head = payment_supplier_prepare_head($paiement); +$head = payment_supplier_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans("SupplierPayment"), 0, 'payment'); -print '
    '; -dol_print_object_info($paiement); -print '
    '; +dol_banner_tab($object, 'id', $linkback, -1, 'rowid', 'ref'); -print '
    '; +dol_fiche_end(); + +print '
    '; +dol_print_object_info($object); +print '
    '; llxFooter(); diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php index 5a6c39840ac..c957ec67a5b 100644 --- a/htdocs/holiday/card.php +++ b/htdocs/holiday/card.php @@ -806,7 +806,7 @@ if (empty($id) || $action == 'add' || $action == 'request' || $action == 'create print '
    '."\n"; print ''."\n"; - dol_fiche_head(); + dol_fiche_head('', '', '', -1); $out=''; $typeleaves=$object->getTypes(1,1); @@ -1045,7 +1045,7 @@ else dol_fiche_head($head, 'card', $langs->trans("CPTitreMenu"), -1, 'holiday'); - $linkback=''.$langs->trans("BackToList").''; + $linkback=''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref'); diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index 10589c9d0b4..ba976c2ee48 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -36,276 +36,277 @@ class Holiday extends CommonObject 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'; + public $picto = 'holiday'; /** * @deprecated * @see id */ - var $rowid; + var $rowid; - var $fk_user; - var $date_create=''; - var $description; - var $date_debut=''; // Date start in PHP server TZ - var $date_fin=''; // Date end in PHP server TZ - var $date_debut_gmt=''; // Date start in GMT - var $date_fin_gmt=''; // Date end in GMT - var $halfday=''; - var $statut=''; // 1=draft, 2=validated, 3=approved - var $fk_validator; - var $date_valid=''; - var $fk_user_valid; - var $date_refuse=''; - var $fk_user_refuse; - var $date_cancel=''; - var $fk_user_cancel; - var $detail_refuse=''; - var $fk_type; + var $fk_user; + var $date_create=''; + var $description; + var $date_debut=''; // Date start in PHP server TZ + var $date_fin=''; // Date end in PHP server TZ + var $date_debut_gmt=''; // Date start in GMT + var $date_fin_gmt=''; // Date end in GMT + var $halfday=''; + var $statut=''; // 1=draft, 2=validated, 3=approved + var $fk_validator; + var $date_valid=''; + var $fk_user_valid; + var $date_refuse=''; + var $fk_user_refuse; + var $date_cancel=''; + var $fk_user_cancel; + var $detail_refuse=''; + var $fk_type; - var $holiday = array(); - var $events = array(); - var $logs = array(); + var $holiday = array(); + var $events = array(); + var $logs = array(); - var $optName = ''; - var $optValue = ''; - var $optRowid = ''; + var $optName = ''; + var $optValue = ''; + var $optRowid = ''; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + } - /** - * Update balance of vacations and check table of users for holidays is complete. If not complete. - * - * @return int <0 if KO, >0 if OK - */ - function updateBalance() - { - $this->db->begin(); + /** + * Update balance of vacations and check table of users for holidays is complete. If not complete. + * + * @return int <0 if KO, >0 if OK + */ + function updateBalance() + { + $this->db->begin(); - // Update sold of vocations - $result = $this->updateSoldeCP(); + // Update sold of vocations + $result = $this->updateSoldeCP(); - // Check nb of users into table llx_holiday_users and update with empty lines - //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser')); + // Check nb of users into table llx_holiday_users and update with empty lines + //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser')); - if ($result >= 0) - { - $this->db->commit(); - return 1; - } - else + if ($result >= 0) { - $this->db->rollback(); - return -1; + $this->db->commit(); + return 1; } - } + else + { + $this->db->rollback(); + return -1; + } + } - /** - * Créer un congés payés dans la base de données - * - * @param User $user User that create - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, Id of created object if OK - */ - function create($user, $notrigger=0) - { - global $conf; - $error=0; + /** + * Créer un congés payés dans la base de données + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + function create($user, $notrigger=0) + { + global $conf; + $error=0; - $now=dol_now(); + $now=dol_now(); - // Check parameters - if (empty($this->fk_user) || ! is_numeric($this->fk_user) || $this->fk_user < 0) { $this->error="ErrorBadParameterFkUser"; return -1; } - if (empty($this->fk_validator) || ! is_numeric($this->fk_validator) || $this->fk_validator < 0) { $this->error="ErrorBadParameterFkValidator"; return -1; } - if (empty($this->fk_type) || ! is_numeric($this->fk_type) || $this->fk_type < 0) { $this->error="ErrorBadParameterFkType"; return -1; } + // Check parameters + if (empty($this->fk_user) || ! is_numeric($this->fk_user) || $this->fk_user < 0) { $this->error="ErrorBadParameterFkUser"; return -1; } + if (empty($this->fk_validator) || ! is_numeric($this->fk_validator) || $this->fk_validator < 0) { $this->error="ErrorBadParameterFkValidator"; return -1; } + if (empty($this->fk_type) || ! is_numeric($this->fk_type) || $this->fk_type < 0) { $this->error="ErrorBadParameterFkType"; return -1; } - // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday("; - $sql.= "fk_user,"; - $sql.= "date_create,"; - $sql.= "description,"; - $sql.= "date_debut,"; - $sql.= "date_fin,"; - $sql.= "halfday,"; - $sql.= "statut,"; - $sql.= "fk_validator,"; - $sql.= "fk_type,"; - $sql.= "fk_user_create,"; - $sql.= "entity"; - $sql.= ") VALUES ("; - $sql.= "'".$this->db->escape($this->fk_user)."',"; - $sql.= " '".$this->db->idate($now)."',"; - $sql.= " '".$this->db->escape($this->description)."',"; - $sql.= " '".$this->db->idate($this->date_debut)."',"; - $sql.= " '".$this->db->idate($this->date_fin)."',"; - $sql.= " ".$this->halfday.","; - $sql.= " '1',"; - $sql.= " '".$this->db->escape($this->fk_validator)."',"; - $sql.= " ".$this->fk_type.","; - $sql.= " ".$user->id.","; - $sql.= " ".$conf->entity; - $sql.= ")"; + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday("; + $sql.= "fk_user,"; + $sql.= "date_create,"; + $sql.= "description,"; + $sql.= "date_debut,"; + $sql.= "date_fin,"; + $sql.= "halfday,"; + $sql.= "statut,"; + $sql.= "fk_validator,"; + $sql.= "fk_type,"; + $sql.= "fk_user_create,"; + $sql.= "entity"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($this->fk_user)."',"; + $sql.= " '".$this->db->idate($now)."',"; + $sql.= " '".$this->db->escape($this->description)."',"; + $sql.= " '".$this->db->idate($this->date_debut)."',"; + $sql.= " '".$this->db->idate($this->date_fin)."',"; + $sql.= " ".$this->halfday.","; + $sql.= " '1',"; + $sql.= " '".$this->db->escape($this->fk_validator)."',"; + $sql.= " ".$this->fk_type.","; + $sql.= " ".$user->id.","; + $sql.= " ".$conf->entity; + $sql.= ")"; - $this->db->begin(); + $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); - } + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) { + $error++; $this->errors[]="Error ".$this->db->lasterror(); + } - if (! $error) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday"); + if (! $error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday"); - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('HOLIDAY_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('HOLIDAY_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return $this->id; - } - } + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return $this->id; + } + } - /** - * Load object in memory from database - * - * @param int $id Id object - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $langs; + /** + * Load object in memory from database + * + * @param int $id Id object + * @return int <0 if KO, >0 if OK + */ + function fetch($id) + { + global $langs; - $sql = "SELECT"; - $sql.= " cp.rowid,"; - $sql.= " cp.fk_user,"; - $sql.= " cp.date_create,"; - $sql.= " cp.description,"; - $sql.= " cp.date_debut,"; - $sql.= " cp.date_fin,"; - $sql.= " cp.halfday,"; - $sql.= " cp.statut,"; - $sql.= " cp.fk_validator,"; - $sql.= " cp.date_valid,"; - $sql.= " cp.fk_user_valid,"; - $sql.= " cp.date_refuse,"; - $sql.= " cp.fk_user_refuse,"; - $sql.= " cp.date_cancel,"; - $sql.= " cp.fk_user_cancel,"; - $sql.= " cp.detail_refuse,"; - $sql.= " cp.note_private,"; - $sql.= " cp.note_public,"; - $sql.= " cp.fk_user_create,"; - $sql.= " cp.fk_type,"; - $sql.= " cp.entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp"; - $sql.= " WHERE cp.rowid = ".$id; + $sql = "SELECT"; + $sql.= " cp.rowid,"; + $sql.= " cp.fk_user,"; + $sql.= " cp.date_create,"; + $sql.= " cp.description,"; + $sql.= " cp.date_debut,"; + $sql.= " cp.date_fin,"; + $sql.= " cp.halfday,"; + $sql.= " cp.statut,"; + $sql.= " cp.fk_validator,"; + $sql.= " cp.date_valid,"; + $sql.= " cp.fk_user_valid,"; + $sql.= " cp.date_refuse,"; + $sql.= " cp.fk_user_refuse,"; + $sql.= " cp.date_cancel,"; + $sql.= " cp.fk_user_cancel,"; + $sql.= " cp.detail_refuse,"; + $sql.= " cp.note_private,"; + $sql.= " cp.note_public,"; + $sql.= " cp.fk_user_create,"; + $sql.= " cp.fk_type,"; + $sql.= " cp.entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp"; + $sql.= " WHERE cp.rowid = ".$id; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->rowid = $obj->rowid; // deprecated - $this->ref = $obj->rowid; - $this->fk_user = $obj->fk_user; - $this->date_create = $this->db->jdate($obj->date_create); - $this->description = $obj->description; - $this->date_debut = $this->db->jdate($obj->date_debut); - $this->date_fin = $this->db->jdate($obj->date_fin); - $this->date_debut_gmt = $this->db->jdate($obj->date_debut,1); - $this->date_fin_gmt = $this->db->jdate($obj->date_fin,1); - $this->halfday = $obj->halfday; - $this->statut = $obj->statut; - $this->fk_validator = $obj->fk_validator; - $this->date_valid = $this->db->jdate($obj->date_valid); - $this->fk_user_valid = $obj->fk_user_valid; - $this->date_refuse = $this->db->jdate($obj->date_refuse); - $this->fk_user_refuse = $obj->fk_user_refuse; - $this->date_cancel = $this->db->jdate($obj->date_cancel); - $this->fk_user_cancel = $obj->fk_user_cancel; - $this->detail_refuse = $obj->detail_refuse; - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->fk_user_create = $obj->fk_user_create; - $this->fk_type = $obj->fk_type; - $this->entity = $obj->entity; - } - $this->db->free($resql); + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; // deprecated + $this->ref = $obj->rowid; + $this->fk_user = $obj->fk_user; + $this->date_create = $this->db->jdate($obj->date_create); + $this->description = $obj->description; + $this->date_debut = $this->db->jdate($obj->date_debut); + $this->date_fin = $this->db->jdate($obj->date_fin); + $this->date_debut_gmt = $this->db->jdate($obj->date_debut,1); + $this->date_fin_gmt = $this->db->jdate($obj->date_fin,1); + $this->halfday = $obj->halfday; + $this->statut = $obj->statut; + $this->fk_validator = $obj->fk_validator; + $this->date_valid = $this->db->jdate($obj->date_valid); + $this->fk_user_valid = $obj->fk_user_valid; + $this->date_refuse = $this->db->jdate($obj->date_refuse); + $this->fk_user_refuse = $obj->fk_user_refuse; + $this->date_cancel = $this->db->jdate($obj->date_cancel); + $this->fk_user_cancel = $obj->fk_user_cancel; + $this->detail_refuse = $obj->detail_refuse; + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->fk_user_create = $obj->fk_user_create; + $this->fk_type = $obj->fk_type; + $this->entity = $obj->entity; + } + $this->db->free($resql); - return 1; - } - else - { - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } + return 1; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } - /** - * List holidays for a particular user - * - * @param int $user_id ID of user to list - * @param string $order Sort order - * @param string $filter SQL Filter - * @return int -1 if KO, 1 if OK, 2 if no result - */ - function fetchByUser($user_id, $order='', $filter='') - { - global $langs, $conf; + /** + * List holidays for a particular user + * + * @param int $user_id ID of user to list + * @param string $order Sort order + * @param string $filter SQL Filter + * @return int -1 if KO, 1 if OK, 2 if no result + */ + function fetchByUser($user_id, $order='', $filter='') + { + global $langs, $conf; - $sql = "SELECT"; - $sql.= " cp.rowid,"; + $sql = "SELECT"; + $sql.= " cp.rowid,"; - $sql.= " cp.fk_user,"; - $sql.= " cp.date_create,"; - $sql.= " cp.description,"; - $sql.= " cp.date_debut,"; - $sql.= " cp.date_fin,"; - $sql.= " cp.halfday,"; - $sql.= " cp.statut,"; - $sql.= " cp.fk_validator,"; - $sql.= " cp.date_valid,"; - $sql.= " cp.fk_user_valid,"; - $sql.= " cp.date_refuse,"; - $sql.= " cp.fk_user_refuse,"; - $sql.= " cp.date_cancel,"; - $sql.= " cp.fk_user_cancel,"; - $sql.= " cp.detail_refuse,"; + $sql.= " cp.fk_user,"; + $sql.= " cp.fk_type,"; + $sql.= " cp.date_create,"; + $sql.= " cp.description,"; + $sql.= " cp.date_debut,"; + $sql.= " cp.date_fin,"; + $sql.= " cp.halfday,"; + $sql.= " cp.statut,"; + $sql.= " cp.fk_validator,"; + $sql.= " cp.date_valid,"; + $sql.= " cp.fk_user_valid,"; + $sql.= " cp.date_refuse,"; + $sql.= " cp.fk_user_refuse,"; + $sql.= " cp.date_cancel,"; + $sql.= " cp.fk_user_cancel,"; + $sql.= " cp.detail_refuse,"; $sql.= " uu.lastname as user_lastname,"; $sql.= " uu.firstname as user_firstname,"; @@ -313,542 +314,554 @@ class Holiday extends CommonObject $sql.= " uu.statut as user_statut,"; $sql.= " uu.photo as user_photo,"; - $sql.= " ua.lastname as validator_lastname,"; - $sql.= " ua.firstname as validator_firstname,"; - $sql.= " ua.login as validator_login,"; - $sql.= " ua.statut as validator_statut,"; - $sql.= " ua.photo as validator_photo"; + $sql.= " ua.lastname as validator_lastname,"; + $sql.= " ua.firstname as validator_firstname,"; + $sql.= " ua.login as validator_login,"; + $sql.= " ua.statut as validator_statut,"; + $sql.= " ua.photo as validator_photo"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua"; - $sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua"; + $sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; $sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau - $sql.= " AND cp.fk_user = '".$user_id."'"; + $sql.= " AND cp.fk_user = ".$user_id; - // Filtre de séléction - if(!empty($filter)) { - $sql.= $filter; - } + // Filtre de séléction + if(!empty($filter)) { + $sql.= $filter; + } - // Ordre d'affichage du résultat - if(!empty($order)) { - $sql.= $order; - } + // Ordre d'affichage du résultat + if(!empty($order)) { + $sql.= $order; + } - dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG); + $resql=$this->db->query($sql); - // Si pas d'erreur SQL - if ($resql) { + // Si pas d'erreur SQL + if ($resql) { - $i = 0; - $tab_result = $this->holiday; - $num = $this->db->num_rows($resql); + $i = 0; + $tab_result = $this->holiday; + $num = $this->db->num_rows($resql); - // Si pas d'enregistrement - if(!$num) { - return 2; - } + // Si pas d'enregistrement + if(!$num) { + return 2; + } - // Liste les enregistrements et les ajoutent au tableau - while($i < $num) { + // Liste les enregistrements et les ajoutent au tableau + while($i < $num) { - $obj = $this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); - $tab_result[$i]['rowid'] = $obj->rowid; - $tab_result[$i]['ref'] = $obj->rowid; - $tab_result[$i]['fk_user'] = $obj->fk_user; - $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create); - $tab_result[$i]['description'] = $obj->description; - $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut); - $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin); - $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1); - $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1); - $tab_result[$i]['halfday'] = $obj->halfday; - $tab_result[$i]['statut'] = $obj->statut; - $tab_result[$i]['fk_validator'] = $obj->fk_validator; - $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid); - $tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid; - $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse); - $tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse; - $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel); - $tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel; - $tab_result[$i]['detail_refuse'] = $obj->detail_refuse; + $tab_result[$i]['rowid'] = $obj->rowid; + $tab_result[$i]['ref'] = $obj->rowid; + $tab_result[$i]['fk_user'] = $obj->fk_user; + $tab_result[$i]['fk_type'] = $obj->fk_type; + $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create); + $tab_result[$i]['description'] = $obj->description; + $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut); + $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin); + $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1); + $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1); + $tab_result[$i]['halfday'] = $obj->halfday; + $tab_result[$i]['statut'] = $obj->statut; + $tab_result[$i]['fk_validator'] = $obj->fk_validator; + $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid); + $tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid; + $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse); + $tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse; + $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel); + $tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel; + $tab_result[$i]['detail_refuse'] = $obj->detail_refuse; - $tab_result[$i]['user_firstname'] = $obj->user_firstname; - $tab_result[$i]['user_lastname'] = $obj->user_lastname; - $tab_result[$i]['user_login'] = $obj->user_login; - $tab_result[$i]['user_statut'] = $obj->user_statut; - $tab_result[$i]['user_photo'] = $obj->user_photo; + $tab_result[$i]['user_firstname'] = $obj->user_firstname; + $tab_result[$i]['user_lastname'] = $obj->user_lastname; + $tab_result[$i]['user_login'] = $obj->user_login; + $tab_result[$i]['user_statut'] = $obj->user_statut; + $tab_result[$i]['user_photo'] = $obj->user_photo; - $tab_result[$i]['validator_firstname'] = $obj->validator_firstname; - $tab_result[$i]['validator_lastname'] = $obj->validator_lastname; - $tab_result[$i]['validator_login'] = $obj->validator_login; - $tab_result[$i]['validator_statut'] = $obj->validator_statut; - $tab_result[$i]['validator_photo'] = $obj->validator_photo; + $tab_result[$i]['validator_firstname'] = $obj->validator_firstname; + $tab_result[$i]['validator_lastname'] = $obj->validator_lastname; + $tab_result[$i]['validator_login'] = $obj->validator_login; + $tab_result[$i]['validator_statut'] = $obj->validator_statut; + $tab_result[$i]['validator_photo'] = $obj->validator_photo; - $i++; - } + $i++; + } - // Retourne 1 avec le tableau rempli - $this->holiday = $tab_result; - return 1; - } - else - { - // Erreur SQL - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } + // Retourne 1 avec le tableau rempli + $this->holiday = $tab_result; + return 1; + } + else + { + // Erreur SQL + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } - /** - * List all holidays of all users - * - * @param string $order Sort order - * @param string $filter SQL Filter - * @return int -1 if KO, 1 if OK, 2 if no result - */ - function fetchAll($order,$filter) - { - global $langs; + /** + * List all holidays of all users + * + * @param string $order Sort order + * @param string $filter SQL Filter + * @return int -1 if KO, 1 if OK, 2 if no result + */ + function fetchAll($order,$filter) + { + global $langs; - $sql = "SELECT"; - $sql.= " cp.rowid,"; + $sql = "SELECT"; + $sql.= " cp.rowid,"; - $sql.= " cp.fk_user,"; - $sql.= " cp.fk_type,"; - $sql.= " cp.date_create,"; - $sql.= " cp.description,"; - $sql.= " cp.date_debut,"; - $sql.= " cp.date_fin,"; - $sql.= " cp.halfday,"; - $sql.= " cp.statut,"; - $sql.= " cp.fk_validator,"; - $sql.= " cp.date_valid,"; - $sql.= " cp.fk_user_valid,"; - $sql.= " cp.date_refuse,"; - $sql.= " cp.fk_user_refuse,"; - $sql.= " cp.date_cancel,"; - $sql.= " cp.fk_user_cancel,"; - $sql.= " cp.detail_refuse,"; + $sql.= " cp.fk_user,"; + $sql.= " cp.fk_type,"; + $sql.= " cp.date_create,"; + $sql.= " cp.description,"; + $sql.= " cp.date_debut,"; + $sql.= " cp.date_fin,"; + $sql.= " cp.halfday,"; + $sql.= " cp.statut,"; + $sql.= " cp.fk_validator,"; + $sql.= " cp.date_valid,"; + $sql.= " cp.fk_user_valid,"; + $sql.= " cp.date_refuse,"; + $sql.= " cp.fk_user_refuse,"; + $sql.= " cp.date_cancel,"; + $sql.= " cp.fk_user_cancel,"; + $sql.= " cp.detail_refuse,"; - $sql.= " uu.lastname as user_lastname,"; - $sql.= " uu.firstname as user_firstname,"; - $sql.= " uu.login as user_login,"; - $sql.= " uu.statut as user_statut,"; - $sql.= " uu.photo as user_photo,"; + $sql.= " uu.lastname as user_lastname,"; + $sql.= " uu.firstname as user_firstname,"; + $sql.= " uu.login as user_login,"; + $sql.= " uu.statut as user_statut,"; + $sql.= " uu.photo as user_photo,"; - $sql.= " ua.lastname as validator_lastname,"; - $sql.= " ua.firstname as validator_firstname,"; - $sql.= " ua.login as validator_login,"; - $sql.= " ua.statut as validator_statut,"; - $sql.= " ua.photo as validator_photo"; + $sql.= " ua.lastname as validator_lastname,"; + $sql.= " ua.firstname as validator_firstname,"; + $sql.= " ua.login as validator_login,"; + $sql.= " ua.statut as validator_statut,"; + $sql.= " ua.photo as validator_photo"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua"; - $sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; - $sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau + $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua"; + $sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; + $sql.= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau - // Filtrage de séléction - if(!empty($filter)) { - $sql.= $filter; - } + // Filtrage de séléction + if(!empty($filter)) { + $sql.= $filter; + } - // Ordre d'affichage - if(!empty($order)) { - $sql.= $order; - } + // Ordre d'affichage + if(!empty($order)) { + $sql.= $order; + } - dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); + $resql=$this->db->query($sql); - // Si pas d'erreur SQL - if ($resql) { + // Si pas d'erreur SQL + if ($resql) { - $i = 0; - $tab_result = $this->holiday; - $num = $this->db->num_rows($resql); + $i = 0; + $tab_result = $this->holiday; + $num = $this->db->num_rows($resql); - // Si pas d'enregistrement - if(!$num) { - return 2; - } + // Si pas d'enregistrement + if(!$num) { + return 2; + } - // On liste les résultats et on les ajoutent dans le tableau - while($i < $num) { + // On liste les résultats et on les ajoutent dans le tableau + while($i < $num) { - $obj = $this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); - $tab_result[$i]['rowid'] = $obj->rowid; - $tab_result[$i]['ref'] = $obj->rowid; - $tab_result[$i]['fk_user'] = $obj->fk_user; - $tab_result[$i]['fk_type'] = $obj->fk_type; - $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create); - $tab_result[$i]['description'] = $obj->description; - $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut); - $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin); - $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1); - $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1); - $tab_result[$i]['halfday'] = $obj->halfday; - $tab_result[$i]['statut'] = $obj->statut; - $tab_result[$i]['fk_validator'] = $obj->fk_validator; - $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid); - $tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid; - $tab_result[$i]['date_refuse'] = $obj->date_refuse; - $tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse; - $tab_result[$i]['date_cancel'] = $obj->date_cancel; - $tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel; - $tab_result[$i]['detail_refuse'] = $obj->detail_refuse; + $tab_result[$i]['rowid'] = $obj->rowid; + $tab_result[$i]['ref'] = $obj->rowid; + $tab_result[$i]['fk_user'] = $obj->fk_user; + $tab_result[$i]['fk_type'] = $obj->fk_type; + $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create); + $tab_result[$i]['description'] = $obj->description; + $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut); + $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin); + $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut,1); + $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin,1); + $tab_result[$i]['halfday'] = $obj->halfday; + $tab_result[$i]['statut'] = $obj->statut; + $tab_result[$i]['fk_validator'] = $obj->fk_validator; + $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid); + $tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid; + $tab_result[$i]['date_refuse'] = $obj->date_refuse; + $tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse; + $tab_result[$i]['date_cancel'] = $obj->date_cancel; + $tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel; + $tab_result[$i]['detail_refuse'] = $obj->detail_refuse; - $tab_result[$i]['user_firstname'] = $obj->user_firstname; - $tab_result[$i]['user_lastname'] = $obj->user_lastname; - $tab_result[$i]['user_login'] = $obj->user_login; - $tab_result[$i]['user_statut'] = $obj->user_statut; - $tab_result[$i]['user_photo'] = $obj->user_photo; + $tab_result[$i]['user_firstname'] = $obj->user_firstname; + $tab_result[$i]['user_lastname'] = $obj->user_lastname; + $tab_result[$i]['user_login'] = $obj->user_login; + $tab_result[$i]['user_statut'] = $obj->user_statut; + $tab_result[$i]['user_photo'] = $obj->user_photo; - $tab_result[$i]['validator_firstname'] = $obj->validator_firstname; - $tab_result[$i]['validator_lastname'] = $obj->validator_lastname; - $tab_result[$i]['validator_login'] = $obj->validator_login; - $tab_result[$i]['validator_statut'] = $obj->validator_statut; - $tab_result[$i]['validator_photo'] = $obj->validator_photo; + $tab_result[$i]['validator_firstname'] = $obj->validator_firstname; + $tab_result[$i]['validator_lastname'] = $obj->validator_lastname; + $tab_result[$i]['validator_login'] = $obj->validator_login; + $tab_result[$i]['validator_statut'] = $obj->validator_statut; + $tab_result[$i]['validator_photo'] = $obj->validator_photo; - $i++; - } - // Retourne 1 et ajoute le tableau à la variable - $this->holiday = $tab_result; - return 1; - } - else - { - // Erreur SQL - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } + $i++; + } + // Retourne 1 et ajoute le tableau à la variable + $this->holiday = $tab_result; + return 1; + } + else + { + // Erreur SQL + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function update($user=null, $notrigger=0) - { - global $conf, $langs; - $error=0; + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function update($user=null, $notrigger=0) + { + global $conf, $langs; + $error=0; - // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET"; + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET"; - $sql.= " description= '".$this->db->escape($this->description)."',"; + $sql.= " description= '".$this->db->escape($this->description)."',"; - if(!empty($this->date_debut)) { - $sql.= " date_debut = '".$this->db->idate($this->date_debut)."',"; - } else { - $error++; - } - if(!empty($this->date_fin)) { - $sql.= " date_fin = '".$this->db->idate($this->date_fin)."',"; - } else { - $error++; - } - $sql.= " halfday = ".$this->halfday.","; - if(!empty($this->statut) && is_numeric($this->statut)) { - $sql.= " statut = ".$this->statut.","; - } else { - $error++; - } - if(!empty($this->fk_validator)) { - $sql.= " fk_validator = '".$this->db->escape($this->fk_validator)."',"; - } else { - $error++; - } - if(!empty($this->date_valid)) { - $sql.= " date_valid = '".$this->db->idate($this->date_valid)."',"; - } else { - $sql.= " date_valid = NULL,"; - } - if(!empty($this->fk_user_valid)) { - $sql.= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',"; - } else { - $sql.= " fk_user_valid = NULL,"; - } - if(!empty($this->date_refuse)) { - $sql.= " date_refuse = '".$this->db->idate($this->date_refuse)."',"; - } else { - $sql.= " date_refuse = NULL,"; - } - if(!empty($this->fk_user_refuse)) { - $sql.= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',"; - } else { - $sql.= " fk_user_refuse = NULL,"; - } - if(!empty($this->date_cancel)) { - $sql.= " date_cancel = '".$this->db->idate($this->date_cancel)."',"; - } else { - $sql.= " date_cancel = NULL,"; - } - if(!empty($this->fk_user_cancel)) { - $sql.= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',"; - } else { - $sql.= " fk_user_cancel = NULL,"; - } - if(!empty($this->detail_refuse)) { - $sql.= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'"; - } else { - $sql.= " detail_refuse = NULL"; - } + if(!empty($this->date_debut)) { + $sql.= " date_debut = '".$this->db->idate($this->date_debut)."',"; + } else { + $error++; + } + if(!empty($this->date_fin)) { + $sql.= " date_fin = '".$this->db->idate($this->date_fin)."',"; + } else { + $error++; + } + $sql.= " halfday = ".$this->halfday.","; + if(!empty($this->statut) && is_numeric($this->statut)) { + $sql.= " statut = ".$this->statut.","; + } else { + $error++; + } + if(!empty($this->fk_validator)) { + $sql.= " fk_validator = '".$this->db->escape($this->fk_validator)."',"; + } else { + $error++; + } + if(!empty($this->date_valid)) { + $sql.= " date_valid = '".$this->db->idate($this->date_valid)."',"; + } else { + $sql.= " date_valid = NULL,"; + } + if(!empty($this->fk_user_valid)) { + $sql.= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',"; + } else { + $sql.= " fk_user_valid = NULL,"; + } + if(!empty($this->date_refuse)) { + $sql.= " date_refuse = '".$this->db->idate($this->date_refuse)."',"; + } else { + $sql.= " date_refuse = NULL,"; + } + if(!empty($this->fk_user_refuse)) { + $sql.= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',"; + } else { + $sql.= " fk_user_refuse = NULL,"; + } + if(!empty($this->date_cancel)) { + $sql.= " date_cancel = '".$this->db->idate($this->date_cancel)."',"; + } else { + $sql.= " date_cancel = NULL,"; + } + if(!empty($this->fk_user_cancel)) { + $sql.= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',"; + } else { + $sql.= " fk_user_cancel = NULL,"; + } + if(!empty($this->detail_refuse)) { + $sql.= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'"; + } else { + $sql.= " detail_refuse = NULL"; + } - $sql.= " WHERE rowid= ".$this->id; + $sql.= " WHERE rowid= ".$this->id; - $this->db->begin(); + $this->db->begin(); - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error++; $this->errors[]="Error ".$this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('HOLIDAY_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('HOLIDAY_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } - // 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; - } - } + // 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; + } + } - /** - * Delete object in database - * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ - function delete($user, $notrigger=0) - { - global $conf, $langs; - $error=0; + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger=0) + { + global $conf, $langs; + $error=0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday"; - $sql.= " WHERE rowid=".$this->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday"; + $sql.= " WHERE rowid=".$this->id; - $this->db->begin(); + $this->db->begin(); - dol_syslog(get_class($this)."::delete", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { - $error++; $this->errors[]="Error ".$this->db->lasterror(); - } + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error++; $this->errors[]="Error ".$this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('HOLIDAY_DELETE',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('HOLIDAY_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return 1; - } - } + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } - /** - * Check if a user is on holiday (partially or completely) into a period. - * This function can be used to avoid to have 2 leave requests on same period for example. - * Warning: It consumes a lot of memory because it load in ->holiday all holiday of a dedicated user at each call. - * - * @param int $fk_user Id user - * @param date $dateDebut Start date of period to check - * @param date $dateFin End date of period to check - * @param int $halfday Tag to define how start and end the period to check: - * 0:Full days, 2:Sart afternoon end monring, -1:Start afternoon, 1:End morning - * @return boolean False is on holiday at least partially into the period, True is never on holiday during chcked period. - * @see verifDateHolidayForTimestamp - */ - function verifDateHolidayCP($fk_user, $dateDebut, $dateFin, $halfday=0) - { - $this->fetchByUser($fk_user,'',''); + /** + * Check if a user is on holiday (partially or completely) into a period. + * This function can be used to avoid to have 2 leave requests on same period for example. + * Warning: It consumes a lot of memory because it load in ->holiday all holiday of a dedicated user at each call. + * + * @param int $fk_user Id user + * @param date $dateDebut Start date of period to check + * @param date $dateFin End date of period to check + * @param int $halfday Tag to define how start and end the period to check: + * 0:Full days, 2:Sart afternoon end monring, -1:Start afternoon, 1:End morning + * @return boolean False is on holiday at least partially into the period, True is never on holiday during chcked period. + * @see verifDateHolidayForTimestamp + */ + function verifDateHolidayCP($fk_user, $dateDebut, $dateFin, $halfday=0) + { + $this->fetchByUser($fk_user,'',''); - foreach($this->holiday as $infos_CP) - { - if ($infos_CP['statut'] == 4) continue; // ignore not validated holidays - if ($infos_CP['statut'] == 5) continue; // ignore not validated holidays + foreach($this->holiday as $infos_CP) + { + if ($infos_CP['statut'] == 4) continue; // ignore not validated holidays + if ($infos_CP['statut'] == 5) continue; // ignore not validated holidays - // TODO Also use halfday for the check - if ($halfday == 0) - { - if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) - { - return false; - } - } - elseif ($halfday == -1) - { - if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) - { - return false; - } - } - elseif ($halfday == 1) - { - if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) - { - return false; - } - } - elseif ($halfday == 2) - { - if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) - { - return false; - } - } - else - { - dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP'); - } - } + // TODO Also use halfday for the check + if ($halfday == 0) + { + if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) + { + return false; + } + } + elseif ($halfday == -1) + { + if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) + { + return false; + } + } + elseif ($halfday == 1) + { + if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) + { + return false; + } + } + elseif ($halfday == 2) + { + if ($dateDebut >= $infos_CP['date_debut'] && $dateDebut <= $infos_CP['date_fin'] || $dateFin <= $infos_CP['date_fin'] && $dateFin >= $infos_CP['date_debut']) + { + return false; + } + } + else + { + dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP'); + } + } - return true; - } + return true; + } - /** - * Check a user is not on holiday for a particular timestamp - * - * @param int $fk_user Id user - * @param timestamp $timestamp Time stamp date for a day (YYYY-MM-DD) without hours (= 12:00AM in english and not 12:00PM that is 12:00) - * @return array array('morning'=> ,'afternoon'=> ), Boolean is true if user is available for day timestamp. - * @see verifDateHolidayCP - */ - function verifDateHolidayForTimestamp($fk_user, $timestamp) - { - global $langs, $conf; + /** + * Check a user is not on holiday for a particular timestamp + * + * @param int $fk_user Id user + * @param timestamp $timestamp Time stamp date for a day (YYYY-MM-DD) without hours (= 12:00AM in english and not 12:00PM that is 12:00) + * @return array array('morning'=> ,'afternoon'=> ), Boolean is true if user is available for day timestamp. + * @see verifDateHolidayCP + */ + function verifDateHolidayForTimestamp($fk_user, $timestamp) + { + global $langs, $conf; - $isavailablemorning=true; - $isavailableafternoon=true; + $isavailablemorning=true; + $isavailableafternoon=true; - $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp"; - $sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; - $sql.= " AND cp.fk_user = ".(int) $fk_user; + $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp"; + $sql.= " WHERE cp.entity IN (".getEntity('holiday').")"; + $sql.= " AND cp.fk_user = ".(int) $fk_user; $sql.= " AND date_debut <= '".$this->db->idate($timestamp)."' AND date_fin >= '".$this->db->idate($timestamp)."'"; - $resql = $this->db->query($sql); - if ($resql) - { - $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon - if ($num_rows > 0) - { - $i=0; - while ($i < $num_rows) - { - $obj = $this->db->fetch_object($resql); + $resql = $this->db->query($sql); + if ($resql) + { + $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon + if ($num_rows > 0) + { + $arrayofrecord=array(); + $i=0; + while ($i < $num_rows) + { + $obj = $this->db->fetch_object($resql); - // Note: $obj->halday is 0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning - $arrayofrecord[$obj->rowid]=array('date_start'=>$this->db->jdate($obj->date_start), 'date_end'=>$this->db->jdate($obj->date_end), 'halfday'=>$obj->halfday); - $i++; - } + // Note: $obj->halfday is 0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning + $arrayofrecord[$obj->rowid]=array('date_start'=>$this->db->jdate($obj->date_start), 'date_end'=>$this->db->jdate($obj->date_end), 'halfday'=>$obj->halfday); + $i++; + } - // We found a record, user is on holiday by default, so is not available is true. - $isavailablemorning = true; - foreach($arrayofrecord as $record) - { + // We found a record, user is on holiday by default, so is not available is true. + $isavailablemorning = true; + foreach($arrayofrecord as $record) + { if ($timestamp == $record['date_start'] && $record['halfday'] == 2) continue; if ($timestamp == $record['date_start'] && $record['halfday'] == -1) continue; - $isavailablemorning = false; - break; - } - $isavailableafternoon = true; - foreach($arrayofrecord as $record) - { + $isavailablemorning = false; + break; + } + $isavailableafternoon = true; + foreach($arrayofrecord as $record) + { if ($timestamp == $record['date_end'] && $record['halfday'] == 2) continue; if ($timestamp == $record['date_end'] && $record['halfday'] == 1) continue; - $isavailableafternoon = false; - break; - } - } - } - else dol_print_error($this->db); + $isavailableafternoon = false; + break; + } + } + } + else dol_print_error($this->db); return array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon); - } + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpicto 0=_No picto, 1=Includes the picto in the linkn, 2=Picto only - * @return string String with URL - */ - function getNomUrl($withpicto=0) - { - global $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=_No picto, 1=Includes the picto in the linkn, 2=Picto only + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $save_lastsearch_value=-1) + { + global $langs; - $result=''; - $label=$langs->trans("Show").': '.$this->ref; + $result=''; + $picto='holiday'; + $label=$langs->trans("Show").': '.$this->ref; - $link = ''; - $linkend=''; + $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id; - $picto='holiday'; + //if ($option != 'nolink') + //{ + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + //} - if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$link.$this->ref.$linkend; - return $result; - } + $linkstart = ''; + $linkend=''; + + if ($withpicto) $result.=($linkstart.img_object($label, $picto, 'class="classfortooltip"').$linkend); + if ($withpicto && $withpicto != 2) $result.=' '; + if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend; + return $result; + } - /** - * Returns the label status - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto - * @return string Label - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut, $mode, $this->date_debut); - } + /** + * Returns the label status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut, $mode, $this->date_debut); + } /** * Returns the label of a statut @@ -864,11 +877,11 @@ class Holiday extends CommonObject if ($mode == 0) { - if ($statut == 1) return $langs->trans('DraftCP'); - if ($statut == 2) return $langs->trans('ToReviewCP'); - if ($statut == 3) return $langs->trans('ApprovedCP'); - if ($statut == 4) return $langs->trans('CancelCP'); - if ($statut == 5) return $langs->trans('RefuseCP'); + if ($statut == 1) return $langs->trans('DraftCP'); + if ($statut == 2) return $langs->trans('ToReviewCP'); + if ($statut == 3) return $langs->trans('ApprovedCP'); + if ($statut == 4) return $langs->trans('CancelCP'); + if ($statut == 5) return $langs->trans('RefuseCP'); } if ($mode == 2) { @@ -902,859 +915,865 @@ class Holiday extends CommonObject } if ($mode == 6) { - $pictoapproved='statut6'; - if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4'; - if ($statut == 1) return $langs->trans('DraftCP').' '.img_picto($langs->trans('DraftCP'),'statut0'); // Draft - if ($statut == 2) return $langs->trans('ToReviewCP').' '.img_picto($langs->trans('ToReviewCP'),'statut1'); // Waiting approval - if ($statut == 3) return $langs->trans('ApprovedCP').' '.img_picto($langs->trans('ApprovedCP'),$pictoapproved); - if ($statut == 4) return $langs->trans('CancelCP').' '.img_picto($langs->trans('CancelCP'),'statut5'); - if ($statut == 5) return $langs->trans('RefuseCP').' '.img_picto($langs->trans('RefuseCP'),'statut5'); + $pictoapproved='statut6'; + if (! empty($startdate) && $startdate > dol_now()) $pictoapproved='statut4'; + if ($statut == 1) return $langs->trans('DraftCP').' '.img_picto($langs->trans('DraftCP'),'statut0'); // Draft + if ($statut == 2) return $langs->trans('ToReviewCP').' '.img_picto($langs->trans('ToReviewCP'),'statut1'); // Waiting approval + if ($statut == 3) return $langs->trans('ApprovedCP').' '.img_picto($langs->trans('ApprovedCP'),$pictoapproved); + if ($statut == 4) return $langs->trans('CancelCP').' '.img_picto($langs->trans('CancelCP'),'statut5'); + if ($statut == 5) return $langs->trans('RefuseCP').' '.img_picto($langs->trans('RefuseCP'),'statut5'); } return $statut; - } + } - /** - * Affiche un select HTML des statuts de congés payés - * - * @param int $selected int du statut séléctionné par défaut - * @return string affiche le select des statuts - */ - function selectStatutCP($selected='') { + /** + * Affiche un select HTML des statuts de congés payés + * + * @param int $selected int du statut séléctionné par défaut + * @return string affiche le select des statuts + */ + function selectStatutCP($selected='') { - global $langs; + global $langs; - // Liste des statuts - $name = array('DraftCP','ToReviewCP','ApprovedCP','CancelCP','RefuseCP'); - $nb = count($name)+1; + // Liste des statuts + $name = array('DraftCP','ToReviewCP','ApprovedCP','CancelCP','RefuseCP'); + $nb = count($name)+1; - // Select HTML - $statut = ''."\n"; + $statut.= ''."\n"; - // Boucle des statuts - for($i=1; $i < $nb; $i++) { - if($i==$selected) { - $statut.= ''."\n"; - } - else { - $statut.= ''."\n"; - } - } + // Boucle des statuts + for($i=1; $i < $nb; $i++) { + if($i==$selected) { + $statut.= ''."\n"; + } + else { + $statut.= ''."\n"; + } + } - $statut.= ''."\n"; - print $statut; + $statut.= ''."\n"; + print $statut; - } + } - /** - * Met à jour une option du module Holiday Payés - * - * @param string $name name du paramètre de configuration - * @param string $value vrai si mise à jour OK sinon faux - * @return boolean ok or ko - */ - function updateConfCP($name,$value) { + /** + * Met à jour une option du module Holiday Payés + * + * @param string $name name du paramètre de configuration + * @param string $value vrai si mise à jour OK sinon faux + * @return boolean ok or ko + */ + function updateConfCP($name,$value) { - $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; - $sql.= " value = '".$value."'"; - $sql.= " WHERE name = '".$name."'"; + $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; + $sql.= " value = '".$value."'"; + $sql.= " WHERE name = '".$name."'"; - dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG); - $result = $this->db->query($sql); - if($result) { - return true; - } + dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG); + $result = $this->db->query($sql); + if($result) { + return true; + } - return false; - } + return false; + } - /** - * Return value of a conf parameterfor leave module - * TODO Move this into llx_const table - * - * @param string $name Name of parameter - * @param string $createifnotfound 'stringvalue'=Create entry with string value if not found. For example 'YYYYMMDDHHMMSS'. - * @return string Value of parameter. Example: 'YYYYMMDDHHMMSS' or < 0 if error - */ - function getConfCP($name, $createifnotfound='') - { - $sql = "SELECT value"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday_config"; - $sql.= " WHERE name = '".$this->db->escape($name)."'"; + /** + * Return value of a conf parameterfor leave module + * TODO Move this into llx_const table + * + * @param string $name Name of parameter + * @param string $createifnotfound 'stringvalue'=Create entry with string value if not found. For example 'YYYYMMDDHHMMSS'. + * @return string Value of parameter. Example: 'YYYYMMDDHHMMSS' or < 0 if error + */ + function getConfCP($name, $createifnotfound='') + { + $sql = "SELECT value"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday_config"; + $sql.= " WHERE name = '".$this->db->escape($name)."'"; - dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG); - $result = $this->db->query($sql); + dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG); + $result = $this->db->query($sql); - if($result) { + if($result) { - $obj = $this->db->fetch_object($result); - // Return value - if (empty($obj)) - { - if ($createifnotfound) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)"; - $sql.= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')"; - $result = $this->db->query($sql); - if ($result) - { - return $createifnotfound; - } - else - { - $this->error=$this->db->lasterror(); - return -2; - } - } - else - { - return ''; - } - } - else - { - return $obj->value; - } - } else { + $obj = $this->db->fetch_object($result); + // Return value + if (empty($obj)) + { + if ($createifnotfound) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)"; + $sql.= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')"; + $result = $this->db->query($sql); + if ($result) + { + return $createifnotfound; + } + else + { + $this->error=$this->db->lasterror(); + return -2; + } + } + else + { + return ''; + } + } + else + { + return $obj->value; + } + } else { - // Erreur SQL - $this->error=$this->db->lasterror(); - return -1; - } - } + // Erreur SQL + $this->error=$this->db->lasterror(); + return -1; + } + } - /** - * Met à jour le timestamp de la dernière mise à jour du solde des CP - * - * @param int $userID Id of user - * @param int $nbHoliday Nb of days - * @param int $fk_type Type of vacation - * @return int 0=Nothing done, 1=OK, -1=KO - */ - function updateSoldeCP($userID='',$nbHoliday='', $fk_type='') - { - global $user, $langs; + /** + * Met à jour le timestamp de la dernière mise à jour du solde des CP + * + * @param int $userID Id of user + * @param int $nbHoliday Nb of days + * @param int $fk_type Type of vacation + * @return int 0=Nothing done, 1=OK, -1=KO + */ + function updateSoldeCP($userID='',$nbHoliday='', $fk_type='') + { + global $user, $langs; - $error = 0; + $error = 0; - if (empty($userID) && empty($nbHoliday) && empty($fk_type)) - { - $langs->load("holiday"); + if (empty($userID) && empty($nbHoliday) && empty($fk_type)) + { + $langs->load("holiday"); - // Si mise à jour pour tout le monde en début de mois + // Si mise à jour pour tout le monde en début de mois $now=dol_now(); - $month = date('m',$now); - $newdateforlastupdate = dol_print_date($now, '%Y%m%d%H%M%S'); + $month = date('m',$now); + $newdateforlastupdate = dol_print_date($now, '%Y%m%d%H%M%S'); - // Get month of last update - $lastUpdate = $this->getConfCP('lastUpdate', $newdateforlastupdate); - $monthLastUpdate = $lastUpdate[4].$lastUpdate[5]; + // Get month of last update + $lastUpdate = $this->getConfCP('lastUpdate', $newdateforlastupdate); + $monthLastUpdate = $lastUpdate[4].$lastUpdate[5]; //print 'month: '.$month.' lastUpdate:'.$lastUpdate.' monthLastUpdate:'.$monthLastUpdate;exit; - // Si la date du mois n'est pas la même que celle sauvegardée, on met à jour le timestamp - if ($month != $monthLastUpdate) - { - $this->db->begin(); + // Si la date du mois n'est pas la même que celle sauvegardée, on met à jour le timestamp + if ($month != $monthLastUpdate) + { + $this->db->begin(); - $users = $this->fetchUsers(false,false); - $nbUser = count($users); + $users = $this->fetchUsers(false,false); + $nbUser = count($users); - $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; - $sql.= " value = '".$this->db->escape($newdateforlastupdate)."'"; - $sql.= " WHERE name = 'lastUpdate'"; - $result = $this->db->query($sql); + $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; + $sql.= " value = '".$this->db->escape($newdateforlastupdate)."'"; + $sql.= " WHERE name = 'lastUpdate'"; + $result = $this->db->query($sql); $typeleaves=$this->getTypes(1,1); - foreach($typeleaves as $key => $val) - { - // On ajoute x jours à chaque utilisateurs - $nb_holiday = $val['newByMonth']; + foreach($typeleaves as $key => $val) + { + // On ajoute x jours à chaque utilisateurs + $nb_holiday = $val['newByMonth']; if (empty($nb_holiday)) $nb_holiday=0; if ($nb_holiday > 0) { dol_syslog("We update leavefor everybody for type ".$key, LOG_DEBUG); - $i = 0; - while ($i < $nbUser) - { - $now_holiday = $this->getCPforUser($users[$i]['rowid'], $val['rowid']); - $new_solde = $now_holiday + $this->getConfCP('nbHolidayEveryMonth'); + $i = 0; + while ($i < $nbUser) + { + $now_holiday = $this->getCPforUser($users[$i]['rowid'], $val['rowid']); + $new_solde = $now_holiday + $this->getConfCP('nbHolidayEveryMonth'); - // We add a log for each user - $this->addLogCP($user->id, $users[$i]['rowid'], $langs->trans('HolidaysMonthlyUpdate'), $new_solde, $val['rowid']); + // We add a log for each user + $this->addLogCP($user->id, $users[$i]['rowid'], $langs->trans('HolidaysMonthlyUpdate'), $new_solde, $val['rowid']); - $i++; - } + $i++; + } - // Now we update counter for all users at once - $sql2 = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET"; - $sql2.= " nb_holiday = nb_holiday + ".$nb_holiday; + // Now we update counter for all users at once + $sql2 = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET"; + $sql2.= " nb_holiday = nb_holiday + ".$nb_holiday; $sql2.= " WHERE fk_type = ".$val['rowid']; - $result= $this->db->query($sql2); + $result= $this->db->query($sql2); - if (! $result) - { - dol_print_error($this->db); - break; - } + if (! $result) + { + dol_print_error($this->db); + break; + } } else dol_syslog("No change for leave of type ".$key, LOG_DEBUG); - } + } if ($result) - { - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - - return 0; - } - else - { - // Mise à jour pour un utilisateur - $nbHoliday = price2num($nbHoliday,5); - - $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users"; - $sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - - if ($num > 0) - { - // Update for user - $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET"; - $sql.= " nb_holiday = ".$nbHoliday; - $sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type; - $result = $this->db->query($sql); - if (! $result) - { - $error++; - $this->errors[]=$this->db->lasterror(); - } - } - else - { - // Insert for user - $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES ("; - $sql.= $nbHoliday; - $sql.= ", '".$userID."', ".$fk_type.")"; - $result = $this->db->query($sql); - if (! $result) - { - $error++; - $this->errors[]=$this->db->lasterror(); - } - } - } - else - { - $this->errors[]=$this->db->lasterror(); - $error++; + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } } - if (! $error) - { - return 1; - } - else - { - return -1; - } - } - - } - - /** - * Retourne un checked si vrai - * - * @param string $name name du paramètre de configuration - * @return string retourne checked si > 0 - */ - function getCheckOption($name) { - - $sql = "SELECT value"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday_config"; - $sql.= " WHERE name = '".$name."'"; - - $result = $this->db->query($sql); - - if($result) { - $obj = $this->db->fetch_object($result); - - // Si la valeur est 1 on retourne checked - if($obj->value) { - return 'checked'; - } - } - } - - - /** - * Créer les entrées pour chaque utilisateur au moment de la configuration - * - * @param boolean $single Single - * @param int $userid Id user - * @return void - */ - function createCPusers($single=false,$userid='') - { - // Si c'est l'ensemble des utilisateurs à ajouter - if (! $single) - { - dol_syslog(get_class($this).'::createCPusers'); - $arrayofusers = $this->fetchUsers(false,true); - - foreach($arrayofusers as $users) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; - $sql.= " (fk_user, nb_holiday)"; - $sql.= " VALUES ('".$users['rowid']."','0')"; - - $resql=$this->db->query($sql); - if (! $resql) dol_print_error($this->db); - } - } - else + return 0; + } + else { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; - $sql.= " (fk_user, nb_holiday)"; - $sql.= " VALUES ('".$userid."','0')"; + // Mise à jour pour un utilisateur + $nbHoliday = price2num($nbHoliday,5); - $resql=$this->db->query($sql); - if (! $resql) dol_print_error($this->db); - } - } + $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users"; + $sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); - /** - * Supprime un utilisateur du module Congés Payés - * - * @param int $user_id ID de l'utilisateur à supprimer - * @return boolean Vrai si pas d'erreur, faut si Erreur - */ - function deleteCPuser($user_id) { - - $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users"; - $sql.= " WHERE fk_user = '".$user_id."'"; - - $this->db->query($sql); - - } - - - /** - * Retourne le solde de congés payés pour un utilisateur - * - * @param int $user_id ID de l'utilisateur - * @param int $fk_type Filter on type - * @return float Retourne le solde de congés payés de l'utilisateur - */ - function getCPforUser($user_id, $fk_type=0) - { - $sql = "SELECT nb_holiday"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users"; - $sql.= " WHERE fk_user = '".$user_id."'"; - if ($fk_type > 0) $sql.=" AND fk_type = ".$fk_type; - - dol_syslog(get_class($this).'::getCPforUser', LOG_DEBUG); - $result = $this->db->query($sql); - if($result) - { - $obj = $this->db->fetch_object($result); - //return number_format($obj->nb_holiday,2); - if ($obj) return $obj->nb_holiday; - else return null; - } - else - { - return null; - } - } - - /** - * Get list of Users or list of vacation balance. - * - * @param boolean $stringlist If true return a string list of id. If false, return an array - * @param boolean $type If true, read Dolibarr user list, if false, return vacation balance list. - * @param string $filters Filters - * @return array|string|int Return an array - */ - function fetchUsers($stringlist=true, $type=true, $filters='') - { - global $conf; - - dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); - - // Si vrai donc pour user Dolibarr - if ($stringlist) - { - if ($type) - { - // Si utilisateur de Dolibarr - - $sql = "SELECT u.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; - $sql.= " WHERE (ug.fk_user = u.rowid"; - $sql.= " AND ug.entity = ".$conf->entity.")"; - $sql.= " OR u.admin = 1"; - } - else - { - $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; - } - $sql.= " AND u.statut > 0"; - if ($filters) $sql.=$filters; - - $resql=$this->db->query($sql); - - // Si pas d'erreur SQL - if ($resql) { - - $i = 0; - $num = $this->db->num_rows($resql); - $stringlist = ''; - - // Boucles du listage des utilisateurs - while($i < $num) - { - $obj = $this->db->fetch_object($resql); - - if ($i == 0) { - $stringlist.= $obj->rowid; - } else { - $stringlist.= ', '.$obj->rowid; - } - - $i++; - } - // Retoune le tableau des utilisateurs - return $stringlist; - } - else - { - // Erreur SQL - $this->error="Error ".$this->db->lasterror(); - return -1; - } - - } - else - { - // We want only list of user id - $sql = "SELECT DISTINCT cpu.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE cpu.fk_user = u.user"; - if ($filters) $sql.=$filters; - - $resql=$this->db->query($sql); - - // Si pas d'erreur SQL - if ($resql) { - - $i = 0; - $num = $this->db->num_rows($resql); - $stringlist = ''; - - // Boucles du listage des utilisateurs - while($i < $num) - { - $obj = $this->db->fetch_object($resql); - - if($i == 0) { - $stringlist.= $obj->fk_user; - } else { - $stringlist.= ', '.$obj->fk_user; - } - - $i++; - } - // Retoune le tableau des utilisateurs - return $stringlist; - } - else - { - // Erreur SQL - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } - - } - else - { // Si faux donc user Congés Payés - - // List for Dolibarr users - if ($type) - { - $sql = "SELECT u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - - if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; - $sql.= " WHERE (ug.fk_user = u.rowid"; - $sql.= " AND ug.entity = ".$conf->entity.")"; - $sql.= " OR u.admin = 1"; - } - else - $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; - - $sql.= " AND u.statut > 0"; - if ($filters) $sql.=$filters; - - $resql=$this->db->query($sql); - - // Si pas d'erreur SQL - if ($resql) - { - $i = 0; - $tab_result = $this->holiday; - $num = $this->db->num_rows($resql); - - // Boucles du listage des utilisateurs - while($i < $num) { - - $obj = $this->db->fetch_object($resql); - - $tab_result[$i]['rowid'] = $obj->rowid; - $tab_result[$i]['name'] = $obj->lastname; // deprecated - $tab_result[$i]['lastname'] = $obj->lastname; - $tab_result[$i]['firstname'] = $obj->firstname; - $tab_result[$i]['gender'] = $obj->gender; - $tab_result[$i]['status'] = $obj->statut; - $tab_result[$i]['employee'] = $obj->employee; - $tab_result[$i]['photo'] = $obj->photo; - //$tab_result[$i]['type'] = $obj->type; - //$tab_result[$i]['nb_holiday'] = $obj->nb_holiday; - - $i++; - } - // Retoune le tableau des utilisateurs - return $tab_result; - } - else + if ($num > 0) { - // Erreur SQL - $this->errors[]="Error ".$this->db->lasterror(); - return -1; - } - } - else - { + // Update for user + $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET"; + $sql.= " nb_holiday = ".$nbHoliday; + $sql.= " WHERE fk_user = '".$userID."' AND fk_type = ".$fk_type; + $result = $this->db->query($sql); + if (! $result) + { + $error++; + $this->errors[]=$this->db->lasterror(); + } + } + else + { + // Insert for user + $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES ("; + $sql.= $nbHoliday; + $sql.= ", '".$userID."', ".$fk_type.")"; + $result = $this->db->query($sql); + if (! $result) + { + $error++; + $this->errors[]=$this->db->lasterror(); + } + } + } + else + { + $this->errors[]=$this->db->lasterror(); + $error++; + } + + if (! $error) + { + return 1; + } + else + { + return -1; + } + } + + } + + /** + * Retourne un checked si vrai + * + * @param string $name name du paramètre de configuration + * @return string retourne checked si > 0 + */ + function getCheckOption($name) { + + $sql = "SELECT value"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday_config"; + $sql.= " WHERE name = '".$name."'"; + + $result = $this->db->query($sql); + + if($result) { + $obj = $this->db->fetch_object($result); + + // Si la valeur est 1 on retourne checked + if($obj->value) { + return 'checked'; + } + } + } + + + /** + * Créer les entrées pour chaque utilisateur au moment de la configuration + * + * @param boolean $single Single + * @param int $userid Id user + * @return void + */ + function createCPusers($single=false,$userid='') + { + // Si c'est l'ensemble des utilisateurs à ajouter + if (! $single) + { + dol_syslog(get_class($this).'::createCPusers'); + $arrayofusers = $this->fetchUsers(false,true); + + foreach($arrayofusers as $users) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; + $sql.= " (fk_user, nb_holiday)"; + $sql.= " VALUES ('".$users['rowid']."','0')"; + + $resql=$this->db->query($sql); + if (! $resql) dol_print_error($this->db); + } + } + else + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users"; + $sql.= " (fk_user, nb_holiday)"; + $sql.= " VALUES ('".$userid."','0')"; + + $resql=$this->db->query($sql); + if (! $resql) dol_print_error($this->db); + } + } + + /** + * Supprime un utilisateur du module Congés Payés + * + * @param int $user_id ID de l'utilisateur à supprimer + * @return boolean Vrai si pas d'erreur, faut si Erreur + */ + function deleteCPuser($user_id) { + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users"; + $sql.= " WHERE fk_user = '".$user_id."'"; + + $this->db->query($sql); + + } + + + /** + * Retourne le solde de congés payés pour un utilisateur + * + * @param int $user_id ID de l'utilisateur + * @param int $fk_type Filter on type + * @return float Retourne le solde de congés payés de l'utilisateur + */ + function getCPforUser($user_id, $fk_type=0) + { + $sql = "SELECT nb_holiday"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users"; + $sql.= " WHERE fk_user = '".$user_id."'"; + if ($fk_type > 0) $sql.=" AND fk_type = ".$fk_type; + + dol_syslog(get_class($this).'::getCPforUser', LOG_DEBUG); + $result = $this->db->query($sql); + if($result) + { + $obj = $this->db->fetch_object($result); + //return number_format($obj->nb_holiday,2); + if ($obj) return $obj->nb_holiday; + else return null; + } + else + { + return null; + } + } + + /** + * Get list of Users or list of vacation balance. + * + * @param boolean $stringlist If true return a string list of id. If false, return an array with detail. + * @param boolean $type If true, read Dolibarr user list, if false, return vacation balance list. + * @param string $filters Filters + * @return array|string|int Return an array + */ + function fetchUsers($stringlist=true, $type=true, $filters='') + { + global $conf; + + dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); + + if ($stringlist) + { + if ($type) + { + // Si utilisateur de Dolibarr + + $sql = "SELECT u.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + + if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql.= " WHERE (ug.fk_user = u.rowid"; + $sql.= " AND ug.entity = ".$conf->entity.")"; + $sql.= " OR u.admin = 1"; + } + else + { + $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; + } + $sql.= " AND u.statut > 0"; + if ($filters) $sql.=$filters; + + $resql=$this->db->query($sql); + + // Si pas d'erreur SQL + if ($resql) { + + $i = 0; + $num = $this->db->num_rows($resql); + $stringlist = ''; + + // Boucles du listage des utilisateurs + while($i < $num) + { + $obj = $this->db->fetch_object($resql); + + if ($i == 0) { + $stringlist.= $obj->rowid; + } else { + $stringlist.= ', '.$obj->rowid; + } + + $i++; + } + // Retoune le tableau des utilisateurs + return $stringlist; + } + else + { + // Erreur SQL + $this->error="Error ".$this->db->lasterror(); + return -1; + } + + } + else + { + // We want only list of vacation balance for user ids + $sql = "SELECT DISTINCT cpu.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE cpu.fk_user = u.user"; + if ($filters) $sql.=$filters; + + $resql=$this->db->query($sql); + + // Si pas d'erreur SQL + if ($resql) { + + $i = 0; + $num = $this->db->num_rows($resql); + $stringlist = ''; + + // Boucles du listage des utilisateurs + while($i < $num) + { + $obj = $this->db->fetch_object($resql); + + if($i == 0) { + $stringlist.= $obj->fk_user; + } else { + $stringlist.= ', '.$obj->fk_user; + } + + $i++; + } + // Retoune le tableau des utilisateurs + return $stringlist; + } + else + { + // Erreur SQL + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + + } + else + { // Si faux donc return array + + // List for Dolibarr users + if ($type) + { + $sql = "SELECT u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + + if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug"; + $sql.= " WHERE (ug.fk_user = u.rowid"; + $sql.= " AND ug.entity = ".$conf->entity.")"; + $sql.= " OR u.admin = 1"; + } + else + $sql.= " WHERE u.entity IN (0,".$conf->entity.")"; + + $sql.= " AND u.statut > 0"; + if ($filters) $sql.=$filters; + + $resql=$this->db->query($sql); + + // Si pas d'erreur SQL + if ($resql) + { + $i = 0; + $tab_result = $this->holiday; + $num = $this->db->num_rows($resql); + + // Boucles du listage des utilisateurs + while($i < $num) { + + $obj = $this->db->fetch_object($resql); + + $tab_result[$i]['rowid'] = $obj->rowid; + $tab_result[$i]['name'] = $obj->lastname; // deprecated + $tab_result[$i]['lastname'] = $obj->lastname; + $tab_result[$i]['firstname'] = $obj->firstname; + $tab_result[$i]['gender'] = $obj->gender; + $tab_result[$i]['status'] = $obj->statut; + $tab_result[$i]['employee'] = $obj->employee; + $tab_result[$i]['photo'] = $obj->photo; + $tab_result[$i]['fk_user'] = $obj->fk_user; + //$tab_result[$i]['type'] = $obj->type; + //$tab_result[$i]['nb_holiday'] = $obj->nb_holiday; + + $i++; + } + // Retoune le tableau des utilisateurs + return $tab_result; + } + else + { + // Erreur SQL + $this->errors[]="Error ".$this->db->lasterror(); + return -1; + } + } + else + { // List of vacation balance users - $sql = "SELECT cpu.fk_user, cpu.fk_type, cpu.nb_holiday, u.lastname, u.firstname"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE cpu.fk_user = u.rowid"; - if ($filters) $sql.=$filters; + $sql = "SELECT cpu.fk_user, cpu.fk_type, cpu.nb_holiday, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE cpu.fk_user = u.rowid"; + if ($filters) $sql.=$filters; - $resql=$this->db->query($sql); + $resql=$this->db->query($sql); - // Si pas d'erreur SQL - if ($resql) - { - $i = 0; - $tab_result = $this->holiday; - $num = $this->db->num_rows($resql); - - // Boucles du listage des utilisateurs - while($i < $num) - { - $obj = $this->db->fetch_object($resql); - - $tab_result[$i]['rowid'] = $obj->fk_user; - $tab_result[$i]['name'] = $obj->lastname; - $tab_result[$i]['lastname'] = $obj->lastname; - $tab_result[$i]['firstname'] = $obj->firstname; - $tab_result[$i]['type'] = $obj->type; - $tab_result[$i]['nb_holiday'] = $obj->nb_holiday; - - $i++; - } - // Retoune le tableau des utilisateurs - return $tab_result; - } - else + // Si pas d'erreur SQL + if ($resql) { - // Erreur SQL - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } - } - } + $i = 0; + $tab_result = $this->holiday; + $num = $this->db->num_rows($resql); - /** - * Compte le nombre d'utilisateur actifs dans Dolibarr - * - * @return int retourne le nombre d'utilisateur - */ - function countActiveUsers() - { - $sql = "SELECT count(u.rowid) as compteur"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + // Boucles du listage des utilisateurs + while($i < $num) + { + $obj = $this->db->fetch_object($resql); + + $tab_result[$i]['rowid'] = $obj->fk_user; + $tab_result[$i]['name'] = $obj->lastname; // deprecated + $tab_result[$i]['lastname'] = $obj->lastname; + $tab_result[$i]['firstname'] = $obj->firstname; + $tab_result[$i]['gender'] = $obj->gender; + $tab_result[$i]['status'] = $obj->statut; + $tab_result[$i]['employee'] = $obj->employee; + $tab_result[$i]['photo'] = $obj->photo; + $tab_result[$i]['fk_user'] = $obj->fk_user; + + $tab_result[$i]['type'] = $obj->type; + $tab_result[$i]['nb_holiday'] = $obj->nb_holiday; + + $i++; + } + // Retoune le tableau des utilisateurs + return $tab_result; + } + else + { + // Erreur SQL + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + } + } + + /** + * Compte le nombre d'utilisateur actifs dans Dolibarr + * + * @return int retourne le nombre d'utilisateur + */ + function countActiveUsers() + { + $sql = "SELECT count(u.rowid) as compteur"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE u.statut > 0"; - $result = $this->db->query($sql); - $objet = $this->db->fetch_object($result); + $result = $this->db->query($sql); + $objet = $this->db->fetch_object($result); - return $objet->compteur; - } - /** - * Compte le nombre d'utilisateur actifs dans Dolibarr sans CP - * - * @return int retourne le nombre d'utilisateur - */ - function countActiveUsersWithoutCP() { + return $objet->compteur; + } + /** + * Compte le nombre d'utilisateur actifs dans Dolibarr sans CP + * + * @return int retourne le nombre d'utilisateur + */ + function countActiveUsersWithoutCP() { - $sql = "SELECT count(u.rowid) as compteur"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)"; + $sql = "SELECT count(u.rowid) as compteur"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)"; $sql.= " WHERE u.statut > 0 AND hu.fk_user IS NULL"; - $result = $this->db->query($sql); - $objet = $this->db->fetch_object($result); + $result = $this->db->query($sql); + $objet = $this->db->fetch_object($result); - return $objet->compteur; - } + return $objet->compteur; + } - /** - * Compare le nombre d'utilisateur actif de Dolibarr à celui des utilisateurs des congés payés - * - * @param int $userDolibarrWithoutCP Number of active users in Dolibarr without holidays - * @param int $userCP Number of active users into table of holidays - * @return int <0 if KO, >0 if OK - */ - function verifNbUsers($userDolibarrWithoutCP, $userCP) - { - if (empty($userCP)) $userCP=0; - dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP); - return 1; - } + /** + * Compare le nombre d'utilisateur actif de Dolibarr à celui des utilisateurs des congés payés + * + * @param int $userDolibarrWithoutCP Number of active users in Dolibarr without holidays + * @param int $userCP Number of active users into table of holidays + * @return int <0 if KO, >0 if OK + */ + function verifNbUsers($userDolibarrWithoutCP, $userCP) + { + if (empty($userCP)) $userCP=0; + dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP); + return 1; + } - /** - * addLogCP - * - * @param int $fk_user_action Id user creation - * @param int $fk_user_update Id user update - * @param string $label Label - * @param int $new_solde New value - * @param int $fk_type Type of vacation - * @return int Id of record added, 0 if nothing done, < 0 if KO - */ - function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type) - { - global $conf, $langs; + /** + * addLogCP + * + * @param int $fk_user_action Id user creation + * @param int $fk_user_update Id user update + * @param string $label Label + * @param int $new_solde New value + * @param int $fk_type Type of vacation + * @return int Id of record added, 0 if nothing done, < 0 if KO + */ + function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type) + { + global $conf, $langs; - $error=0; + $error=0; - $prev_solde = price2num($this->getCPforUser($fk_user_update, $fk_type), 5); - $new_solde = price2num($new_solde, 5); + $prev_solde = price2num($this->getCPforUser($fk_user_update, $fk_type), 5); + $new_solde = price2num($new_solde, 5); //print "$prev_solde == $new_solde"; - if ($prev_solde == $new_solde) return 0; + if ($prev_solde == $new_solde) return 0; $this->db->begin(); // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs ("; - $sql.= "date_action,"; - $sql.= "fk_user_action,"; - $sql.= "fk_user_update,"; - $sql.= "type_action,"; - $sql.= "prev_solde,"; - $sql.= "new_solde,"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs ("; + $sql.= "date_action,"; + $sql.= "fk_user_action,"; + $sql.= "fk_user_update,"; + $sql.= "type_action,"; + $sql.= "prev_solde,"; + $sql.= "new_solde,"; $sql.= "fk_type"; - $sql.= ") VALUES ("; - $sql.= " '".$this->db->idate(dol_now())."',"; - $sql.= " '".$fk_user_action."',"; - $sql.= " '".$fk_user_update."',"; - $sql.= " '".$this->db->escape($label)."',"; - $sql.= " '".$prev_solde."',"; - $sql.= " '".$new_solde."',"; - $sql.= " ".$fk_type; - $sql.= ")"; + $sql.= ") VALUES ("; + $sql.= " '".$this->db->idate(dol_now())."',"; + $sql.= " '".$fk_user_action."',"; + $sql.= " '".$fk_user_update."',"; + $sql.= " '".$this->db->escape($label)."',"; + $sql.= " '".$prev_solde."',"; + $sql.= " '".$new_solde."',"; + $sql.= " ".$fk_type; + $sql.= ")"; - $resql=$this->db->query($sql); - if (! $resql) - { - $error++; $this->errors[]="Error ".$this->db->lasterror(); - } + $resql=$this->db->query($sql); + if (! $resql) + { + $error++; $this->errors[]="Error ".$this->db->lasterror(); + } - if (! $error) - { - $this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs"); - } + if (! $error) + { + $this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs"); + } - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return $this->optRowid; - } - } + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return $this->optRowid; + } + } - /** - * Liste le log des congés payés - * - * @param string $order Filtrage par ordre - * @param string $filter Filtre de séléction - * @return int -1 si erreur, 1 si OK et 2 si pas de résultat - */ - function fetchLog($order,$filter) - { - global $langs; + /** + * Liste le log des congés payés + * + * @param string $order Filtrage par ordre + * @param string $filter Filtre de séléction + * @return int -1 si erreur, 1 si OK et 2 si pas de résultat + */ + function fetchLog($order,$filter) + { + global $langs; - $sql = "SELECT"; - $sql.= " cpl.rowid,"; - $sql.= " cpl.date_action,"; - $sql.= " cpl.fk_user_action,"; - $sql.= " cpl.fk_user_update,"; - $sql.= " cpl.type_action,"; - $sql.= " cpl.prev_solde,"; - $sql.= " cpl.new_solde,"; + $sql = "SELECT"; + $sql.= " cpl.rowid,"; + $sql.= " cpl.date_action,"; + $sql.= " cpl.fk_user_action,"; + $sql.= " cpl.fk_user_update,"; + $sql.= " cpl.type_action,"; + $sql.= " cpl.prev_solde,"; + $sql.= " cpl.new_solde,"; $sql.= " cpl.fk_type"; - $sql.= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl"; - $sql.= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria + $sql.= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl"; + $sql.= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria - // Filtrage de séléction - if(!empty($filter)) { - $sql.= " ".$filter; - } + // Filtrage de séléction + if(!empty($filter)) { + $sql.= " ".$filter; + } - // Ordre d'affichage - if(!empty($order)) { - $sql.= " ".$order; - } + // Ordre d'affichage + if(!empty($order)) { + $sql.= " ".$order; + } - dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG); - $resql=$this->db->query($sql); + dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG); + $resql=$this->db->query($sql); - // Si pas d'erreur SQL + // Si pas d'erreur SQL if ($resql) { - $i = 0; - $tab_result = $this->logs; - $num = $this->db->num_rows($resql); + $i = 0; + $tab_result = $this->logs; + $num = $this->db->num_rows($resql); - // Si pas d'enregistrement - if(!$num) { - return 2; - } + // Si pas d'enregistrement + if(!$num) { + return 2; + } - // On liste les résultats et on les ajoutent dans le tableau - while($i < $num) { + // On liste les résultats et on les ajoutent dans le tableau + while($i < $num) { - $obj = $this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); - $tab_result[$i]['rowid'] = $obj->rowid; - $tab_result[$i]['date_action'] = $obj->date_action; - $tab_result[$i]['fk_user_action'] = $obj->fk_user_action; - $tab_result[$i]['fk_user_update'] = $obj->fk_user_update; - $tab_result[$i]['type_action'] = $obj->type_action; - $tab_result[$i]['prev_solde'] = $obj->prev_solde; - $tab_result[$i]['new_solde'] = $obj->new_solde; - $tab_result[$i]['fk_type'] = $obj->fk_type; + $tab_result[$i]['rowid'] = $obj->rowid; + $tab_result[$i]['date_action'] = $obj->date_action; + $tab_result[$i]['fk_user_action'] = $obj->fk_user_action; + $tab_result[$i]['fk_user_update'] = $obj->fk_user_update; + $tab_result[$i]['type_action'] = $obj->type_action; + $tab_result[$i]['prev_solde'] = $obj->prev_solde; + $tab_result[$i]['new_solde'] = $obj->new_solde; + $tab_result[$i]['fk_type'] = $obj->fk_type; - $i++; - } - // Retourne 1 et ajoute le tableau à la variable - $this->logs = $tab_result; - return 1; + $i++; + } + // Retourne 1 et ajoute le tableau à la variable + $this->logs = $tab_result; + return 1; } else { - // Erreur SQL - $this->error="Error ".$this->db->lasterror(); - return -1; + // Erreur SQL + $this->error="Error ".$this->db->lasterror(); + return -1; } - } + } - /** - * Return array with list of types - * - * @param int $active Status of type. -1 = Both - * @param int $affect Filter on affect (a request will change sold or not). -1 = Both - * @return array Return array with list of types - */ - function getTypes($active=-1, $affect=-1) - { - global $mysoc; + /** + * Return array with list of types + * + * @param int $active Status of type. -1 = Both + * @param int $affect Filter on affect (a request will change sold or not). -1 = Both + * @return array Return array with list of types + */ + function getTypes($active=-1, $affect=-1) + { + global $mysoc; - $sql = "SELECT rowid, code, label, affect, delay, newByMonth"; - $sql.= " FROM " . MAIN_DB_PREFIX . "c_holiday_types"; - $sql.= " WHERE (fk_country IS NULL OR fk_country = ".$mysoc->country_id.')'; - if ($active >= 0) $sql.=" AND active = ".((int) $active); - if ($affect >= 0) $sql.=" AND affect = ".((int) $affect); + $sql = "SELECT rowid, code, label, affect, delay, newByMonth"; + $sql.= " FROM " . MAIN_DB_PREFIX . "c_holiday_types"; + $sql.= " WHERE (fk_country IS NULL OR fk_country = ".$mysoc->country_id.')'; + if ($active >= 0) $sql.=" AND active = ".((int) $active); + if ($affect >= 0) $sql.=" AND affect = ".((int) $affect); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - if ($num) - { - while ($obj = $this->db->fetch_object($result)) - { - $types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newByMonth'=>$obj->newByMonth); - } + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); + if ($num) + { + while ($obj = $this->db->fetch_object($result)) + { + $types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newByMonth'=>$obj->newByMonth); + } - return $types; - } - } - else dol_print_error($this->db); + return $types; + } + } + else dol_print_error($this->db); - return array(); - } + return array(); + } - /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void - */ - function initAsSpecimen() - { - global $user,$langs; + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + global $user,$langs; - // Initialise parameters - $this->id=0; - $this->specimen=1; + // Initialise parameters + $this->id=0; + $this->specimen=1; - $this->fk_user=1; - $this->description='SPECIMEN description'; - $this->date_debut=dol_now(); - $this->date_fin=dol_now()+(24*3600); - $this->fk_validator=1; - $this->halfday=0; - $this->fk_type=1; - } + $this->fk_user=1; + $this->description='SPECIMEN description'; + $this->date_debut=dol_now(); + $this->date_fin=dol_now()+(24*3600); + $this->fk_validator=1; + $this->halfday=0; + $this->fk_type=1; + } } diff --git a/htdocs/holiday/define_holiday.php b/htdocs/holiday/define_holiday.php index de8a7147267..b4440700be7 100644 --- a/htdocs/holiday/define_holiday.php +++ b/htdocs/holiday/define_holiday.php @@ -36,6 +36,7 @@ $langs->load('hrm'); $action=GETPOST('action','aZ09'); $search_name=GETPOST('search_name', 'alpha'); +$search_supervisor=GETPOST('search_supervisor', 'int'); // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; @@ -54,7 +55,7 @@ if (! $sortorder) $sortorder="ASC"; if ($user->societe_id > 0) accessforbidden(); // If the user does not have perm to read the page -if(!$user->rights->holiday->read) accessforbidden(); +if (!$user->rights->holiday->read) accessforbidden(); // Initialize technical object to manage context to save list fields @@ -87,6 +88,7 @@ if (empty($reshook)) if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { $search_name=''; + $search_supervisor=''; $toselect=''; $search_array_options=array(); } @@ -202,9 +204,20 @@ if ($result < 0) setEventMessages($holiday->error, $holiday->errors, 'errors'); } -$filters=natural_search(array('u.firstname','u.lastname'), $search_name); +$filters = ''; -$listUsers = $holiday->fetchUsers(false,true,$filters); +// Filter on array of ids of all childs +$userchilds=array(); +if (empty($user->rights->holiday->read_all)) +{ + $userchilds=$user->getAllChildIds(1); + $filters.=' AND u.rowid IN ('.join(', ',$userchilds).')'; +} + +$filters.=natural_search(array('u.firstname','u.lastname'), $search_name); +if ($search_supervisor > 0) $filters.=natural_search(array('u.fk_user'), $search_supervisor, 2); + +$listUsers = $holiday->fetchUsers(false, true, $filters); if (is_numeric($listUsers) && $listUsers < 0) { setEventMessages($holiday->error, $holiday->errors, 'errors'); @@ -227,13 +240,6 @@ else $canedit=0; if (! empty($user->rights->holiday->define_holiday)) $canedit=1; - // Get array of ids of all childs - $userchilds=array(); - if (empty($user->rights->holiday->read_all)) - { - $userchilds=$user->getAllChildIds(); - } - print ''; $moreforfilter=''; @@ -242,7 +248,16 @@ else print ''."\n"; print ''; + + // User print ''; + + // Supervisor + print ''; + + // Type of leave request if (count($typeleaves)) { foreach($typeleaves as $key => $val) @@ -266,23 +281,23 @@ else print ''; print_liste_field_titre('Employee', $_SERVER["PHP_SELF"]); + print_liste_field_titre('Supervisor', $_SERVER["PHP_SELF"]); if (count($typeleaves)) { foreach($typeleaves as $key => $val) { - print ''; + print_liste_field_titre($val['label'], $_SERVER["PHP_SELF"], '', '', '', 'align="center"'); } } else { - print ''; + print_liste_field_titre('NoLeaveWithCounterDefined', $_SERVER["PHP_SELF"], '', '', '', ''); } - print ''; + print_liste_field_titre((empty($user->rights->holiday->define_holiday) ? '' : 'Note'), $_SERVER["PHP_SELF"]); print_liste_field_titre(''); print ''; + $usersupervisor = new User($db); foreach($listUsers as $users) { @@ -292,10 +307,6 @@ else if (($users['rowid'] != $user->id) && (! in_array($users['rowid'], $userchilds))) continue; // This user is not into hierarchy of current user, we hide it. } - print ''; - - // User - print ''; + + // User + print ''; + // Supervisor + print ''; + // Amount for each type if (count($typeleaves)) { @@ -313,6 +337,8 @@ else { $nbtoshow=''; if ($holiday->getCPforUser($users['rowid'], $val['rowid']) != '') $nbtoshow=price2num($holiday->getCPforUser($users['rowid'], $val['rowid']), 5); + + //var_dump($users['rowid'].' - '.$val['rowid']); print ''; print '
    '; + print $form->select_dolusers($search_supervisor, 'search_supervisor', 1, null, 0, null, null, 0, 0, 0, '', 0, '', 'maxwidth200'); + print '
    '.$val['label'].''.$langs->trans("NoLeaveWithCounterDefined").''; - if ($canedit) print $langs->trans('Note'); - print '
    '; $userstatic->id=$users['rowid']; $userstatic->lastname=$users['lastname']; $userstatic->firstname=$users['firstname']; @@ -303,9 +314,22 @@ else $userstatic->photo=$users['photo']; $userstatic->statut=$users['status']; $userstatic->employee=$users['employee']; + $userstatic->fk_user=$users['fk_user']; + + if ($userstatic->fk_user > 0) $usersupervisor->fetch($userstatic->fk_user); + + print '
    '; print $userstatic->getNomUrl(-1); print ''; + if ($userstatic->fk_user > 0) print $usersupervisor->getNomUrl(-1); + print ''; if ($canedit) print ''; else print $nbtoshow; @@ -326,7 +352,7 @@ else } // Note - print ''; + print ''; if ($canedit) print ''; print ''; diff --git a/htdocs/holiday/document.php b/htdocs/holiday/document.php index 38f68e58937..94d32b3bc49 100644 --- a/htdocs/holiday/document.php +++ b/htdocs/holiday/document.php @@ -97,7 +97,7 @@ if ($object->id) $head=holiday_prepare_head($object); - dol_fiche_head($head, 'documents',$langs->trans("CPTitreMenu"),0,'holiday'); + dol_fiche_head($head, 'documents', $langs->trans("CPTitreMenu"), -1,'holiday'); // Construit liste des fichiers @@ -109,17 +109,17 @@ if ($object->id) } - $linkback=''.$langs->trans("BackToList").''; - + $linkback=''.$langs->trans("BackToList").''; + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref'); - - + + print '
    '; //print '
    '; print '
    '; - + print ''; - + print ''; print ''; print ''; print ''; - + print ''; print '
    '.$langs->trans("User").''; @@ -212,16 +212,16 @@ if ($object->id) print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '."\n"; /* print '
    '; print '
    '; print '
    '; - + print '
    '; - + // Info workflow print ''."\n"; print ''; @@ -278,11 +278,11 @@ if ($object->id) print ''; print ''; */ print ''; - + print '
    '; - + dol_fiche_end(); - + $modulepart = 'holiday'; diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index b041861b9d4..f25dcb9e227 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -33,26 +33,44 @@ require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; -$langs->load('users'); -$langs->load('holidays'); -$langs->load('hrm'); +$langs->loadLangs(array('users', 'holidays', 'hrm')); // Protection if external user if ($user->societe_id > 0) accessforbidden(); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -$page = is_numeric($page) ? $page : 0; -$page = $page == -1 ? 0 : $page; +$action = GETPOST('action','alpha'); // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction','alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files','int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'myobjectlist'; // To manage different context of search +$backtopage = GETPOST('backtopage','alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss','aZ'); // Option for the css output (always '' except when 'print') -if (! $sortfield) $sortfield="cp.rowid"; -if (! $sortorder) $sortorder="DESC"; +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; +// Initialize technical objects +$object=new Holiday($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->holiday->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('holidaylist')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('holiday'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (! $sortfield) $sortfield="cp.rowid"; +if (! $sortorder) $sortorder="DESC"; + $id = GETPOST('id','int'); $sall = GETPOST('sall', 'alphanohtml'); @@ -81,27 +99,60 @@ $fieldstosearchall = array( * Actions */ -if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) { - $search_ref=""; - $month_create=""; - $year_create=""; - $month_start=""; - $year_start=""; - $month_end=""; - $year_end=""; - $search_employee=""; - $search_valideur=""; - $search_statut=""; - $search_type=''; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + $search_ref=""; + $month_create=""; + $year_create=""; + $month_start=""; + $year_start=""; + $month_end=""; + $year_end=""; + $search_employee=""; + $search_valideur=""; + $search_statut=""; + $search_type=''; + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='Holiday'; + $objectlabel='Holiday'; + $permtoread = $user->rights->holiday->read; + $permtodelete = $user->rights->holiday->delete; + $uploaddir = $conf->holiday->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } + /* * View */ +$form = new Form($db); +$formother = new FormOther($db); + $holiday = new Holiday($db); $holidaystatic=new Holiday($db); $fuser = new User($db); @@ -231,32 +282,41 @@ if ($result == '-1') // Show table of vacations -$var=true; $num = count($holiday->holiday); -$form = new Form($db); -$formother = new FormOther($db); + +$arrayofselected=is_array($toselect)?$toselect:array(); $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($optioncss != '') $param.='&optioncss='.$optioncss; -print ''."\n"; +// List of mass actions available +$arrayofmassactions = array( +//'presend'=>$langs->trans("SendByMail"), +//'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->holiday->delete) $arrayofmassactions['delete']=$langs->trans("Delete"); +//if ($massaction == 'presend') $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + +print ''; if ($optioncss != '') print ''; print ''; print ''; print ''; print ''; print ''; +print ''; if ($id > 0) print ''; -if ($id > 0) +if ($id > 0) // For user tab { $title = $langs->trans("User"); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $head = user_prepare_head($fuser); - dol_fiche_head($head, 'paidholidays', $title, 0, 'user'); + dol_fiche_head($head, 'paidholidays', $title, -1, 'user'); dol_banner_tab($fuser,'id',$linkback,$user->rights->user->user->lire || $user->admin); @@ -270,61 +330,46 @@ if ($id > 0) } dol_fiche_end(); + + print '
    '; + + $canedit=(($user->id == $user_id && $user->rights->holiday->write) || ($user->id != $user_id && $user->rights->holiday->write_all)); + + // Boutons d'actions + if ($canedit) + { + print ''.$langs->trans("AddCP").''; + } + + print '
    '; } else { - //print $num; + $nbtotalofrecords = count($holiday->holiday); + //print $num; //print count($holiday->holiday); - print_barre_liste($langs->trans("ListeCP"), $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, "", $num, count($holiday->holiday), 'title_hrm.png', 0, '', '', $limit); + print_barre_liste($langs->trans("ListeCP"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_hrm.png', 0, '', '', $limit); - if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) + /*if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) { - dol_fiche_head(''); + dol_fiche_head('', '', '', -1); showMyBalance($holiday, $user_id); dol_fiche_end(); - } + }*/ } - - -/** - * Show balance of user - * - * @param Holiday $holiday Object $holiday - * @param int $user_id User id - * @return string Html code with balance - */ -function showMyBalance($holiday, $user_id) -{ - global $conf, $langs; - - $alltypeleaves=$holiday->getTypes(1,-1); // To have labels - - $out=''; - $nb_holiday=0; - $typeleaves=$holiday->getTypes(1,1); - foreach($typeleaves as $key => $val) - { - $nb_type = $holiday->getCPforUser($user_id, $val['rowid']); - $nb_holiday += $nb_type; - $out .= ' - '.$val['label'].': '.($nb_type?price2num($nb_type):0).'
    '; - } - print $langs->trans('SoldeCPUser', round($nb_holiday,5)).'
    '; - print $out; -} - - - -if ($id > 0) print '
    '; - if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); } +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=''; // $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + print '
    '; print '
    '."\n"; @@ -383,7 +428,7 @@ foreach($typeleaves as $key => $val) //$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':''); $arraytypeleaves[$val['rowid']]=$labeltoshow; } -print $form->selectarray('search_type', $arraytypeleaves, (GETPOST('search_type')?GETPOST('search_type'):''), 1); +print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1); print ''; // Duration @@ -424,7 +469,7 @@ print_liste_field_titre("Duration",$_SERVER["PHP_SELF"],'','',$pram,'align="righ print_liste_field_titre("DateDebCP",$_SERVER["PHP_SELF"],"cp.date_debut","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("DateFinCP",$_SERVER["PHP_SELF"],"cp.date_fin","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"cp.statut","",$param,'align="right"',$sortfield,$sortorder); -print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'',$param,'',$sortfield,$sortorder,'maxwidthsearch '); +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; print "\n"; // Lines @@ -433,6 +478,8 @@ if (! empty($holiday->holiday)) $userstatic = new User($db); $approbatorstatic = new User($db); + $typeleaves=$holiday->getTypes(1,-1); + foreach($holiday->holiday as $infos_CP) { // User @@ -463,8 +510,7 @@ if (! empty($holiday->holiday)) print ''; print ''; print ''; print ''; print ''; print ''; - print ''; + + // Action column + print ''; + print ''."\n"; } @@ -503,3 +559,33 @@ print ''; llxFooter(); $db->close(); + + + + + +/** + * Show balance of user + * + * @param Holiday $holiday Object $holiday + * @param int $user_id User id + * @return string Html code with balance + */ +function showMyBalance($holiday, $user_id) +{ + global $conf, $langs; + + $alltypeleaves=$holiday->getTypes(1,-1); // To have labels + + $out=''; + $nb_holiday=0; + $typeleaves=$holiday->getTypes(1,1); + foreach($typeleaves as $key => $val) + { + $nb_type = $holiday->getCPforUser($user_id, $val['rowid']); + $nb_holiday += $nb_type; + $out .= ' - '.$val['label'].': '.($nb_type?price2num($nb_type):0).'
    '; + } + print $langs->trans('SoldeCPUser', round($nb_holiday,5)).'
    '; + print $out; +} diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index 82ecad62417..0847f1c4262 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -77,7 +77,7 @@ $hexa = GETPOST('hexa'); $importmodelid = GETPOST('importmodelid'); $excludefirstline = (GETPOST('excludefirstline') ? GETPOST('excludefirstline') : 1); $endatlinenb = (GETPOST('endatlinenb') ? GETPOST('endatlinenb') : ''); -$updatekeys = (GETPOST('updatekeys') ? GETPOST('updatekeys') : array()); +$updatekeys = (GETPOST('updatekeys', 'array') ? GETPOST('updatekeys', 'array') : array()); $separator = (GETPOST('separator') ? GETPOST('separator') : (! empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE)?$conf->global->IMPORT_CSV_SEPARATOR_TO_USE:',')); $enclosure = (GETPOST('enclosure') ? GETPOST('enclosure') : '"'); diff --git a/htdocs/includes/odtphp/odf.php b/htdocs/includes/odtphp/odf.php index 01633634705..19fd3390937 100644 --- a/htdocs/includes/odtphp/odf.php +++ b/htdocs/includes/odtphp/odf.php @@ -36,14 +36,14 @@ class Odf protected $images = array(); protected $vars = array(); protected $segments = array(); - + public $creator; public $title; public $subject; public $userdefined=array(); - + const PIXEL_TO_CM = 0.026458333; - + /** * Class constructor * @@ -113,7 +113,7 @@ class Odf copy($filename, $this->tmpfile); - // Now file has been loaded, we must move the [!-- BEGIN and [!-- END tags outside the + // Now file has been loaded, we must move the [!-- BEGIN and [!-- END tags outside the // _moveRowSegments(); } @@ -124,7 +124,7 @@ class Odf * @param string $key Name of the variable within the template * @param string $value Replacement value * @param bool $encode If true, special XML characters are encoded - * @param string $charset Charset + * @param string $charset Charset * @throws OdfException * @return odf */ @@ -211,7 +211,7 @@ class Odf { preg_match_all('/[\{\<]\?(php)?\s+(?P.+)\?[\}\>]/iU',$this->contentXml, $matches); // detecting all {?php code ?} or $nbfound=count($matches['content']); - for ($i=0; $i < $nbfound; $i++) + for ($i=0; $i < $nbfound; $i++) { try { $ob_output = ''; // flush the output for each code. This var will be filled in by the eval($code) and output buffering : any print or echo or output will be redirected into this variable @@ -268,7 +268,7 @@ IMG; $this->contentXml = preg_replace('/\[!--\sBEGIN]>(row.[\S]*)\s--\]/sm', '[!-- BEGIN \\1 --]', $this->contentXml); // Replace ENDxxx into END xxx $this->contentXml = preg_replace('/\[!--\sEND]>(row.[\S]*)\s--\]/sm', '[!-- END \\1 --]', $this->contentXml); - + // Search all possible rows in the document $reg1 = "#]*>(.*)#smU"; preg_match_all($reg1, $this->contentXml, $matches); @@ -302,7 +302,7 @@ IMG; // Search all tags fou into condition to complete $this->vars, so we will proceed all tests even if not defined $reg='@\[!--\sIF\s([{}a-zA-Z0-9\.\,_]+)\s--\]@smU'; preg_match_all($reg, $this->contentXml, $matches, PREG_SET_ORDER); - + //var_dump($this->vars);exit; foreach($matches as $match) // For each match, if there is no entry into this->vars, we add it { @@ -312,7 +312,7 @@ IMG; } } //var_dump($this->vars);exit; - + // Conditionals substitution // Note: must be done before static substitution, else the variable will be replaced by its value and the conditional won't work anymore foreach($this->vars as $key => $value) @@ -358,7 +358,7 @@ IMG; if ($type == 'content') $this->contentXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->contentXml); if ($type == 'styles') $this->stylesXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->stylesXml); if ($type == 'meta') $this->metaXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->metaXml); - + } /** @@ -467,7 +467,7 @@ IMG; $this->setMetaData(); //print $this->metaXml;exit; - + if (! $this->file->addFromString('content.xml', $this->contentXml)) { throw new OdfException('Error during file export addFromString content'); } @@ -477,7 +477,7 @@ IMG; if (! $this->file->addFromString('styles.xml', $this->stylesXml)) { throw new OdfException('Error during file export addFromString styles'); } - + foreach ($this->images as $imageKey => $imageValue) { // Add the image inside the ODT document $this->file->addFile($imageKey, 'Pictures/' . $imageValue); @@ -499,12 +499,12 @@ IMG; public function setMetaData() { if (empty($this->creator)) $this->creator=''; - + $this->metaXml = preg_replace('/.*<\/dc:date>/', ''.gmdate("Y-m-d\TH:i:s").'', $this->metaXml); $this->metaXml = preg_replace('/.*<\/dc:creator>/', ''.htmlspecialchars($this->creator).'', $this->metaXml); $this->metaXml = preg_replace('/.*<\/dc:title>/', ''.htmlspecialchars($this->title).'', $this->metaXml); $this->metaXml = preg_replace('/.*<\/dc:subject>/', ''.htmlspecialchars($this->subject).'', $this->metaXml); - + if (count($this->userdefined)) { foreach($this->userdefined as $key => $val) @@ -515,7 +515,7 @@ IMG; } } } - + /** * Update Manifest file according to added image files * @@ -569,24 +569,58 @@ IMG; { global $conf; - if( $name == "" ) $name = md5(uniqid()); + if( $name == "" ) $name = "temp".md5(uniqid()); dol_syslog(get_class($this).'::exportAsAttachedPDF $name='.$name, LOG_DEBUG); $this->saveToDisk($name); $execmethod=(empty($conf->global->MAIN_EXEC_USE_POPEN)?1:2); // 1 or 2 + // Method 1 sometimes hang the server. - $name=preg_replace('/\.odt/i', '', $name); - if (!empty($conf->global->MAIN_DOL_SCRIPTS_ROOT)) + if (preg_match('/unoconv/', $conf->global->MAIN_ODT_AS_PDF)) { - $command = $conf->global->MAIN_DOL_SCRIPTS_ROOT.'/scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); + // If issue with unoconv, see https://github.com/dagwieers/unoconv/issues/87 + + // MAIN_ODT_AS_PDF should be "sudo -u unoconv /usr/bin/unoconv" and userunoconv must have sudo to be root by adding file /etc/sudoers.d/unoconv with content www-data ALL=(unoconv) NOPASSWD: /usr/bin/unoconv . + + // Try this with www-data user: /usr/bin/unoconv -vvvv -f pdf /tmp/document-example.odt + // It must return: + //Verbosity set to level 4 + //Using office base path: /usr/lib/libreoffice + //Using office binary path: /usr/lib/libreoffice/program + //DEBUG: Connection type: socket,host=127.0.0.1,port=2002;urp;StarOffice.ComponentContext + //DEBUG: Existing listener not found. + //DEBUG: Launching our own listener using /usr/lib/libreoffice/program/soffice.bin. + //LibreOffice listener successfully started. (pid=9287) + //Input file: /tmp/document-example.odt + //unoconv: file `/tmp/document-example.odt' does not exist. + //unoconv: RuntimeException during import phase: + //Office probably died. Unsupported URL : "type detection failed" + //DEBUG: Terminating LibreOffice instance. + //DEBUG: Waiting for LibreOffice instance to exit + + // It fails: + // - set shel of user to bash instead of nologin. + // - set permission to read/write to user on home directory /var/www so user can create the libreoffice , dconf and .cache dir and files then set permission back + + $command = $conf->global->MAIN_ODT_AS_PDF.' '.escapeshellcmd($name); + //$command = '/usr/bin/unoconv -vvv '.escapeshellcmd($name); } else { - dol_syslog(get_class($this).'::exportAsAttachedPDF is used but the constant MAIN_DOL_SCRIPTS_ROOT with path to script directory was not defined.', LOG_WARNING); - $command = '../../scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); - } + // deprecated old method + $name=preg_replace('/\.odt/i', '', $name); + if (!empty($conf->global->MAIN_DOL_SCRIPTS_ROOT)) + { + $command = $conf->global->MAIN_DOL_SCRIPTS_ROOT.'/scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); + } + else + { + dol_syslog(get_class($this).'::exportAsAttachedPDF is used but the constant MAIN_DOL_SCRIPTS_ROOT with path to script directory was not defined.', LOG_WARNING); + $command = '../../scripts/odt2pdf/odt2pdf.sh '.escapeshellcmd($name).' '.(is_numeric($conf->global->MAIN_ODT_AS_PDF)?'jodconverter':$conf->global->MAIN_ODT_AS_PDF); + } + } //$dirname=dirname($name); //$command = DOL_DOCUMENT_ROOT.'/includes/odtphp/odt2pdf.sh '.$name.' '.$dirname; @@ -598,16 +632,19 @@ IMG; } if ($execmethod == 2) { + $outputfile = DOL_DATA_ROOT.'/odt2pdf.log'; + $ok=0; $handle = fopen($outputfile, 'w'); if ($handle) { dol_syslog(get_class($this)."Run command ".$command,LOG_DEBUG); + fwrite($handle, $command."\n"); $handlein = popen($command, 'r'); while (!feof($handlein)) { $read = fgets($handlein); - fwrite($handle,$read); + fwrite($handle, $read); $output_arr[]=$read; } pclose($handlein); @@ -616,7 +653,7 @@ IMG; if (! empty($conf->global->MAIN_UMASK)) @chmod($outputfile, octdec($conf->global->MAIN_UMASK)); } - if($retval == 0) + if ($retval == 0) { dol_syslog(get_class($this).'::exportAsAttachedPDF $ret_val='.$retval, LOG_DEBUG); if (headers_sent($filename, $linenum)) { @@ -686,7 +723,7 @@ IMG; /** * Empty the temporary working directory recursively - * + * * @param string $dir The temporary working directory * @return void */ @@ -709,7 +746,7 @@ IMG; /** * return the value present on odt in [valuename][/valuename] - * + * * @param string $valuename Balise in the template * @return string The value inside the balise */ diff --git a/htdocs/index.php b/htdocs/index.php index 597d41423e5..f8e90919c6a 100644 --- a/htdocs/index.php +++ b/htdocs/index.php @@ -373,135 +373,135 @@ require DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php'; // Number of actions to do (late) if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->read) { - include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - $board=new ActionComm($db); - - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; + $board=new ActionComm($db); + + $dashboardlines[] = $board->load_board($user); } // Number of project opened if (! empty($conf->projet->enabled) && $user->rights->projet->lire) { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - $board=new Project($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + $board=new Project($db); + $dashboardlines[] = $board->load_board($user); } // Number of tasks to do (late) if (! empty($conf->projet->enabled) && empty($conf->global->PROJECT_HIDE_TASKS) && $user->rights->projet->lire) { - include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - $board=new Task($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + $board=new Task($db); + $dashboardlines[] = $board->load_board($user); } // Number of commercial proposals opened (expired) if (! empty($conf->propal->enabled) && $user->rights->propale->lire) { - include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $board=new Propal($db); - $dashboardlines[] = $board->load_board($user,"opened"); - // Number of commercial proposals CLOSED signed (billed) - $dashboardlines[] = $board->load_board($user,"signed"); + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $board=new Propal($db); + $dashboardlines[] = $board->load_board($user,"opened"); + // Number of commercial proposals CLOSED signed (billed) + $dashboardlines[] = $board->load_board($user,"signed"); } // Number of commercial proposals opened (expired) if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { - include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; - $board=new SupplierProposal($db); - $dashboardlines[] = $board->load_board($user,"opened"); - // Number of commercial proposals CLOSED signed (billed) - $dashboardlines[] = $board->load_board($user,"signed"); + include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; + $board=new SupplierProposal($db); + $dashboardlines[] = $board->load_board($user,"opened"); + // Number of commercial proposals CLOSED signed (billed) + $dashboardlines[] = $board->load_board($user,"signed"); } // Number of customer orders a deal if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $board=new Commande($db); + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + $board=new Commande($db); $dashboardlines[] = $board->load_board($user); } // Number of suppliers orders a deal if (! empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->lire) { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; - $board=new CommandeFournisseur($db); + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; + $board=new CommandeFournisseur($db); $dashboardlines[] = $board->load_board($user); } // Number of services enabled (delayed) if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) { - include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - $board=new Contrat($db); - $dashboardlines[] = $board->load_board($user,"inactives"); + include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + $board=new Contrat($db); + $dashboardlines[] = $board->load_board($user,"inactives"); // Number of active services (expired) - $dashboardlines[] = $board->load_board($user,"expired"); + $dashboardlines[] = $board->load_board($user,"expired"); } // Number of invoices customers (has paid) if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $board=new Facture($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $board=new Facture($db); + $dashboardlines[] = $board->load_board($user); } // Number of supplier invoices (has paid) if (! empty($conf->supplier_invoice->enabled) && ! empty($user->rights->fournisseur->facture->lire)) { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - $board=new FactureFournisseur($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + $board=new FactureFournisseur($db); + $dashboardlines[] = $board->load_board($user); } // Number of transactions to conciliate if (! empty($conf->banque->enabled) && $user->rights->banque->lire && ! $user->societe_id) { - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $board=new Account($db); - $nb = $board::countAccountToReconcile(); // Get nb of account to reconciliate - if ($nb > 0) - { - $dashboardlines[] = $board->load_board($user); - } + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + $board=new Account($db); + $nb = $board::countAccountToReconcile(); // Get nb of account to reconciliate + if ($nb > 0) + { + $dashboardlines[] = $board->load_board($user); + } } // Number of cheque to send if (! empty($conf->banque->enabled) && $user->rights->banque->lire && ! $user->societe_id && empty($conf->global->BANK_DISABLE_CHECK_DEPOSIT)) { - include_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; - $board=new RemiseCheque($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; + $board=new RemiseCheque($db); + $dashboardlines[] = $board->load_board($user); } // Number of foundation members if (! empty($conf->adherent->enabled) && $user->rights->adherent->lire && ! $user->societe_id) { - include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - $board=new Adherent($db); - $dashboardlines[] = $board->load_board($user); + include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + $board=new Adherent($db); + $dashboardlines[] = $board->load_board($user); } // Number of expense reports to approve if (! empty($conf->expensereport->enabled) && $user->rights->expensereport->approve) { - include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $board=new ExpenseReport($db); + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $board=new ExpenseReport($db); $dashboardlines[] = $board->load_board($user,'toapprove'); } // Number of expense reports to pay if (! empty($conf->expensereport->enabled) && $user->rights->expensereport->to_paid) { - include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $board=new ExpenseReport($db); + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $board=new ExpenseReport($db); $dashboardlines[] = $board->load_board($user,'topay'); } // Calculate total nb of late -$totallate=0; +$totallate=$totaltodo=0; $var=true; //Remove any invalid response @@ -516,11 +516,13 @@ foreach($dashboardlines as $tmp) foreach($valid_dashboardlines as $board) { if ($board->nbtodolate > 0) { + if(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $totaltodo += $board->nbtodo; $totallate += $board->nbtodolate; } } - - +//var_dump($totallate, $totaltodo); +if(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $totallate = round($totallate / $totaltodo * 100, 2); +//var_dump($totallate); $boxwork=''; $boxwork.='
    '; $boxwork.='
    '.$userstatic->getNomUrl(-1, 'leave').''.$approbatorstatic->getNomUrl(-1).''; - $label=$alltypeleaves[$infos_CP['fk_type']]['label']; - print $label?$label:$infos_CP['fk_type']; + print empty($typeleaves[$infos_CP['fk_type']]['label']) ? $langs->trans("TypeWasDisabledOrRemoved",$infos_CP['fk_type']) : $typeleaves[$infos_CP['fk_type']]['label']; print ''; $nbopenedday=num_open_day($infos_CP['date_debut_gmt'], $infos_CP['date_fin_gmt'], 0, 1, $infos_CP['halfday']); @@ -473,7 +519,17 @@ if (! empty($holiday->holiday)) print ''.dol_print_date($infos_CP['date_debut'],'day').''.dol_print_date($infos_CP['date_fin'],'day').''.$holidaystatic->LibStatut($infos_CP['statut'],5).''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($infos_CP['rowid'], $arrayofselected)) $selected=1; + print ''; + } + print '
    '."\n"; @@ -533,7 +535,7 @@ if ($showweather) $boxwork.=''; $boxwork.=''; if ($object->lines[$i]->fk_product > 0) @@ -666,7 +666,7 @@ else print ''; print ""; - + //Display lines extrafields if (is_array($extralabelslines) && count($extralabelslines)>0) { $colspan=2; @@ -689,14 +689,14 @@ else } print "
    '; $text=''; - if ($totallate > 0) $text=$langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate",$totallate).')'; + if ($totallate > 0) $text=$langs->transnoentitiesnoconv("WarningYouHaveAtLeastOneTaskLate").' ('.$langs->transnoentitiesnoconv("NActionsLate",$totallate.(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '%' : '')).')'; $text.='. '.$langs->trans("LateDesc"); //$text.=$form->textwithpicto('',$langs->trans("LateDesc")); $options='height="64px"'; @@ -686,15 +688,17 @@ $db->close(); function showWeather($totallate,$text,$options) { global $conf; - + $out=''; $offset=0; $factor=10; // By default - $level0=$offset; if (! empty($conf->global->MAIN_METEO_LEVEL0)) $level0=$conf->global->MAIN_METEO_LEVEL0; - $level1=$offset+1*$factor; if (! empty($conf->global->MAIN_METEO_LEVEL1)) $level1=$conf->global->MAIN_METEO_LEVEL1; - $level2=$offset+2*$factor; if (! empty($conf->global->MAIN_METEO_LEVEL2)) $level2=$conf->global->MAIN_METEO_LEVEL2; - $level3=$offset+3*$factor; if (! empty($conf->global->MAIN_METEO_LEVEL3)) $level3=$conf->global->MAIN_METEO_LEVEL3; + $used_conf = !empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE) ? 'MAIN_METEO_PERCENTAGE_LEVEL' : 'MAIN_METEO_LEVEL'; + + $level0=$offset; if (! empty($conf->global->{$used_conf.'0'})) $level0=$conf->global->{$used_conf.'0'}; + $level1=$offset+1*$factor; if (! empty($conf->global->{$used_conf.'1'})) $level1=$conf->global->{$used_conf.'1'}; + $level2=$offset+2*$factor; if (! empty($conf->global->{$used_conf.'2'})) $level2=$conf->global->{$used_conf.'2'}; + $level3=$offset+3*$factor; if (! empty($conf->global->{$used_conf.'3'})) $level3=$conf->global->{$used_conf.'3'}; if ($totallate <= $level0) $out.=img_weather($text,'weather-clear.png',$options); if ($totallate > $level0 && $totallate <= $level1) $out.=img_weather($text,'weather-few-clouds.png',$options); diff --git a/htdocs/install/mysql/data/llx_c_email_templates.sql b/htdocs/install/mysql/data/llx_c_email_templates.sql index b3bb3292ba6..bfa183781c7 100644 --- a/htdocs/install/mysql/data/llx_c_email_templates.sql +++ b/htdocs/install/mysql/data/llx_c_email_templates.sql @@ -20,4 +20,7 @@ -- de l'install et tous les sigles '--' sont supprimés. -- -INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,active,topic,content,content_lines) VALUES (0,null,'member',null,0,null,null,'(SendAnEMailToMember)',1,1,'__(CardContent)__','__(ThisIsContentOfYourCard)__
    \n__(ID)__ : __ID__
    \n__(Civiliyty)__ : __MEMBER_CIVILITY__
    \n__(Firstname)__ : __MEMBER_FIRSTNAME__
    \n__(Lastname)__ : __MEMBER_LASTNAME__
    \n__(Fullname)__ : __MEMBER_FULLNAME__
    \n__(Company)__ : __MEMBER_COMPANY__
    \n__(Address)__ : __MEMBER_ADDRESS__
    \n__(Zip)__ : __MEMBER_ZIP__
    \n__(Town)__ : __MEMBER_TOWN__
    \n__(Country)__ : __MEMBER_COUNTRY__
    \n__(Email)__ : __MEMBER_EMAIL__
    \n__(Birthday)__ : __MEMBER_BIRTH__
    \n__(Photo)__ : __MEMBER_PHOTO__
    \n__(Login)__ : __MEMBER_LOGIN__
    \n__(Password)__ : __MEMBER_PASSWORD__
    \n__(Phone)__ : __MEMBER_PHONE__
    \n__(PhonePerso)__ : __MEMBER_PHONEPRO__
    \n__(PhoneMobile)__ : __MEMBER_PHONEMOBILE__',null); +INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines) VALUES (0,'adherent','member','',0,null,null,'(SendAnEMailToMember)',1,1,1,'__(CardContent)__','__(Hello)__,

    \n\n__(ThisIsContentOfYourCard)__
    \n__(ID)__ : __ID__
    \n__(Civiliyty)__ : __MEMBER_CIVILITY__
    \n__(Firstname)__ : __MEMBER_FIRSTNAME__
    \n__(Lastname)__ : __MEMBER_LASTNAME__
    \n__(Fullname)__ : __MEMBER_FULLNAME__
    \n__(Company)__ : __MEMBER_COMPANY__
    \n__(Address)__ : __MEMBER_ADDRESS__
    \n__(Zip)__ : __MEMBER_ZIP__
    \n__(Town)__ : __MEMBER_TOWN__
    \n__(Country)__ : __MEMBER_COUNTRY__
    \n__(Email)__ : __MEMBER_EMAIL__
    \n__(Birthday)__ : __MEMBER_BIRTH__
    \n__(Photo)__ : __MEMBER_PHOTO__
    \n__(Login)__ : __MEMBER_LOGIN__
    \n__(Password)__ : __MEMBER_PASSWORD__
    \n__(Phone)__ : __MEMBER_PHONE__
    \n__(PhonePerso)__ : __MEMBER_PHONEPRO__
    \n__(PhoneMobile)__ : __MEMBER_PHONEMOBILE__

    \n__(Sincerely)__
    __USER_SIGNATURE__',null); +INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines) VALUES (0,'banque','thirdparty','',0,null,null,'(YourSEPAMandate)',1,1,0,'__(YourSEPAMandate)__','__(Hello)__,

    \n\n__(FindYourSEPAMandate)__ :
    \n__MYCOMPANY_NAME__
    \n__MYCOMPANY_FULLADDRESS__

    \n__(Sincerely)__
    \n__USER_SIGNATURE__',null); + + diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql index 026db0d4383..b805b9f8014 100644 --- a/htdocs/install/mysql/data/llx_c_tva.sql +++ b/htdocs/install/mysql/data/llx_c_tva.sql @@ -135,10 +135,7 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 3 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 34, 3, '0','0','VAT Rate 0',1); -- INDIA (id country=117) -insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (1171, 117, '12.5','0','VAT standard rate', 0); -insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (1172, 117, '4','0','VAT reduced rate', 0); -insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (1173, 117, '1','0','VAT super-reduced rate',0); -insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (1174, 117, '0','0','VAT Rate 0', 0); +insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (1171, 117, '0','0','VAT Rate 0', 0); insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1178, 117, 'C+S-5', 0, 2.5, '1', 2.5, '1', 0, 'CGST+SGST - Same state sales', 1); insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1179, 117, 'I-5' , 5, 0, '0', 0, '0', 0, 'IGST', 1); diff --git a/htdocs/install/mysql/migration/3.0.0-3.1.0.sql b/htdocs/install/mysql/migration/3.0.0-3.1.0.sql index fa94a5deeed..a4ab666299d 100644 --- a/htdocs/install/mysql/migration/3.0.0-3.1.0.sql +++ b/htdocs/install/mysql/migration/3.0.0-3.1.0.sql @@ -63,7 +63,7 @@ ALTER TABLE llx_facturedet ADD UNIQUE INDEX uk_fk_remise_except (fk_remise_excep ALTER TABLE llx_societe ADD COLUMN fk_currency integer DEFAULT 0 AFTER fk_forme_juridique; ALTER TABLE llx_societe ADD COLUMN status tinyint DEFAULT 1; -ALTER TABLE llx_societe ADD COLUMN logo varchar(255); +ALTER TABLE llx_societe ADD COLUMN logo varchar(255) DEFAULT NULL; ALTER TABLE llx_societe_remise MODIFY remise_client double(6,3) DEFAULT 0 NOT NULL; diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index 158c82da020..9e3b19abe26 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -26,6 +26,12 @@ +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_journal MODIFY code VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_journal MODIFY code VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_bank_account MODIFY accountancy_journal VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_bank_account MODIFY accountancy_journal VARCHAR(20) COLLATE utf8_unicode_ci; + + ALTER TABLE llx_holiday_config MODIFY COLUMN name varchar(128); ALTER TABLE llx_supplier_proposaldet CHANGE COLUMN fk_askpricesupplier fk_supplier_proposal integer NOT NULL; @@ -618,5 +624,11 @@ CREATE TABLE llx_facturedet_rec_extrafields ALTER TABLE llx_facturedet_rec_extrafields ADD INDEX idx_facturedet_rec_extrafields (fk_object); -insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1176, 117, 'CGST+SGST', 0, 9, '1', 9, '1', 0, 'CGST+SGST - Same state sales', 1); -insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1177, 117, 'IGST' , 18, 0, '0', 0, '0', 0, 'IGST', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1178, 117, 'C+S-5', 0, 2.5, '1', 2.5, '1', 0, 'CGST+SGST - Same state sales', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1179, 117, 'I-5' , 5, 0, '0', 0, '0', 0, 'IGST', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1180, 117, 'C+S-12', 0, 6, '1', 6, '1', 0, 'CGST+SGST - Same state sales', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1181, 117, 'I-12' , 12, 0, '0', 0, '0', 0, 'IGST', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1176, 117, 'C+S-18', 0, 9, '1', 9, '1', 0, 'CGST+SGST - Same state sales', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1177, 117, 'I-18' , 18, 0, '0', 0, '0', 0, 'IGST', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1182, 117, 'C+S-28', 0, 14, '1', 14, '1', 0, 'CGST+SGST - Same state sales', 1); +insert into llx_c_tva(rowid,fk_pays,code,taux,localtax1,localtax1_type,localtax2,localtax2_type,recuperableonly,note,active) values (1183, 117, 'I-28' , 28, 0, '0', 0, '0', 0, 'IGST', 1); diff --git a/htdocs/install/mysql/migration/6.0.0-7.0.0.sql b/htdocs/install/mysql/migration/6.0.0-7.0.0.sql index c8f2142684c..75b2ac4d688 100644 --- a/htdocs/install/mysql/migration/6.0.0-7.0.0.sql +++ b/htdocs/install/mysql/migration/6.0.0-7.0.0.sql @@ -25,6 +25,28 @@ -- -- VMYSQL4.1 DELETE FROM llx_usergroup_user WHERE fk_usergroup NOT IN (SELECT rowid from llx_usergroup); +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_account MODIFY account_number VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_account MODIFY account_number VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_bookkeeping MODIFY numero_compte VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_bookkeeping MODIFY numero_compte VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_journal MODIFY code VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_journal MODIFY code VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_bank_account MODIFY accountancy_journal VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_bank_account MODIFY accountancy_journal VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_stock_mouvement MODIFY batch VARCHAR(30) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_stock_mouvement MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_lot MODIFY batch VARCHAR(30) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_lot MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_batch MODIFY batch VARCHAR(30) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_batch MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_sell VARCHAR(32) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_sell VARCHAR(32) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_buy VARCHAR(32) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_buy VARCHAR(32) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_c_type_fees MODIFY accountancy_code VARCHAR(32) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_c_type_fees MODIFY accountancy_code VARCHAR(32) COLLATE utf8_unicode_ci; + + -- Missing in 5.0 ALTER TABLE llx_user MODIFY login varchar(50) NOT NULL; @@ -41,6 +63,17 @@ ALTER TABLE llx_website_page ADD COLUMN fk_user_modif integer; -- For 7.0 +ALTER TABLE llx_user ADD COLUMN birth date; + +-- VMYSQL4.1 ALTER TABLE llx_holiday_users DROP PRIMARY KEY; + +ALTER TABLE llx_holiday_users ADD UNIQUE INDEX uk_holiday_users(fk_user, fk_type, nb_holiday); + +ALTER TABLE llx_product_fournisseur_price ADD COLUMN localtax1_tx double(6,3) DEFAULT 0; +ALTER TABLE llx_product_fournisseur_price ADD COLUMN localtax1_type varchar(10) NOT NULL DEFAULT '0'; +ALTER TABLE llx_product_fournisseur_price ADD COLUMN localtax2_tx double(6,3) DEFAULT 0; +ALTER TABLE llx_product_fournisseur_price ADD COLUMN localtax2_type varchar(10) NOT NULL DEFAULT '0'; + insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('MEMBER_SENTBYMAIL','Mails sent from member card','Executed when you send email from member card','member',23); @@ -65,8 +98,14 @@ ALTER TABLE llx_contrat MODIFY COLUMN ref_ext varchar(50); UPDATE llx_c_email_templates SET position = 0 WHERE position IS NULL; +UPDATE llx_c_email_templates SET lang = '' WHERE lang IS NULL; -INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,active,topic,content,content_lines) VALUES (0,null,'member',null,0,null,null,'(SendAnEMailToMember)',1,1,'__(CardContent)__','__(ThisIsContentOfYourCard)__
    \n__(ID)__ : __ID__
    \n__(Civiliyty)__ : __MEMBER_CIVILITY__
    \n__(Firstname)__ : __MEMBER_FIRSTNAME__
    \n__(Lastname)__ : __MEMBER_LASTNAME__
    \n__(Fullname)__ : __MEMBER_FULLNAME__
    \n__(Company)__ : __MEMBER_COMPANY__
    \n__(Address)__ : __MEMBER_ADDRESS__
    \n__(Zip)__ : __MEMBER_ZIP__
    \n__(Town)__ : __MEMBER_TOWN__
    \n__(Country)__ : __MEMBER_COUNTRY__
    \n__(Email)__ : __MEMBER_EMAIL__
    \n__(Birthday)__ : __MEMBER_BIRTH__
    \n__(Photo)__ : __MEMBER_PHOTO__
    \n__(Login)__ : __MEMBER_LOGIN__
    \n__(Password)__ : __MEMBER_PASSWORD__
    \n__(Phone)__ : __MEMBER_PHONE__
    \n__(PhonePerso)__ : __MEMBER_PHONEPRO__
    \n__(PhoneMobile)__ : __MEMBER_PHONEMOBILE__',null); +ALTER TABLE llx_c_email_templates ADD COLUMN enabled varchar(255) DEFAULT '1'; +ALTER TABLE llx_c_email_templates ADD COLUMN joinfiles varchar(255) DEFAULT '1'; +ALTER TABLE llx_c_email_templates MODIFY COLUMN content mediumtext; + +INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines) VALUES (0,'adherent','member','',0,null,null,'(SendAnEMailToMember)',1,1,1,'__(CardContent)__','__(Hello)__,

    \n\n__(ThisIsContentOfYourCard)__
    \n__(ID)__ : __ID__
    \n__(Civiliyty)__ : __MEMBER_CIVILITY__
    \n__(Firstname)__ : __MEMBER_FIRSTNAME__
    \n__(Lastname)__ : __MEMBER_LASTNAME__
    \n__(Fullname)__ : __MEMBER_FULLNAME__
    \n__(Company)__ : __MEMBER_COMPANY__
    \n__(Address)__ : __MEMBER_ADDRESS__
    \n__(Zip)__ : __MEMBER_ZIP__
    \n__(Town)__ : __MEMBER_TOWN__
    \n__(Country)__ : __MEMBER_COUNTRY__
    \n__(Email)__ : __MEMBER_EMAIL__
    \n__(Birthday)__ : __MEMBER_BIRTH__
    \n__(Photo)__ : __MEMBER_PHOTO__
    \n__(Login)__ : __MEMBER_LOGIN__
    \n__(Password)__ : __MEMBER_PASSWORD__
    \n__(Phone)__ : __MEMBER_PHONE__
    \n__(PhonePerso)__ : __MEMBER_PHONEPRO__
    \n__(PhoneMobile)__ : __MEMBER_PHONEMOBILE__

    \n__(Sincerely)__
    __USER_SIGNATURE__',null); +INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines) VALUES (0,'banque','thirdparty','',0,null,null,'(YourSEPAMandate)',1,1,0,'__(YourSEPAMandate)__','__(Hello)__,

    \n\n__(FindYourSEPAMandate)__ :
    \n__MYCOMPANY_NAME__
    \n__MYCOMPANY_FULLADDRESS__

    \n__(Sincerely)__
    \n__USER_SIGNATURE__',null); INSERT INTO llx_c_accounting_category (rowid, code, label, range_account, sens, category_type, formula, position, fk_country, active) VALUES ( 1, 'VENTES', 'Income of products/services', 'Exemple: 7xxxxx', 0, 0, '', '10', 1, 1); INSERT INTO llx_c_accounting_category (rowid, code, label, range_account, sens, category_type, formula, position, fk_country, active) VALUES ( 2, 'DEPENSES', 'Expenses of products/services', 'Exemple: 6xxxxx', 0, 0, '', '20', 1, 1); @@ -94,6 +133,8 @@ ALTER TABLE llx_website_page MODIFY COLUMN pageurl varchar(255); ALTER TABLE llx_website_page ADD COLUMN lang varchar(6); ALTER TABLE llx_website_page ADD COLUMN fk_page integer; ALTER TABLE llx_website_page ADD COLUMN grabbed_from varchar(255); +ALTER TABLE llx_website_page ADD COLUMN htmlheader mediumtext; +ALTER TABLE llx_website_page MODIFY COLUMN htmlheader mediumtext; ALTER TABLE llx_website_page MODIFY COLUMN status INTEGER DEFAULT 1; UPDATE llx_website_page set status = 1 WHERE status IS NULL; @@ -110,7 +151,7 @@ ALTER TABLE llx_accounting_account ADD COLUMN extraparams varchar(255); ALTER TABLE llx_accounting_bookkeeping ADD COLUMN import_key varchar(14); ALTER TABLE llx_accounting_bookkeeping ADD COLUMN extraparams varchar(255); -ALTER TABLE llx_accounting_bookkeeping ADD COLUMN date_lim_reglement datetime; +ALTER TABLE llx_accounting_bookkeeping ADD COLUMN date_lim_reglement datetime DEFAULT NULL; ALTER TABLE llx_accounting_bookkeeping ADD COLUMN fk_user integer NULL; CREATE TABLE IF NOT EXISTS llx_expensereport_ik ( @@ -239,7 +280,7 @@ CREATE TABLE llx_expensereport_rules ( code_expense_rules_type varchar(50) NOT NULL, is_for_all tinyint DEFAULT '0', entity integer DEFAULT 1 -); +)ENGINE=innodb; ALTER TABLE llx_expensereport_det ADD COLUMN rule_warning_message text; ALTER TABLE llx_expensereport_det ADD COLUMN fk_c_exp_tax_cat integer; @@ -252,6 +293,12 @@ ALTER TABLE llx_extrafields ADD COLUMN fk_user_modif integer; ALTER TABLE llx_extrafields ADD COLUMN datec datetime; ALTER TABLE llx_extrafields ADD COLUMN tms timestamp; +-- We fix value of 'list' fro m0 to 1 for all extrafields created before this migration +UPDATE llx_extrafields SET list = 1 WHERE list = 0 AND fk_user_author IS NULL and fk_user_modif IS NULL and datec IS NULL; + +ALTER TABLE llx_extrafields MODIFY COLUMN list integer DEFAULT 1; +--VPGSQL8.2 ALTER TABLE llx_extrafields ALTER COLUMN list SET DEFAULT 1; + ALTER TABLE llx_extrafields MODIFY COLUMN langs varchar(64); ALTER TABLE llx_holiday_config MODIFY COLUMN name varchar(128); @@ -282,14 +329,16 @@ insert into llx_c_action_trigger (code,label,description,elementtype,rang) value insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROPOSAL_SUPPLIER_CLOSE_SIGNED','Price request closed signed','Executed when a customer proposal is closed signed','proposal_supplier',10); insert into llx_c_action_trigger (code,label,description,elementtype,rang) values ('PROPOSAL_SUPPLIER_CLOSE_REFUSED','Price request closed refused','Executed when a customer proposal is closed refused','proposal_supplier',10); +DROP TABLE llx_projet_task_comment; -CREATE TABLE llx_projet_task_comment ( +CREATE TABLE llx_comment ( rowid integer AUTO_INCREMENT PRIMARY KEY, datec datetime DEFAULT NULL, tms timestamp, description text NOT NULL, - fk_user integer DEFAULT NULL, - fk_task integer DEFAULT NULL, + fk_user_author integer DEFAULT NULL, + fk_element integer DEFAULT NULL, + element_type varchar(50) DEFAULT NULL, entity integer DEFAULT 1, import_key varchar(125) DEFAULT NULL )ENGINE=innodb; @@ -307,19 +356,29 @@ DELETE FROM llx_const WHERE name = __ENCRYPT('ACCOUNTING_EXPORT_DEVISE')__; DELETE FROM llx_const WHERE name = __ENCRYPT('ACCOUNTING_EXPORT_PIECE')__; DELETE FROM llx_const WHERE name = __ENCRYPT('ACCOUNTING_EXPENSEREPORT_JOURNAL')__; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_account MODIFY account_number VARCHAR(20) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_account MODIFY account_number VARCHAR(20) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_bookkeeping MODIFY numero_compte VARCHAR(20) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_bookkeeping MODIFY numero_compte VARCHAR(20) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_stock_mouvement MODIFY batch VARCHAR(30) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_stock_mouvement MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_lot MODIFY batch VARCHAR(30) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_lot MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_batch MODIFY batch VARCHAR(30) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_batch MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_sell VARCHAR(32) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_sell VARCHAR(32) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_buy VARCHAR(32) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_product MODIFY accountancy_code_buy VARCHAR(32) COLLATE utf8_unicode_ci; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_c_type_fees MODIFY accountancy_code VARCHAR(32) CHARACTER SET utf8; --- VMYSQLUTF8UNICODECI ALTER TABLE llx_c_type_fees MODIFY accountancy_code VARCHAR(32) COLLATE utf8_unicode_ci; +ALTER TABLE llx_c_paiement DROP PRIMARY KEY; +ALTER TABLE llx_c_paiement ADD COLUMN entity integer DEFAULT 1 NOT NULL AFTER id; +ALTER TABLE llx_c_paiement DROP INDEX uk_c_paiement; +ALTER TABLE llx_c_paiement ADD UNIQUE INDEX uk_c_paiement(id, entity, code); + +ALTER TABLE llx_c_payment_term DROP PRIMARY KEY; +ALTER TABLE llx_c_payment_term ADD COLUMN entity integer DEFAULT 1 NOT NULL AFTER rowid; +ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term(rowid, entity, code); + +ALTER TABLE llx_projet CHANGE datec datec datetime; + +create table llx_c_email_senderprofile +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + private smallint DEFAULT 0 NOT NULL, -- Template public or private + date_creation datetime, + tms timestamp, + label varchar(255), -- Label of predefined email + email varchar(255), -- Email + signature text, -- Predefined signature + position smallint, -- Position + active tinyint DEFAULT 1 NOT NULL +)ENGINE=innodb; + +ALTER TABLE llx_c_email_senderprofile ADD UNIQUE INDEX uk_c_email_senderprofile(entity, label, email); diff --git a/htdocs/install/mysql/migration/repair.sql b/htdocs/install/mysql/migration/repair.sql index 1fed846bd44..7bc403fd3b3 100755 --- a/htdocs/install/mysql/migration/repair.sql +++ b/htdocs/install/mysql/migration/repair.sql @@ -31,6 +31,10 @@ -- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_account MODIFY account_number VARCHAR(20) COLLATE utf8_unicode_ci; -- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_bookkeeping MODIFY numero_compte VARCHAR(20) CHARACTER SET utf8; -- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_bookkeeping MODIFY numero_compte VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_journal MODIFY code VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_accounting_journal MODIFY code VARCHAR(20) COLLATE utf8_unicode_ci; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_bank_account MODIFY accountancy_journal VARCHAR(20) CHARACTER SET utf8; +-- VMYSQLUTF8UNICODECI ALTER TABLE llx_bank_account MODIFY accountancy_journal VARCHAR(20) COLLATE utf8_unicode_ci; -- VMYSQLUTF8UNICODECI ALTER TABLE llx_stock_mouvement MODIFY batch VARCHAR(30) CHARACTER SET utf8; -- VMYSQLUTF8UNICODECI ALTER TABLE llx_stock_mouvement MODIFY batch VARCHAR(30) COLLATE utf8_unicode_ci; -- VMYSQLUTF8UNICODECI ALTER TABLE llx_product_lot MODIFY batch VARCHAR(30) CHARACTER SET utf8; @@ -364,6 +368,8 @@ update llx_bank_url as bu set url_id = (select e.fk_user_author from tmp_bank_ur drop table tmp_bank_url_expense_user; +-- VMYSQL4.1 update llx_projet_task_time set task_datehour = task_date where task_datehour < task_date or task_datehour > DATE_ADD(task_date, interval 1 day); + -- Clean product prices --delete from llx_product_price where date_price between '2017-04-20 06:51:00' and '2017-04-20 06:51:05'; diff --git a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql index 9ec89aad971..4d9f6320566 100644 --- a/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql +++ b/htdocs/install/mysql/tables/llx_accounting_bookkeeping.sql @@ -40,7 +40,7 @@ CREATE TABLE llx_accounting_bookkeeping multicurrency_code varchar(255), -- FEC:Idevise lettering_code varchar(255), -- FEC:EcritureLet date_lettering datetime, -- FEC:DateLet - date_lim_reglement datetime, -- | date limite de reglement + date_lim_reglement datetime DEFAULT NULL, -- | date limite de reglement fk_user_author integer NOT NULL, -- | user creating fk_user_modif integer, -- | user making last change date_creation datetime, -- FEC:EcritureDate | creation date diff --git a/htdocs/install/mysql/tables/llx_c_email_senderprofile.key.sql b/htdocs/install/mysql/tables/llx_c_email_senderprofile.key.sql new file mode 100644 index 00000000000..a4896ea162c --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_email_senderprofile.key.sql @@ -0,0 +1,21 @@ +-- =================================================================== +-- Copyright (C) 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 +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- Table with templates of emails +-- =================================================================== + +ALTER TABLE llx_c_email_senderprofile ADD UNIQUE INDEX uk_c_email_senderprofile(entity, label, email); + diff --git a/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql b/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql new file mode 100644 index 00000000000..24a050ca45a --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_email_senderprofile.sql @@ -0,0 +1,32 @@ +-- =================================================================== +-- Copyright (C) 2001-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 +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- Table with templates of emails +-- =================================================================== + +create table llx_c_email_senderprofile +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + entity integer DEFAULT 1 NOT NULL, -- multi company id + private smallint DEFAULT 0 NOT NULL, -- Template public or private + date_creation datetime, + tms timestamp, + label varchar(255), -- Label of predefined email + email varchar(255) NOT NULL, -- Email + signature text -- Predefined signature + position smallint DEFAULT 0, -- Position + active tinyint DEFAULT 1 NOT NULL, +)ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_c_email_templates.sql b/htdocs/install/mysql/tables/llx_c_email_templates.sql index 9d82d37768a..adcda4c69f8 100644 --- a/htdocs/install/mysql/tables/llx_c_email_templates.sql +++ b/htdocs/install/mysql/tables/llx_c_email_templates.sql @@ -23,15 +23,17 @@ create table llx_c_email_templates entity integer DEFAULT 1 NOT NULL, -- multi company id module varchar(32), -- Nom du module en rapport avec le modele type_template varchar(32), -- template for which type of email (send invoice by email, send order, ...) - lang varchar(6), + lang varchar(6) DEFAULT '', -- We use a default to '' so the unique index that include this field will work private smallint DEFAULT 0 NOT NULL, -- Template public or private fk_user integer, -- Id user owner if template is private, or null datec datetime, tms timestamp, label varchar(255), -- Label of predefined email position smallint, -- Position + enabled varchar(255) DEFAULT '1', -- Condition to have this module visible active tinyint DEFAULT 1 NOT NULL, topic text, -- Predefined topic - content text, -- Predefined text + joinfiles text, -- Files to attach + content mediumtext, -- Predefined text content_lines text -- Predefined lines )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_c_paiement.key.sql b/htdocs/install/mysql/tables/llx_c_paiement.key.sql index 0d6686a774c..ad1930fba2e 100644 --- a/htdocs/install/mysql/tables/llx_c_paiement.key.sql +++ b/htdocs/install/mysql/tables/llx_c_paiement.key.sql @@ -1,5 +1,6 @@ -- ======================================================================== --- Copyright (C) 2012 Florian Henry +-- Copyright (C) 2012 Florian Henry +-- Copyright (C) 2017 Regis Houssin -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by @@ -16,4 +17,4 @@ -- -- ======================================================================== -ALTER TABLE llx_c_paiement ADD UNIQUE INDEX uk_c_paiement(code); +ALTER TABLE llx_c_paiement ADD UNIQUE INDEX uk_c_paiement(id, entity, code); diff --git a/htdocs/install/mysql/tables/llx_c_paiement.sql b/htdocs/install/mysql/tables/llx_c_paiement.sql index 7db85510608..55cb44fb257 100644 --- a/htdocs/install/mysql/tables/llx_c_paiement.sql +++ b/htdocs/install/mysql/tables/llx_c_paiement.sql @@ -1,7 +1,8 @@ -- ======================================================================== --- Copyright (C) 2001-2004 Rodolphe Quiedeville --- Copyright (C) 2004-2014 Laurent Destailleur --- Copyright (C) 2014 Alexandre Spangaro +-- Copyright (C) 2001-2004 Rodolphe Quiedeville +-- Copyright (C) 2004-2014 Laurent Destailleur +-- Copyright (C) 2014 Alexandre Spangaro +-- Copyright (C) 2017 Regis Houssin -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by @@ -20,15 +21,13 @@ create table llx_c_paiement ( - id integer PRIMARY KEY, + id integer, + entity integer DEFAULT 1 NOT NULL, -- multi company id code varchar(6) NOT NULL, libelle varchar(62), type smallint, -- 0: input money, 1: output money, 2: input and output, 3: other active tinyint DEFAULT 1 NOT NULL, accountancy_code varchar(32) NULL, module varchar(32) NULL, - position integer NOT NULL DEFAULT 0 + position integer NOT NULL DEFAULT 0 )ENGINE=innodb; - - - diff --git a/htdocs/install/mysql/tables/llx_c_payment_term.key.sql b/htdocs/install/mysql/tables/llx_c_payment_term.key.sql new file mode 100644 index 00000000000..1bd86401945 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_c_payment_term.key.sql @@ -0,0 +1,20 @@ +-- ======================================================================== +-- Copyright (C) 2012 Florian Henry +-- Copyright (C) 2017 Regis Houssin +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- ======================================================================== + +ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term(rowid, entity, code); diff --git a/htdocs/install/mysql/tables/llx_c_payment_term.sql b/htdocs/install/mysql/tables/llx_c_payment_term.sql index d0f07abc5a1..cc7c7a22dea 100644 --- a/htdocs/install/mysql/tables/llx_c_payment_term.sql +++ b/htdocs/install/mysql/tables/llx_c_payment_term.sql @@ -1,6 +1,7 @@ -- ============================================================================ --- Copyright (C) 2002-2003 Rodolphe Quiedeville --- Copyright (C) 2016 Laurent Destailleur +-- Copyright (C) 2002-2003 Rodolphe Quiedeville +-- Copyright (C) 2016 Laurent Destailleur +-- Copyright (C) 2017 Regis Houssin -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by @@ -19,15 +20,16 @@ create table llx_c_payment_term ( - rowid integer PRIMARY KEY, - code varchar(16), - sortorder smallint, - active tinyint DEFAULT 1, - libelle varchar(255), - libelle_facture text, - type_cdr tinyint, -- Type of change date reckoning. 1=Payment at end of current month, 2=the Nth of next month - nbjour smallint, - decalage smallint, - module varchar(32) NULL, - position integer NOT NULL DEFAULT 0 + rowid integer, + entity integer DEFAULT 1 NOT NULL, -- multi company id + code varchar(16), + sortorder smallint, + active tinyint DEFAULT 1, + libelle varchar(255), + libelle_facture text, + type_cdr tinyint, -- Type of change date reckoning. 1=Payment at end of current month, 2=the Nth of next month + nbjour smallint, + decalage smallint, + module varchar(32) NULL, + position integer NOT NULL DEFAULT 0 )ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_extrafields.sql b/htdocs/install/mysql/tables/llx_extrafields.sql index 3b9a9b2d72b..548508d451d 100644 --- a/htdocs/install/mysql/tables/llx_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_extrafields.sql @@ -34,7 +34,7 @@ create table llx_extrafields pos integer DEFAULT 0, alwayseditable integer DEFAULT 0, -- 1 if field can be edited whatever is element status param text, -- extra parameters to define possible values of field - list integer DEFAULT 0, -- list of values for field that are combo lists + list integer DEFAULT 1, -- list of values for field that are combo lists langs varchar(64), -- example: fileofmymodule@mymodule ishidden integer DEFAULT 0, -- Can be foreign key of external system fk_user_author integer, -- user making creation diff --git a/htdocs/install/mysql/tables/llx_holiday.sql b/htdocs/install/mysql/tables/llx_holiday.sql index 35982525853..f6994810021 100644 --- a/htdocs/install/mysql/tables/llx_holiday.sql +++ b/htdocs/install/mysql/tables/llx_holiday.sql @@ -19,7 +19,7 @@ CREATE TABLE llx_holiday ( rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY, -ref varchar(30) NOT NULL, -- number +ref varchar(30) NULL, -- number ref_ext varchar(255), entity integer DEFAULT 1 NOT NULL, -- Multi company id fk_user integer NOT NULL, diff --git a/htdocs/install/mysql/tables/llx_holiday_users.key.sql b/htdocs/install/mysql/tables/llx_holiday_users.key.sql new file mode 100644 index 00000000000..e03dd6ebfcb --- /dev/null +++ b/htdocs/install/mysql/tables/llx_holiday_users.key.sql @@ -0,0 +1,19 @@ +-- =================================================================== +-- Copyright (C) 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 +-- the Free Software Foundation; either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- =================================================================== + +ALTER TABLE llx_holiday_users ADD UNIQUE INDEX uk_holiday_users(fk_user, fk_type, nb_holiday); diff --git a/htdocs/install/mysql/tables/llx_holiday_users.sql b/htdocs/install/mysql/tables/llx_holiday_users.sql index 00ac2715458..ae47c0a99e0 100644 --- a/htdocs/install/mysql/tables/llx_holiday_users.sql +++ b/htdocs/install/mysql/tables/llx_holiday_users.sql @@ -20,5 +20,5 @@ CREATE TABLE llx_holiday_users ( fk_user integer NOT NULL, fk_type integer NOT NULL, - nb_holiday real NOT NULL DEFAULT '0' + nb_holiday real NOT NULL DEFAULT 0 ) ENGINE=innodb; \ No newline at end of file diff --git a/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql b/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql index f341b103edb..1c86bfe04f8 100755 --- a/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql +++ b/htdocs/install/mysql/tables/llx_product_fournisseur_price.sql @@ -38,6 +38,10 @@ create table llx_product_fournisseur_price unitcharges double(24,8) DEFAULT 0, -- deprecated default_vat_code varchar(10), tva_tx double(6,3) NOT NULL, + localtax1_tx double(6,3) DEFAULT 0, + localtax1_type varchar(10) NOT NULL DEFAULT '0', + localtax2_tx double(6,3) DEFAULT 0, + localtax2_type varchar(10) NOT NULL DEFAULT '0', info_bits integer NOT NULL DEFAULT 0, fk_user integer, fk_supplier_price_expression integer, -- Link to the rule for dynamic price calculation diff --git a/htdocs/install/mysql/tables/llx_projet.sql b/htdocs/install/mysql/tables/llx_projet.sql index 8ca404d3a0e..3875e64e1a7 100644 --- a/htdocs/install/mysql/tables/llx_projet.sql +++ b/htdocs/install/mysql/tables/llx_projet.sql @@ -21,7 +21,7 @@ create table llx_projet ( rowid integer AUTO_INCREMENT PRIMARY KEY, fk_soc integer, - datec date, -- date creation project + datec datetime, -- date creation project tms timestamp, dateo date, -- date start project datee date, -- date end project diff --git a/htdocs/install/mysql/tables/llx_societe.sql b/htdocs/install/mysql/tables/llx_societe.sql index 20440b692d7..0f0cb437750 100644 --- a/htdocs/install/mysql/tables/llx_societe.sql +++ b/htdocs/install/mysql/tables/llx_societe.sql @@ -95,13 +95,13 @@ create table llx_societe barcode varchar(255), -- barcode fk_barcode_type integer NULL DEFAULT 0, -- barcode type price_level integer NULL, -- level of price for multiprices - outstanding_limit double(24,8) DEFAULT NULL, -- allowed outstanding limit + outstanding_limit double(24,8) DEFAULT NULL, -- allowed outstanding limit default_lang varchar(6), -- default language - logo varchar(255), - canvas varchar(32), -- type of canvas if used (null by default) + logo varchar(255) DEFAULT NULL, + canvas varchar(32) DEFAULT NULL, -- type of canvas if used (null by default) import_key varchar(14), -- import key - webservices_url varchar(255), -- supplier webservice url - webservices_key varchar(128), -- supplier webservice key + webservices_url varchar(255), -- supplier webservice url + webservices_key varchar(128), -- supplier webservice key fk_multicurrency integer, multicurrency_code varchar(255) diff --git a/htdocs/install/mysql/tables/llx_user.sql b/htdocs/install/mysql/tables/llx_user.sql index ed837b49b51..71ea5a559f5 100644 --- a/htdocs/install/mysql/tables/llx_user.sql +++ b/htdocs/install/mysql/tables/llx_user.sql @@ -47,6 +47,7 @@ create table llx_user town varchar(50), -- town fk_state integer DEFAULT 0, -- fk_country integer DEFAULT 0, -- + birth date, -- birthday job varchar(128), skype varchar(255), office_phone varchar(20), diff --git a/htdocs/install/mysql/tables/llx_website_page.sql b/htdocs/install/mysql/tables/llx_website_page.sql index f3d1cca4786..5393177a3bb 100644 --- a/htdocs/install/mysql/tables/llx_website_page.sql +++ b/htdocs/install/mysql/tables/llx_website_page.sql @@ -27,6 +27,7 @@ CREATE TABLE llx_website_page keywords varchar(255), lang varchar(6), fk_page integer, + htmlheader text, content mediumtext, -- text is not enough in size status integer DEFAULT 1, grabbed_from varchar(255), diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php index 135d4b83caa..f6a51657799 100644 --- a/htdocs/install/upgrade2.php +++ b/htdocs/install/upgrade2.php @@ -410,15 +410,16 @@ if (! GETPOST('action','aZ09') || preg_match('/upgrade/i',GETPOST('action','aZ09 migrate_reload_menu($db,$langs,$conf,$versionto); } - // Can force activation of some module during migration with paramater 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...' + // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...' + // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line. if (! $error && $enablemodules) { - // Reload modules (this must be always and only into last targeted version) + // Reload modules (this must be always done and only into last targeted version) $listofmodules=array(); $tmplistofmodules=explode(',', $enablemodules); foreach($tmplistofmodules as $value) { - $listofmodules[$value]='newboxdefonly'; + $listofmodules[$value]='forceactivate'; } migrate_reload_modules($db,$langs,$conf,$listofmodules,1); } @@ -4118,31 +4119,11 @@ function migrate_delete_old_dir($db,$langs,$conf) */ function migrate_reload_modules($db,$langs,$conf,$listofmodule=array(),$force=0) { + if (count($listofmodule) == 0) return; + dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force); - // If no info is provided, we reload all modules with mode newboxdefonly. - if (count($listofmodule) == 0) - { - $listofmodule=array( - 'MAIN_MODULE_AGENDA'=>'newboxdefonly', - 'MAIN_MODULE_SOCIETE'=>'newboxdefonly', - 'MAIN_MODULE_PRODUIT'=>'newboxdefonly', - 'MAIN_MODULE_SERVICE'=>'newboxdefonly', - 'MAIN_MODULE_COMMANDE'=>'newboxdefonly', - 'MAIN_MODULE_FACTURE'=>'newboxdefonly', - 'MAIN_MODULE_FOURNISSEUR'=>'newboxdefonly', - 'MAIN_MODULE_HOLIDAY'=>'newboxdefonly', - 'MAIN_MODULE_USER'=>'newboxdefonly', - 'MAIN_MODULE_DEPLACEMENT'=>'newboxdefonly', - 'MAIN_MODULE_DON'=>'newboxdefonly', - 'MAIN_MODULE_ECM'=>'newboxdefonly', - 'MAIN_MODULE_PAYBOX'=>'newboxdefonly', - 'MAIN_MODULE_OPENSURVEY'=>'newboxdefonly', - 'MAIN_MODULE_SALARIES'=>'newboxdefonly' - ); - } - - foreach($listofmodule as $moduletoreload => $reloadmode) + foreach($listofmodule as $moduletoreload => $reloadmode) // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate' { if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && ! $force)) continue; // Discard reload if module not enabled diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 8ab0ddc018c..eacfe4fc2aa 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -148,7 +148,8 @@ Doctype=Type of document Docdate=Date Docref=Reference Code_tiers=Thirdparty -Labelcompte=Label account +LabelAccount=Label account +LabelOperation=Label operation Sens=Sens Codejournal=Journal NumPiece=Piece number diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index 7d96aba7d8f..d0da9be7aef 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -259,17 +259,18 @@ FontSize=Font size Content=Content NoticePeriod=Notice period NewByMonth=New by month -Emails=E-mails -EMailsSetup=E-mails setup -EMailsDesc=This page allows you to overwrite your PHP parameters for e-mails sending. In most cases on Unix/Linux OS, your PHP setup is correct and these parameters are useless. +Emails=Emails +EMailsSetup=Emails setup +EMailsDesc=This page allows you to overwrite your PHP parameters for emails sending. In most cases on Unix/Linux OS, your PHP setup is correct and these parameters are useless. +EmailSenderProfiles=Emails sender profiles MAIN_MAIL_SMTP_PORT=SMTP/SMTPS Port (By default in php.ini: %s) MAIN_MAIL_SMTP_SERVER=SMTP/SMTPS Host (By default in php.ini: %s) MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike=SMTP/SMTPS Port (Not defined into PHP on Unix like systems) MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike=SMTP/SMTPS Host (Not defined into PHP on Unix like systems) -MAIN_MAIL_EMAIL_FROM=Sender e-mail for automatic emails (By default in php.ini: %s) -MAIN_MAIL_ERRORS_TO=Sender e-mail used for error returns emails sent +MAIN_MAIL_EMAIL_FROM=Sender email for automatic emails (By default in php.ini: %s) +MAIN_MAIL_ERRORS_TO=Sender email used for error returns emails sent MAIN_MAIL_AUTOCOPY_TO= Send systematically a hidden carbon-copy of all sent emails to -MAIN_DISABLE_ALL_MAILS=Disable all e-mails sendings (for test purposes or demos) +MAIN_DISABLE_ALL_MAILS=Disable all emails sendings (for test purposes or demos) MAIN_MAIL_SENDMODE=Method to use to send EMails MAIN_MAIL_SMTPS_ID=SMTP ID if authentication required MAIN_MAIL_SMTPS_PW=SMTP Password if authentication required @@ -278,7 +279,7 @@ MAIN_MAIL_EMAIL_STARTTLS= Use TLS (STARTTLS) encrypt MAIN_DISABLE_ALL_SMS=Disable all SMS sendings (for test purposes or demos) MAIN_SMS_SENDMODE=Method to use to send SMS MAIN_MAIL_SMS_FROM=Default sender phone number for Sms sending -MAIN_MAIL_DEFAULT_FROMTYPE=Sender e-mail by default for manual sendings (User email or Company email) +MAIN_MAIL_DEFAULT_FROMTYPE=Sender email by default for manual sendings (User email or Company email) UserEmail=User email CompanyEmail=Company email FeatureNotAvailableOnLinux=Feature not available on Unix like systems. Test your sendmail program locally. @@ -452,8 +453,8 @@ DependsOn=This module need the module(s) RequiredBy=This module is required by module(s) TheKeyIsTheNameOfHtmlField=This is the name of the HTML field. This need to have technical knowledges to read the content of the HTML page to get the key name of a field. PageUrlForDefaultValues=You must enter here the relative url of the page. If you include parameters in URL, the default values will be effective if all parameters are set to same value. Examples: -PageUrlForDefaultValuesCreate=
    For form to create a new thirdparty, it is %s,
    If we want default only if url has some parameter, we can use %s -PageUrlForDefaultValuesList=
    For page that list thirdparties, it is %s,
    If we want default only if url has some parameter, we can use %s +PageUrlForDefaultValuesCreate=
    For form to create a new thirdparty, it is %s,
    If you want default value only if url has some parameter, you can use %s +PageUrlForDefaultValuesList=
    For page that list thirdparties, it is %s,
    If you want default value only if url has some parameter, you can use %s EnableDefaultValues=Enable usage of personalized default values EnableOverwriteTranslation=Enable usage of overwrote translation GoIntoTranslationMenuToChangeThis=A translation has been found for the key with this code, so to change this value, you must edit it fom Home-Setup-translation. @@ -462,6 +463,8 @@ Field=Field ProductDocumentTemplates=Document templates to generate product document FreeLegalTextOnExpenseReports=Free legal text on expense reports WatermarkOnDraftExpenseReports=Watermark on draft expense reports +AttachMainDocByDefault=Set this to 1 if you want to attach main document to email by default (if applicable) +FilesAttachedToEmail=Attach file # Modules Module0Name=Users & groups Module0Desc=Users / Employees and Groups management @@ -584,7 +587,7 @@ Module3100Desc=Add a Skype button into users / third parties / contacts / member Module3200Name=Non Reversible Logs Module3200Desc=Activate log of some business events into a non reversible log. Events are archived in real-time. The log is a table of chained event that can be then read and exported. This module may be mandatory for some countries. Module4000Name=HRM -Module4000Desc=Human resources management (mangement of department, employee contracts and feelings) +Module4000Desc=Human resources management (management of department, employee contracts and feelings) Module5000Name=Multi-company Module5000Desc=Allows you to manage multiple companies Module6000Name=Workflow @@ -1089,6 +1092,11 @@ ShowProfIdInAddress=Show professionnal id with addresses on documents ShowVATIntaInAddress=Hide VAT Intra num with addresses on documents TranslationUncomplete=Partial translation MAIN_DISABLE_METEO=Disable meteo view +MeteoStdMod=Standard mode +MeteoStdModEnabled=Standard mode enabled +MeteoPercentageMod=Percentage mode +MeteoPercentageModEnabled=Percentage mode enabled +MeteoUseMod=Click to use %s TestLoginToAPI=Test login to API ProxyDesc=Some features of Dolibarr need to have an Internet access to work. Define here parameters for this. If the Dolibarr server is behind a Proxy server, those parameters tells Dolibarr how to access Internet through it. ExternalAccess=External access @@ -1400,7 +1408,7 @@ CompressionOfResources=Compression of HTTP responses CompressionOfResourcesDesc=For exemple using the Apache directive "AddOutputFilterByType DEFLATE" TestNotPossibleWithCurrentBrowsers=Such an automatic detection is not possible with current browsers DefaultValuesDesc=You can define/force here the default value you want to get when your create a new record, and/or defaut filters or sort order when your list record. -DefaultCreateForm=Default values for new objects +DefaultCreateForm=Default values for creation form DefaultSearchFilters=Default search filters DefaultSortOrder=Default sort orders DefaultFocus=Default focus fields @@ -1620,7 +1628,7 @@ ProjectsSetup=Project module setup ProjectsModelModule=Project reports document model TasksNumberingModules=Tasks numbering module TaskModelModule=Tasks reports document model -UseSearchToSelectProject=Use autocompletion fields to choose project (instead of using a list box) +UseSearchToSelectProject=Wait you press a key before loading content of project combo list (This may increase performance if you have a large number of project, but it is less convenient) ##### ECM (GED) ##### ##### Fiscal Year ##### AccountingPeriods=Accounting periods @@ -1705,6 +1713,7 @@ MailToSendSupplierInvoice=To send supplier invoice MailToSendContract=To send a contract MailToThirdparty=To send email from third party page MailToMember=To send email from member page +MailToUser=To send email from user page ByDefaultInList=Show by default on list view YouUseLastStableVersion=You use the latest stable version TitleExampleForMajorRelease=Example of message you can use to announce this major release (feel free to use it on your web sites) @@ -1715,6 +1724,7 @@ MultiPriceRuleDesc=When option "Several level of prices per product/service" is ModelModulesProduct=Templates for product documents ToGenerateCodeDefineAutomaticRuleFirst=To be able to generate automatically codes, you must first define a manager to auto define barcode number. SeeSubstitutionVars=See * note for list of possible substitution variables +SeeChangeLog=See ChangeLog file (english only) AllPublishers=All publishers UnknownPublishers=Unknown publishers AddRemoveTabs=Add or remove tabs @@ -1745,7 +1755,11 @@ TypeCdr=Use "None" if the date of payment term is date of invoice plus a delta i BaseCurrency=Reference currency of the company (go into setup of company to change this) WarningNoteModuleInvoiceForFrenchLaw=This module %s is compliant with french laws (Loi Finance 2016). WarningNoteModulePOSForFrenchLaw=This module %s is compliant with french laws (Loi Finance 2016) because module Non Reversible Logs is automatically activated. -WarningInstallationMayBecomeNotCompliantWithLaw=You try to install the module %s that is an external module. Activating an external module means you trust the publisher of the module and you are sure that this module does not alterate negatively the behavior of your application and is compliant with laws of your country (%s). If the module bring a non legal feature, you become responsible for the use of a non legal software. +WarningInstallationMayBecomeNotCompliantWithLaw=You try to install the module %s that is an external module. Activating an external module means you trust the publisher of the module and you are sure that this module does not alterate negatively the behavior of your application and is compliant with laws of your country (%s). If the module bring a non legal feature, you become responsible for the use of a non legal software. +MAIN_PDF_MARGIN_LEFT=Left margin on PDF +MAIN_PDF_MARGIN_RIGHT=Right margin on PDF +MAIN_PDF_MARGIN_TOP=Top margin on PDF +MAIN_PDF_MARGIN_BOTTOM=Bottom margin on PDF ##### Resource #### ResourceSetup=Configuration du module Resource UseSearchToSelectResource=Use a search form to choose a resource (rather than a drop-down list). diff --git a/htdocs/langs/en_US/agenda.lang b/htdocs/langs/en_US/agenda.lang index 88c6bbc54f5..116fc189732 100644 --- a/htdocs/langs/en_US/agenda.lang +++ b/htdocs/langs/en_US/agenda.lang @@ -12,6 +12,7 @@ Event=Event Events=Events EventsNb=Number of events ListOfActions=List of events +EventReports=Event reports Location=Location ToUserOfGroup=To any user in group EventOnFullDay=Event on all day(s) diff --git a/htdocs/langs/en_US/banks.lang b/htdocs/langs/en_US/banks.lang index caed4498f3b..d45c0c15c1c 100644 --- a/htdocs/langs/en_US/banks.lang +++ b/htdocs/langs/en_US/banks.lang @@ -157,4 +157,6 @@ NewVariousPayment=New miscellaneous payments VariousPayment=Miscellaneous payments VariousPayments=Miscellaneous payments ShowVariousPayment=Show miscellaneous payments -AddVariousPayment=Add miscellaneous payments \ No newline at end of file +AddVariousPayment=Add miscellaneous payments +YourSEPAMandate=Your SEPA mandate +FindYourSEPAMandate=This is your SEPA mandate to authorize our company to make direct debit order to your bank. Thanks to return it signed (scan of the signed document) or sent it by mail to diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index f093726ed4b..b3f9c030d3e 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -337,6 +337,7 @@ NextDateToExecution=Date for next invoice generation DateLastGeneration=Date of latest generation MaxPeriodNumber=Max nb of invoice generation NbOfGenerationDone=Nb of invoice generation already done +NbOfGenerationDoneShort=Nb of generation done MaxGenerationReached=Maximum nb of generations reached InvoiceAutoValidate=Validate invoices automatically GeneratedFromRecurringInvoice=Generated from template recurring invoice %s diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index a7e7c67ae9c..7cff22df092 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -29,6 +29,7 @@ AliasNameShort=Alias name Companies=Companies CountryIsInEEC=Country is inside European Economic Community ThirdPartyName=Third party name +ThirdPartyEmail=Third party email ThirdParty=Third party ThirdParties=Third parties ThirdPartyProspects=Prospects @@ -266,6 +267,7 @@ CustomerAbsoluteDiscountShort=Absolute discount CompanyHasRelativeDiscount=This customer has a default discount of %s%% CompanyHasNoRelativeDiscount=This customer has no relative discount by default CompanyHasAbsoluteDiscount=This customer has discount available (credits notes or down payments) for %s %s +CompanyHasDownPaymentOrCommercialDiscount=This customer has discount available (commercial, down payments) for %s %s CompanyHasCreditNote=This customer still has credit notes for %s %s CompanyHasNoAbsoluteDiscount=This customer has no discount credit available CustomerAbsoluteDiscountAllUsers=Absolute discounts (granted by all users) diff --git a/htdocs/langs/en_US/contracts.lang b/htdocs/langs/en_US/contracts.lang index 63d3c403e50..e0642b27c02 100644 --- a/htdocs/langs/en_US/contracts.lang +++ b/htdocs/langs/en_US/contracts.lang @@ -88,7 +88,8 @@ ContactNameAndSignature=For %s, name and signature: OnlyLinesWithTypeServiceAreUsed=Only lines with type "Service" will be cloned. CloneContract=Clone contract ConfirmCloneContract=Are you sure you want to clone the contract %s? - +LowerDateEndPlannedShort=Lower planned end date of active services +SendContractRef=Contract information __REF__ ##### Types de contacts ##### TypeContact_contrat_internal_SALESREPSIGN=Sales representative signing contract TypeContact_contrat_internal_SALESREPFOLL=Sales representative following-up contract diff --git a/htdocs/langs/en_US/interventions.lang b/htdocs/langs/en_US/interventions.lang index b151565f3a3..15415a7fcd5 100644 --- a/htdocs/langs/en_US/interventions.lang +++ b/htdocs/langs/en_US/interventions.lang @@ -53,6 +53,7 @@ UseDateWithoutHourOnFichinter=Hides hours and minutes off the date field for int InterventionStatistics=Statistics of interventions NbOfinterventions=Nb of intervention cards NumberOfInterventionsByMonth=Nb of intervention cards by month (date of validation) +AmountOfInteventionNotIncludedByDefault=Amount of intervention is not included by default into profit (in most cases, timesheets are used to count time spent). Add option PROJECT_INCLUDE_INTERVENTION_AMOUNT_IN_PROFIT to 1 into home-setup-other to include them. ##### Exports ##### InterId=Intervention id InterRef=Intervention ref. diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang index 0caae25c1d5..ccf52302e9a 100644 --- a/htdocs/langs/en_US/mails.lang +++ b/htdocs/langs/en_US/mails.lang @@ -115,7 +115,7 @@ DeliveryReceipt=Delivery Ack. YouCanUseCommaSeparatorForSeveralRecipients=You can use the comma separator to specify several recipients. TagCheckMail=Track mail opening TagUnsubscribe=Unsubscribe link -TagSignature=Signature sending user +TagSignature=Signature of sending user EMailRecipient=Recipient EMail TagMailtoEmail=Recipient EMail (including html "mailto:" link) NoEmailSentBadSenderOrRecipientEmail=No email sent. Bad sender or recipient email. Verify user profile. diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 7475d1194eb..91d642bef7e 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -27,6 +27,7 @@ DatabaseConnection=Database connection NoTemplateDefined=No template available for this email type AvailableVariables=Available substitution variables NoTranslation=No translation +Translation=Translation NoRecordFound=No record found NoRecordDeleted=No record deleted NotEnoughDataYet=Not enough data @@ -262,6 +263,7 @@ DateBuild=Report build date DatePayment=Date of payment DateApprove=Approving date DateApprove2=Approving date (second approval) +RegistrationDate=Registration date UserCreation=Creation user UserModification=Modification user UserCreationShort=Creat. user @@ -376,12 +378,15 @@ VATIN=IGST VATs=Sales taxes VATINs=IGST taxes LT1=Sales tax 2 +LT1Type=Sales tax 2 type LT2=Sales tax 3 +LT2Type=Sales tax 3 type LT1ES=RE LT2ES=IRPF LT1IN=CGST LT2IN=SGST VATRate=Tax Rate +DefaultTaxRate=Default tax rate Average=Average Sum=Sum Delta=Delta @@ -593,6 +598,7 @@ Undo=Undo Redo=Redo ExpandAll=Expand all UndoExpandAll=Undo expand +SeeAll=See all Reason=Reason FeatureNotYetSupported=Feature not yet supported CloseWindow=Close window @@ -767,6 +773,7 @@ Genderwoman=Woman ViewList=List view Mandatory=Mandatory Hello=Hello +GoodBye=GoodBye Sincerely=Sincerely DeleteLine=Delete line ConfirmDeleteLine=Are you sure you want to delete this line? @@ -868,3 +875,8 @@ SearchIntoContracts=Contracts SearchIntoCustomerShipments=Customer shipments SearchIntoExpenseReports=Expense reports SearchIntoLeaves=Leaves +CommentLink=Comments +NbComments=Number of comments +CommentPage=Comments space +CommentAdded=Comment added +CommentDeleted=Comment deleted diff --git a/htdocs/langs/en_US/modulebuilder.lang b/htdocs/langs/en_US/modulebuilder.lang index e5e662a7852..1ec51989ee6 100644 --- a/htdocs/langs/en_US/modulebuilder.lang +++ b/htdocs/langs/en_US/modulebuilder.lang @@ -12,7 +12,7 @@ ObjectKey=Object key ModuleInitialized=Module initialized FilesForObjectInitialized=Files for new object '%s' initialized FilesForObjectUpdated=Files for object '%s' updated (.sql files and .class.php file) -ModuleBuilderDescdescription=Enter here all general information that describe your module +ModuleBuilderDescdescription=Enter here all general information that describe your module. ModuleBuilderDescspecifications=You can enter here a long text to describe the specifications of your module that is not already structured into other tabs. So you have within easy reach all the rules to develop. Also this text content will be included into the generated documentation (see last tab). You can use Markdown format, but it is recommanded to use Asciidoc format (Comparison between .md and .asciidoc: http://asciidoctor.org/docs/user-manual/#compared-to-markdown) ModuleBuilderDescobjects=Define here the objects you want to manage with your module. A CRUD DAO class, SQL files, page to list record of objects, to create/edit/view a record and an API will be generated. ModuleBuilderDescmenus=This tab is dedicated to define menu entries provided by your module. @@ -77,5 +77,8 @@ SpecDefDesc=Enter here all documentation you want to provide with your module th LanguageDefDesc=Enter in this files, all the key and the translation for each language file. MenusDefDesc=Define here the menus provided by your module (once defined, they are visible into the menu editor %s) PermissionsDefDesc=Define here the new permissions provided by your module (once defined, they are visible into the default permissions setup %s) -HooksDefDesc=Define in the module_parts['hooks'] property in the module descriptor the context of hooks you want to manage (list of contexts can be found by a search on 'initHooks(' in core code).
    Edit the hook file to add code of your hooked functions (hookable functions can be found by a search on 'executeHooks' in core code). -TriggerDefDesc=Define in the trigger file the code you want to execute for each business event executed +HooksDefDesc=Define in the module_parts['hooks'] property, in the module descriptor, the context of hooks you want to manage (list of contexts can be found by a search on 'initHooks(' in core code).
    Edit the hook file to add code of your hooked functions (hookable functions can be found by a search on 'executeHooks' in core code). +TriggerDefDesc=Define in the trigger file the code you want to execute for each business event executed. +SeeIDsInUse=See IDs in use in your installation +SeeReservedIDsRangeHere=See range of reserved IDs +ToolkitForDevelopers=Toolkit for Dolibarr developers \ No newline at end of file diff --git a/htdocs/langs/en_US/other.lang b/htdocs/langs/en_US/other.lang index f1cca6a1696..e1270533ae2 100644 --- a/htdocs/langs/en_US/other.lang +++ b/htdocs/langs/en_US/other.lang @@ -76,19 +76,19 @@ MaxSize=Maximum size AttachANewFile=Attach a new file/document LinkedObject=Linked object NbOfActiveNotifications=Number of notifications (nb of recipient emails) -PredefinedMailTest=This is a test mail sent to __EMAIL__.\nThe two lines are separated by a carriage return.\n\n__SIGNATURE__ -PredefinedMailTestHtml=This is a test mail (the word test must be in bold).
    The two lines are separated by a carriage return.

    __SIGNATURE__ -PredefinedMailContentSendInvoice=__CONTACTCIVNAME__\n\nYou will find here the invoice __REF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendInvoiceReminder=__CONTACTCIVNAME__\n\nWe would like to warn you that the invoice __REF__ seems to not being payed. So this is the invoice in attachment again, as a reminder.\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendProposal=__CONTACTCIVNAME__\n\nYou will find here the commercial proposal __PROPREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendSupplierProposal=__CONTACTCIVNAME__\n\nYou will find here the price request __REF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendOrder=__CONTACTCIVNAME__\n\nYou will find here the order __ORDERREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendSupplierOrder=__CONTACTCIVNAME__\n\nYou will find here our order __ORDERREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendSupplierInvoice=__CONTACTCIVNAME__\n\nYou will find here the invoice __REF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendShipping=__CONTACTCIVNAME__\n\nYou will find here the shipping __SHIPPINGREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentSendFichInter=__CONTACTCIVNAME__\n\nYou will find here the intervention __FICHINTERREF__\n\n__PERSONALIZED__Sincerely\n\n__SIGNATURE__ -PredefinedMailContentThirdparty=__CONTACTCIVNAME__\n\n__PERSONALIZED__\n\n__SIGNATURE__ -PredefinedMailContentUser=aa__PERSONALIZED__\n\n__SIGNATURE__ +PredefinedMailTest=__(Hello)__\nThis is a test mail sent to __EMAIL__.\nThe two lines are separated by a carriage return.\n\n__USER_SIGNATURE__ +PredefinedMailTestHtml=__(Hello)__\nThis is a test mail (the word test must be in bold).
    The two lines are separated by a carriage return.

    __USER_SIGNATURE__ +PredefinedMailContentSendInvoice=__(Hello)__\n\nYou will find here the invoice __REF__\n\n__ONLINE_PAYMENT_URL__\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendInvoiceReminder=__(Hello)__\n\nWe would like to warn you that the invoice __REF__ seems to not be payed. So this is the invoice in attachment again, as a reminder.\n\n__ONLINE_PAYMENT_URL__\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendProposal=__(Hello)__\n\nYou will find here the commercial proposal __PREF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendSupplierProposal=__(Hello)__\n\nYou will find here the price request __REF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendOrder=__(Hello)__\n\nYou will find here the order __REF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendSupplierOrder=__(Hello)__\n\nYou will find here our order __REF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendSupplierInvoice=__(Hello)__\n\nYou will find here the invoice __REF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendShipping=__(Hello)__\n\nYou will find here the shipping __REF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentSendFichInter=__(Hello)__\n\nYou will find here the intervention __REF__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentThirdparty=__(Hello)__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ +PredefinedMailContentUser=__(Hello)__\n\n\n__(Sincerely)__\n\n__USER_SIGNATURE__ DemoDesc=Dolibarr is a compact ERP/CRM supporting several business modules. A demo showcasing all modules makes no sense as this scenario never occurs (several hundred available). So, several demo profiles are available. ChooseYourDemoProfil=Choose the demo profile that best suits your needs... ChooseYourDemoProfilMore=...or build your own profile
    (manual module selection) @@ -186,6 +186,7 @@ EMailTextInterventionAddedContact=A newintervention %s has been assigned to you. EMailTextInterventionValidated=The intervention %s has been validated. EMailTextInvoiceValidated=The invoice %s has been validated. EMailTextProposalValidated=The proposal %s has been validated. +EMailTextProposalClosedSigned=The proposal %s has been closed signed. EMailTextOrderValidated=The order %s has been validated. EMailTextOrderApproved=The order %s has been approved. EMailTextOrderValidatedBy=The order %s has been recorded by %s. diff --git a/htdocs/langs/en_US/products.lang b/htdocs/langs/en_US/products.lang index b324154e9d0..55138235335 100644 --- a/htdocs/langs/en_US/products.lang +++ b/htdocs/langs/en_US/products.lang @@ -100,7 +100,6 @@ ParentProductsNumber=Number of parent packaging product ParentProducts=Parent products IfZeroItIsNotAVirtualProduct=If 0, this product is not a virtual product IfZeroItIsNotUsedByVirtualProduct=If 0, this product is not used by any virtual product -Translation=Translation KeywordFilter=Keyword filter CategoryFilter=Category filter ProductToAddSearch=Search product to add diff --git a/htdocs/langs/en_US/projects.lang b/htdocs/langs/en_US/projects.lang index 408c3db5e7a..f9eb6c00477 100644 --- a/htdocs/langs/en_US/projects.lang +++ b/htdocs/langs/en_US/projects.lang @@ -210,8 +210,4 @@ OppStatusLOST=Lost Budget=Budget # Comments trans AllowCommentOnTask=Allow user comments on tasks -TaskCommentLinks=Comments -TaskNbComments=Number of comments -TaskComment=Task's comments space -CommentAdded=Comment added -CommentDeleted=Comment deleted +AllowCommentOnProject=Allow user comments on projects diff --git a/htdocs/langs/en_US/sendings.lang b/htdocs/langs/en_US/sendings.lang index fcd28cc9f56..47012406b74 100644 --- a/htdocs/langs/en_US/sendings.lang +++ b/htdocs/langs/en_US/sendings.lang @@ -18,11 +18,13 @@ SendingCard=Shipment card NewSending=New shipment CreateShipment=Create shipment QtyShipped=Qty shipped +QtyShippedShort=Qty ship. QtyPreparedOrShipped=Qty prepared or shipped QtyToShip=Qty to ship QtyReceived=Qty received QtyInOtherShipments=Qty in other shipments KeepToShip=Remain to ship +KeepToShipShort=Remain OtherSendingsForSameOrder=Other shipments for this order SendingsAndReceivingForSameOrder=Shipments and receipts for this order SendingsToValidate=Shipments to validate diff --git a/htdocs/langs/en_US/users.lang b/htdocs/langs/en_US/users.lang index 1a9b5cde8d0..3ae08747510 100644 --- a/htdocs/langs/en_US/users.lang +++ b/htdocs/langs/en_US/users.lang @@ -96,7 +96,8 @@ HierarchicView=Hierarchical view UseTypeFieldToChange=Use field Type to change OpenIDURL=OpenID URL LoginUsingOpenID=Use OpenID to login -WeeklyHours=Weekly hours +WeeklyHours=Hours worked (per week) +ExpectedWorkedHours=Expected worked hours per week ColorUser=Color of the user DisabledInMonoUserMode=Disabled in maintenance mode UserAccountancyCode=User accounting code diff --git a/htdocs/langs/en_US/website.lang b/htdocs/langs/en_US/website.lang index e42504f4706..4352c480fc0 100644 --- a/htdocs/langs/en_US/website.lang +++ b/htdocs/langs/en_US/website.lang @@ -4,9 +4,11 @@ WebsiteSetupDesc=Create here as much entry as number of different websites you n DeleteWebsite=Delete website ConfirmDeleteWebsite=Are you sure you want to delete this web site. All its pages and content will also be removed. WEBSITE_PAGENAME=Page name/alias -WEBSITE_HTML_HEADER=HTML Header +WEBSITE_HTML_HEADER=HTML Header (common to all pages) +HtmlHeaderPage=HTML specific header for ppage WEBSITE_CSS_URL=URL of external CSS file -WEBSITE_CSS_INLINE=CSS content +WEBSITE_CSS_INLINE=CSS file content (common to all pages) +WEBSITE_JS_INLINE=Javascript file content (common to all pages) WEBSITE_ROBOT=Robot file (robots.txt) WEBSITE_HTACCESS=Web site .htaccess file PageNameAliasHelp=Name or alias of the page.
    This alias is also used to forge a SEO URL when website is ran from a Virtual host of a Web server (like Apacke, Nginx, ...). Use the button "%s" to edit this alias. @@ -37,7 +39,7 @@ VirtualHostUrlNotDefined=URL of the virtual host served by external web server n NoPageYet=No pages yet SyntaxHelp=Help on specific syntax tips YouCanEditHtmlSourceckeditor=You can edit HTML source code using the "Source" button in editor. -YouCanEditHtmlSource=You can include PHP code into this source using tags <?php ?>. The following global variables are available: $conf, $langs, $db, $mysoc, $user, $website.

    You can also include content of another Page/Container with the following syntax: <?php dolIncludeHtmlContent($websitekey.'/contentaliastoinclude.php'); ?>

    To include a link to download a file stored into the documents directory, use the document.php wrapper:
    Example, for a file into documents/ecm (need to be logged), syntax is:
    <a href="/document.php?modulepart=ecm&file=reldir/filename.ext">.
    for a file into documents/media (open public access), syntax is:
    <a href="/document.php?modulepart=medias[&hashp=publicsharekey if modulepart != medias]">.

    To include an image stored into the documents directory, use the viewimage.php wrapper:
    Example, for an image into documents/media (open access), syntax is:
    <a href="/viewimage.php?modulepart=medias&file=filename.ext">. +YouCanEditHtmlSource=You can include PHP code into this source using tags <?php ?>. The following global variables are available: $conf, $langs, $db, $mysoc, $user, $website.

    You can also include content of another Page/Container with the following syntax:
    <?php dolIncludeHtmlContent($websitekey.'/alias_of_content_to_include.php'); ?>

    To include a link to download a file stored into the documents directory, use the document.php wrapper:
    Example, for a file into documents/ecm (need to be logged), syntax is:
    <a href="/document.php?modulepart=ecm&file=relative_dir/filename.ext">
    For same file into documents/ecm (open access using the sharing hash key), syntax is:
    <a href="/document.php?modulepart=ecm&file=relative_dir/filename.ext&hashp=publicsharekeyoffile">
    For a file into documents/media (open directory for public access), syntax is:
    <a href="/document.php?modulepart=medias&file=relative_dir/filename.ext">

    To include an image stored into the documents directory, use the viewimage.php wrapper:
    Example, for an image into documents/media (open access), syntax is:
    <a href="/viewimage.php?modulepart=medias&file=relative_dir/filename.ext"> ClonePage=Clone page/container CloneSite=Clone site ConfirmClonePage=Please enter code/alias of new page and if it is a translation of the cloned page. @@ -49,3 +51,4 @@ CreateByFetchingExternalPage=Create page/container by fetching page from externa OrEnterPageInfoManually=Or create empty page from scratch... FetchAndCreate=Fetch and Create ExportSite=Export site +IDOfPage=Id of page \ No newline at end of file diff --git a/htdocs/langs/en_US/withdrawals.lang b/htdocs/langs/en_US/withdrawals.lang index 308987575f5..6b1babf9d88 100644 --- a/htdocs/langs/en_US/withdrawals.lang +++ b/htdocs/langs/en_US/withdrawals.lang @@ -55,7 +55,9 @@ StatusMotif5=RIB unusable StatusMotif6=Account without balance StatusMotif7=Judicial Decision StatusMotif8=Other reason -CreateAll=Withdraw all +CreateForSepaFRST=Create direct debit file (SEPA FRST) +CreateForSepaRCUR=Create direct debit file (SEPA RCUR) +CreateAll=Create direct debit file (all) CreateGuichet=Only office CreateBanque=Only bank OrderWaiting=Waiting for treatment diff --git a/htdocs/langs/fr_FR/companies.lang b/htdocs/langs/fr_FR/companies.lang index 67ef632a010..ffed13c0c69 100644 --- a/htdocs/langs/fr_FR/companies.lang +++ b/htdocs/langs/fr_FR/companies.lang @@ -101,15 +101,15 @@ Gencod=Code-barres ProfId1Short=Id. prof. 1 ProfId2Short=Id. prof. 2 ProfId3Short=Id. prof. 3 -ProfId4Short=Id. prof. 4 -ProfId5Short=Id. prof. 5 -ProfId6Short=Id prof. 6 +ProfId4Short=- +ProfId5Short=- +ProfId6Short=- ProfId1=Identifiant professionnel 1 ProfId2=Identifiant professionnel 2 ProfId3=Identifiant professionnel 3 -ProfId4=Identifiant professionnel 4 -ProfId5=Identifiant professionnel 5 -ProfId6=Identifiant professionnel 6 +ProfId4=- +ProfId5=- +ProfId6=- ProfId1AR=Id. prof. 1 (CUIT/CUIL) ProfId2AR=Id. prof. 2 (Revenus brutes) ProfId3AR=- diff --git a/htdocs/langs/fr_FR/main.lang b/htdocs/langs/fr_FR/main.lang index 6a6c80a78bf..83a9c889b97 100644 --- a/htdocs/langs/fr_FR/main.lang +++ b/htdocs/langs/fr_FR/main.lang @@ -771,6 +771,7 @@ Calendar=Calendrier GroupBy=Grouper par... ViewFlatList=Voir vue liste RemoveString=Supprimer la chaine '%s' +Translation=Traduction SomeTranslationAreUncomplete=Certains languages pourraient n'être que partiellement traduis, ou contenir des erreurs. Si vous en détectez, vous pouvez les corriger en vous enregistrant sur https://transifex.com/projects/p/dolibarr/ DirectDownloadLink=Lien de téléchargement direct Download=Téléchargement @@ -842,3 +843,8 @@ SearchIntoContracts=Contrats SearchIntoCustomerShipments=Expéditions clients SearchIntoExpenseReports=Notes de frais SearchIntoLeaves=Congés +CommentLink=Commentaires +NbComments=Nombre de commentaires +CommentPage=Espace commentaires +CommentAdded=Commentaire ajouté avec succès +CommentDeleted=Commentaire supprimé avec succès diff --git a/htdocs/langs/fr_FR/other.lang b/htdocs/langs/fr_FR/other.lang index 346fcf42934..71f9aae8490 100644 --- a/htdocs/langs/fr_FR/other.lang +++ b/htdocs/langs/fr_FR/other.lang @@ -180,6 +180,7 @@ EMailTextInterventionAddedContact=Une nouvelle intervention %s vous a été assi EMailTextInterventionValidated=La fiche intervention %s vous concernant a été validée. EMailTextInvoiceValidated=La facture %s vous concernant a été validée. EMailTextProposalValidated=La proposition commerciale %s vous concernant a été validée. +EMailTextProposalClosedSigned=La proposition commerciale %s a été fermée signée. EMailTextOrderValidated=La commande %s vous concernant a été validée. EMailTextOrderApproved=La commande %s a été approuvée. EMailTextOrderValidatedBy=La commande %s a été enregistrée par %s diff --git a/htdocs/langs/fr_FR/products.lang b/htdocs/langs/fr_FR/products.lang index ee4c7c328cf..ca61fff3460 100644 --- a/htdocs/langs/fr_FR/products.lang +++ b/htdocs/langs/fr_FR/products.lang @@ -100,7 +100,6 @@ ParentProductsNumber=Nbre de produits virtuels/packages parent ParentProducts=Produits parents IfZeroItIsNotAVirtualProduct=Si 0, ce produit n'est pas un produit virtuel IfZeroItIsNotUsedByVirtualProduct=Si 0, ce produit n'est pas utilisé par un produit virtuel -Translation=Traduction KeywordFilter=Filtre par mot-clé CategoryFilter=Filtre par catégorie ProductToAddSearch=Recherche des produits à ajouter diff --git a/htdocs/langs/fr_FR/projects.lang b/htdocs/langs/fr_FR/projects.lang index 154c1138ab9..c235230eb2f 100644 --- a/htdocs/langs/fr_FR/projects.lang +++ b/htdocs/langs/fr_FR/projects.lang @@ -209,8 +209,4 @@ OppStatusLOST=Perdu Budget=Budget #Comments trans AllowCommentOnTask=Autoriser les commentaires entre utilisateurs sur les tâches -TaskCommentLinks=Commentaires -TaskNbComments=Nombre de commentaires -TaskComment=Tâches espace commentaires -CommentAdded=Commentaire ajouté avec succès -CommentDeleted=Commentaire supprimé avec succès +AllowCommentOnProject=Autoriser les commentaires entre utilisateurs sur les projets diff --git a/htdocs/livraison/card.php b/htdocs/livraison/card.php index d6ebf7b68aa..84cd7c8899d 100644 --- a/htdocs/livraison/card.php +++ b/htdocs/livraison/card.php @@ -44,7 +44,7 @@ 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'; } - + $langs->load("sendings"); $langs->load("bills"); @@ -223,7 +223,7 @@ if ($action == 'update_extras_line') { $array_options=array(); $num=count($object->lines); - + for ($i = 0; $i < $num; $i++) { // Extrafields @@ -236,7 +236,7 @@ if ($action == 'update_extras_line') unset($_POST["options_" . $key]); } } - + $ret = $object->update_line($object->lines[$i]->id,$array_options[$i]); // extrafields update if ($ret < 0) { @@ -305,7 +305,7 @@ $formfile = new FormFile($db); if ($action == 'create') // Seems to no be used { - + } else /* *************************************************************************** */ @@ -333,16 +333,16 @@ else $head=delivery_prepare_head($object); - + print '
    '; print ''; print ''; print ''; print ''; print ''; - + dol_fiche_head($head, 'delivery', $langs->trans("Shipment"), 0, 'sending'); - + /* * Confirmation de la suppression * @@ -367,7 +367,7 @@ else /* * Livraison */ - + if ($typeobject == 'commande' && $expedition->origin_id > 0 && ! empty($conf->commande->enabled)) { $objectsrc=new Commande($db); @@ -380,8 +380,8 @@ else } // Shipment card - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
    '; // Ref customer shipment $morehtmlref.=$form->editfieldkey("RefCustomer", '', $expedition->ref_customer, $expedition, $user->rights->expedition->creer, 'string', '', 0, 1); @@ -422,17 +422,17 @@ else } } $morehtmlref.='
    '; - + $morehtmlright = $langs->trans("StatusReceipt").' : '.$object->getLibStatut(6).'
    '; - + dol_banner_tab($expedition, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', $morehtmlright); - - + + print '
    '; print '
    '; - + print ''; - + // Shipment /* if (($object->origin == 'shipment' || $object->origin == 'expedition') && $object->origin_id > 0) @@ -459,7 +459,7 @@ else print ''; print ""; */ - + // Document origine if ($typeobject == 'commande' && $expedition->origin_id && ! empty($conf->commande->enabled)) { @@ -535,7 +535,7 @@ else print ''; } - /* A delivery note should be just more properties of a shipment, so notes are on shipment + /* A delivery note should be just more properties of a shipment, so notes are on shipment // Note Public print ''; print ''; print ''; } - + // Other attributes if ($action = 'create_delivery') { // copy from expedition @@ -579,7 +579,7 @@ else print "
    '.$soc->getNomUrl(1).'
    '.$langs->trans("NotePublic").''; @@ -563,7 +563,7 @@ else print ''.$entrepot->libelle.'

    \n"; print '
    '; - + /* * Lignes produits */ @@ -602,7 +602,7 @@ else $var=true; while ($i < $num_prod) { - + print '
    '.$object->lines[$i]->qty_shipped.'
    \n"; - + dol_fiche_end(); //if ($object->statut == 0) // only if draft // print '
    '; - + print ''; - + /* * Boutons actions @@ -706,7 +706,7 @@ else { print '
    '; - if ($object->statut == 0 && $num_prod > 0) + if ($object->statut == 0 && $num_prod > 0) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->livraison->creer)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->livraison_advance->validate))) diff --git a/htdocs/livraison/class/livraison.class.php b/htdocs/livraison/class/livraison.class.php index 56ffa78f429..837b0af77f5 100644 --- a/htdocs/livraison/class/livraison.class.php +++ b/htdocs/livraison/class/livraison.class.php @@ -295,13 +295,13 @@ class Livraison extends CommonObject //Incoterms $this->fk_incoterms = $obj->fk_incoterms; - $this->location_incoterms = $obj->location_incoterms; + $this->location_incoterms = $obj->location_incoterms; $this->libelle_incoterms = $obj->libelle_incoterms; $this->db->free($result); if ($this->statut == 0) $this->brouillon = 1; - - + + // Retrieve all extrafields for delivery // fetch optionals attributes and labels require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; @@ -524,7 +524,7 @@ class Livraison extends CommonObject $this->fk_delivery_address = $expedition->fk_delivery_address; $this->socid = $expedition->socid; $this->ref_customer = $expedition->ref_customer; - + //Incoterms $this->fk_incoterms = $expedition->fk_incoterms; $this->location_incoterms = $expedition->location_incoterms; @@ -543,26 +543,26 @@ class Livraison extends CommonObject { global $conf; $error = 0; - + if ($id > 0 && !$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used { $livraisonline = new LivraisonLigne($this->db); $livraisonline->array_options=$array_options; $livraisonline->id=$id; $result=$livraisonline->insertExtraFields(); - + if ($result < 0) { $this->error[]=$livraisonline->error; $error++; } } - + if (! $error) return 1; else return -1; } - - + + /** * Add line * @@ -696,26 +696,36 @@ class Livraison extends CommonObject /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @return string Chaine avec URL + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL */ - function getNomUrl($withpicto=0) + function getNomUrl($withpicto=0, $save_lastsearch_value=-1) { global $langs; $result=''; - $urlOption=''; - $label=$langs->trans("ShowReceiving").': '.$this->ref; - - - $link = ''; - $linkend=''; - $picto='sending'; - if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + $label=$langs->trans("ShowReceiving").': '.$this->ref; + + $url=DOL_URL_ROOT.'/livraison/card.php?id='.$this->id; + + //if ($option !== 'nolink') + //{ + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + //} + + + $linkstart = ''; + $linkend=''; + + if ($withpicto) $result.=($linkstart.img_object($label, $picto, 'class="classfortooltip"').$linkend); if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$link.$this->ref.$linkend; + $result.=$linkstart.$this->ref.$linkend; return $result; } @@ -1052,7 +1062,7 @@ class Livraison extends CommonObject class LivraisonLigne extends CommonObjectLine { var $db; - + // From llx_expeditiondet var $qty; var $qty_asked; @@ -1075,7 +1085,7 @@ class LivraisonLigne extends CommonObjectLine public $product_ref; public $product_label; - + public $element='livraisondet'; public $table_element='livraisondet'; diff --git a/htdocs/loan/card.php b/htdocs/loan/card.php index 1f76d705305..2edf3c34547 100644 --- a/htdocs/loan/card.php +++ b/htdocs/loan/card.php @@ -642,6 +642,7 @@ if ($id > 0) $sql.= " AND p.fk_loan = l.rowid"; $sql.= " AND l.entity = ".$conf->entity; $sql.= " AND p.fk_typepayment = c.id"; + $sql.= " AND c.entity = " . getEntity('c_paiement'); $sql.= " ORDER BY dp DESC"; //print $sql; diff --git a/htdocs/loan/class/loanschedule.class.php b/htdocs/loan/class/loanschedule.class.php index fb6df8fcb6c..c5794b52daf 100644 --- a/htdocs/loan/class/loanschedule.class.php +++ b/htdocs/loan/class/loanschedule.class.php @@ -179,6 +179,7 @@ class LoanSchedule extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX.$this->table_element." as t)"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepayment = pt.id"; + $sql.= " AND pt.entity = " . getEntity('c_paiement'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php index 52c822e54c1..836acd082e1 100644 --- a/htdocs/loan/class/paymentloan.class.php +++ b/htdocs/loan/class/paymentloan.class.php @@ -178,6 +178,7 @@ class PaymentLoan extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as pt, ".MAIN_DB_PREFIX."payment_loan as t)"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepayment = pt.id"; + $sql.= " AND pt.entity = " . getEntity('c_paiement'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 8f5c5fb11bd..77af64afa3d 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -38,34 +38,34 @@ $micro_start_time=0; if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) { - list($usec, $sec) = explode(" ", microtime()); - $micro_start_time=((float) $usec + (float) $sec); - // Add Xdebug code coverage - //define('XDEBUGCOVERAGE',1); - if (defined('XDEBUGCOVERAGE')) { - xdebug_start_code_coverage(); - } + list($usec, $sec) = explode(" ", microtime()); + $micro_start_time=((float) $usec + (float) $sec); + // Add Xdebug code coverage + //define('XDEBUGCOVERAGE',1); + if (defined('XDEBUGCOVERAGE')) { + xdebug_start_code_coverage(); + } } // Removed magic_quotes if (function_exists('get_magic_quotes_gpc')) // magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5 { - if (get_magic_quotes_gpc()) - { - // Forcing parameter setting magic_quotes_gpc and cleaning parameters - // (Otherwise he would have for each position, condition - // Reading stripslashes variable according to state get_magic_quotes_gpc). - // Off mode recommended (just do $db->escape for insert / update). - function stripslashes_deep($value) - { - return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value)); - } - $_GET = array_map('stripslashes_deep', $_GET); - $_POST = array_map('stripslashes_deep', $_POST); - $_FILES = array_map('stripslashes_deep', $_FILES); - //$_COOKIE = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql - @set_magic_quotes_runtime(0); - } + if (get_magic_quotes_gpc()) + { + // Forcing parameter setting magic_quotes_gpc and cleaning parameters + // (Otherwise he would have for each position, condition + // Reading stripslashes variable according to state get_magic_quotes_gpc). + // Off mode recommended (just do $db->escape for insert / update). + function stripslashes_deep($value) + { + return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value)); + } + $_GET = array_map('stripslashes_deep', $_GET); + $_POST = array_map('stripslashes_deep', $_POST); + $_FILES = array_map('stripslashes_deep', $_FILES); + //$_COOKIE = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql + @set_magic_quotes_runtime(0); + } } /** @@ -77,44 +77,44 @@ if (function_exists('get_magic_quotes_gpc')) // magic_quotes_* deprecated in PHP */ function test_sql_and_script_inject($val, $type) { - $inj = 0; - // For SQL Injection (only GET and POST are used to be included into bad escaped SQL requests) - if ($type != 2) - { - $inj += preg_match('/delete\s+from/i', $val); - $inj += preg_match('/create\s+table/i', $val); - $inj += preg_match('/update.+set.+=/i', $val); - $inj += preg_match('/insert\s+into/i', $val); - $inj += preg_match('/select.+from/i', $val); - $inj += preg_match('/union.+select/i', $val); - $inj += preg_match('/into\s+(outfile|dumpfile)/i', $val); - $inj += preg_match('/(\.\.%2f)+/i', $val); - } - // For XSS Injection done by adding javascript with script - // This is all cases a browser consider text is javascript: - // When it found ' - $inj += preg_match('/onerror\s*=/i', $val); // onerror can be set on img or any html tag like - $inj += preg_match('/onfocus\s*=/i', $val); // onfocus can be set on input text html tag like - $inj += preg_match('/onload\s*=/i', $val); // onload can be set on svg tag or other tag like body - //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val); // To lock event handlers onAbort(), ... + if (! defined('NOSTYLECHECK')) $inj += preg_match('/'."\n"; + //var_dump($pagecsscontent); + + //print dol_escape_htmltag($tmp);exit; + $objectpage->htmlheader .= $pagecsscontent; + + + // Now loop to fetch all images + $tmp = $objectpage->content; + + getAllImages($object, $objectpage, $urltograb, $tmp, $action, 1); + + //print dol_escape_htmltag($tmp);exit; + $objectpage->content = $tmp; + + $objectpage->grabbed_from = $urltograb; + } + } + else + { + $objectpage->title = GETPOST('WEBSITE_TITLE','alpha'); + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME','alpha'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION','alpha'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS','alpha'); + $objectpage->lang = GETPOST('WEBSITE_LANG','aZ09'); + $objectpage->htmlheader = GETPOST('htmlheader','none'); + } + + if (! $error) + { + if (empty($objectpage->pageurl)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); + $error++; + $action='create'; + } + else if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) + { + setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); + $error++; + $action='create'; + } + if (empty($objectpage->title)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors'); + $error++; + $action='create'; + } + } + + if (! $error) + { + $res = $objectpage->create($user); + if ($res <= 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + } + if (! $error) + { + if (! empty($objectpage->content)) + { + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filetpl=$pathofwebsite.'/page'.$objectpage->id.'.tpl.php'; + + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpage); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + + // Save page of content + $result=dolSavePageContent($filetpl, $object, $objectpage); + if ($result) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + else + { + setEventMessages('Failed to write file '.$filetpl, null, 'errors'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + } + } if (! $error) { $db->commit(); - setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; + setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); + $action=''; } else { @@ -326,46 +473,89 @@ if ($action == 'add') if (! $error) { - $action = 'preview'; - $pageid = $objectpage->id; + $pageid = $objectpage->id; + + // To generate the CSS, robot and htmlheader file. + + // Check symlink to medias and restore it if ko + $pathtomedias=DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite=$pathofwebsite.'/medias'; + if (! is_link(dol_osencode($pathtomediasinwebsite))) + { + dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists + $result = symlink($pathtomedias, $pathtomediasinwebsite); + } + + if (! dol_is_file($filehtmlheader)) + { + $htmlheadercontent = ""; + $result=dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); + } + + if (! dol_is_file($filecss)) + { + $csscontent = "/* CSS content (all pages) */\nbody.bodywebsite { margin: 0; }"; + $result=dolSaveCssFile($filecss, $csscontent); + } + + if (! dol_is_file($filejs)) + { + $jscontent = "/* JS content (all pages) */\n"; + $result=dolSaveJsFile($filejs, $jscontent); + } + + if (! dol_is_file($filerobot)) + { + $robotcontent = "# Robot file. Generated with Dolibarr\nUser-agent: *\nAllow: /public/\nDisallow: /administrator/"; + $result=dolSaveRobotFile($filerobot, $robotcontent); + } + + if (! dol_is_file($filehtaccess)) + { + $htaccesscontent = "# Order allow,deny\n# Deny from all"; + $result=dolSaveHtaccessFile($filehtaccess, $htaccesscontent); + } + + $action = 'preview'; } } -// Update page +// Delete 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); + } } // Update css @@ -377,12 +567,12 @@ if ($action == 'updatecss') } else { - $res = $object->fetch(0, $website); + $res = $object->fetch(0, $website); - // Html header file - $htmlheadercontent =''; + // Html header file + $htmlheadercontent =''; - /* We disable php code since htmlheader is never executed as an include but only read by fgets_content. + /* We disable php code since htmlheader is never executed as an include but only read by fgets_content. $htmlheadercontent.= "\n";*/ - $htmlheadercontent.= preg_replace(array('/\n*/ims','/<\/html>\n*/ims'),array('',''),GETPOST('WEBSITE_HTML_HEADER', 'none')); + $htmlheadercontent.= preg_replace(array('/\n*/ims','/<\/html>\n*/ims'),array('',''),GETPOST('WEBSITE_HTML_HEADER', 'none')); - /*$htmlheadercontent.= "\n".'"."\n";*/ - $htmlheadercontent = trim($htmlheadercontent)."\n"; + $htmlheadercontent = trim($htmlheadercontent)."\n"; - dol_syslog("Save html header into ".$filehtmlheader); - - dol_mkdir($pathofwebsite); - $result = file_put_contents($filehtmlheader, $htmlheadercontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filehtmlheader, octdec($conf->global->MAIN_UMASK)); - - if (! $result) - { - $error++; - setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); - } - - // Css file - $csscontent =''; - - $csscontent.= "\n"; - - $csscontent.= GETPOST('WEBSITE_CSS_INLINE', 'none'); - - $csscontent.= "\n".'"."\n"; - - dol_syslog("Save css content into ".$filecss); - - dol_mkdir($pathofwebsite); - $result = file_put_contents($filecss, $csscontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filecss, octdec($conf->global->MAIN_UMASK)); - - if (! $result) - { - $error++; - setEventMessages('Failed to write file '.$filecss, null, 'errors'); - } + dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); - // Css file - $robotcontent =''; + // Css file + $csscontent =''; - /*$robotcontent.= "\n"; + + $csscontent.= GETPOST('WEBSITE_CSS_INLINE', 'none'); + + $csscontent.= "\n".'"."\n"; + + dol_syslog("Save css content into ".$filecss); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filecss, $csscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filecss, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filecss, null, 'errors'); + } + + + // Js file + $jscontent =''; + + $jscontent.= "\n"; + + $jscontent.= GETPOST('WEBSITE_JS_INLINE', 'none'); + + $jscontent.= "\n".'"."\n"; + + dol_syslog("Save js content into ".$filejs); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filejs, $jscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filejs, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filejs, null, 'errors'); + } + + + // Robot file + $robotcontent =''; + + /*$robotcontent.= "\n";*/ - $robotcontent.= GETPOST('WEBSITE_ROBOT', 'none'); + $robotcontent.= GETPOST('WEBSITE_ROBOT', 'none'); - /*$robotcontent.= "\n".'"."\n";*/ - dol_syslog("Save file robot into ".$filerobot); + dol_syslog("Save file robot into ".$filerobot); - dol_mkdir($pathofwebsite); - $result = file_put_contents($filerobot, $robotcontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filerobot, octdec($conf->global->MAIN_UMASK)); + dol_mkdir($pathofwebsite); + $result = file_put_contents($filerobot, $robotcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filerobot, octdec($conf->global->MAIN_UMASK)); - if (! $result) - { - $error++; - setEventMessages('Failed to write file '.$filerobot, null, 'errors'); - } + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filerobot, null, 'errors'); + } - // Css file - $htaccesscontent =''; + // Css file + $htaccesscontent =''; - /*$robotcontent.= "\n";*/ - $htaccesscontent.= GETPOST('WEBSITE_HTACCESS', 'none'); + $htaccesscontent.= GETPOST('WEBSITE_HTACCESS', 'none'); - /*$robotcontent.= "\n".'"."\n";*/ - dol_syslog("Save file htaccess into ".$filehtaccess); + dol_syslog("Save file htaccess into ".$filehtaccess); - dol_mkdir($pathofwebsite); - $result = file_put_contents($filehtaccess, $htaccesscontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filehtaccess, octdec($conf->global->MAIN_UMASK)); + dol_mkdir($pathofwebsite); + $result = file_put_contents($filehtaccess, $htaccesscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filehtaccess, octdec($conf->global->MAIN_UMASK)); if (! $result) { @@ -509,165 +721,166 @@ if ($action == 'updatecss') } // Message if no error - if (! $error) - { - setEventMessages($langs->trans("Saved"), null, 'mesgs'); - } + if (! $error) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + } - $action='preview'; + $action='preview'; } } // Update page if ($action == 'setashome') { - $db->begin(); - $object->fetch(0, $website); + $db->begin(); + $object->fetch(0, $website); - $object->fk_default_home = $pageid; - $res = $object->update($user); - if (! $res > 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fk_default_home = $pageid; + $res = $object->update($user); + if (! $res > 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } - if (! $error) - { - $db->commit(); + if (! $error) + { + $db->commit(); - // Generate the index.php page to be the home page - //------------------------------------------------- - dol_mkdir($pathofwebsite); - dol_delete_file($fileindex); + // Generate the index.php page to be the home page + //------------------------------------------------- + dol_mkdir($pathofwebsite); + dol_delete_file($fileindex); - $indexcontent = ''."\n"; - $result = file_put_contents($fileindex, $indexcontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($fileindex, octdec($conf->global->MAIN_UMASK)); + $indexcontent = ''."\n"; + $result = file_put_contents($fileindex, $indexcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($fileindex, octdec($conf->global->MAIN_UMASK)); - if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); - else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); + else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); - $action='preview'; - } - else - { - $db->rollback(); - } + $action='preview'; + } + else + { + $db->rollback(); + } } // Update page (meta) if ($action == 'updatemeta') { - $db->begin(); - $object->fetch(0, $website); + $db->begin(); + $object->fetch(0, $website); - $objectpage->fk_website = $object->id; + $objectpage->fk_website = $object->id; // Check parameters - if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) - { - $error++; - setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); - $action='editmeta'; - } + if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) + { + $error++; + setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); + $action='editmeta'; + } - $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res <= 0) - { - $error++; - dol_print_error($db, 'Page not found'); - } + $res = $objectpage->fetch($pageid, $object->fk_website); + if ($res <= 0) + { + $error++; + dol_print_error($db, 'Page not found'); + } - if (! $error) - { - $objectpage->old_object = clone $objectpage; + if (! $error) + { + $objectpage->old_object = clone $objectpage; - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); - $objectpage->title = GETPOST('WEBSITE_TITLE', 'alpha'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); - $objectpage->lang = GETPOST('WEBSITE_LANG', 'alpha'); + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); + $objectpage->title = GETPOST('WEBSITE_TITLE', 'alpha'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); + $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09'); + $objectpage->htmlheader = GETPOST('htmlheader', 'none'); - $res = $objectpage->update($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } + $res = $objectpage->update($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } - if (! $error) - { - $db->commit(); + if (! $error) + { + $db->commit(); - $filemaster=$pathofwebsite.'/master.inc.php'; - $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filemaster=$pathofwebsite.'/master.inc.php'; + $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; - dol_mkdir($pathofwebsite); + dol_mkdir($pathofwebsite); - // Now generate the master.inc.php page - dol_syslog("We regenerate the master file (because we update meta)"); - dol_delete_file($filemaster); + // Now generate the master.inc.php page + dol_syslog("We regenerate the master file (because we update meta)"); + dol_delete_file($filemaster); - $mastercontent = ''."\n"; - $result = file_put_contents($filemaster, $mastercontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); + $mastercontent = ''."\n"; + $result = file_put_contents($filemaster, $mastercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); - if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); - // Now generate the alias.php page - if (! empty($fileoldalias)) - { - dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); - dol_delete_file($fileoldalias); - } + // Now generate the alias.php page + if (! empty($fileoldalias)) + { + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($fileoldalias); + } - // Save page alias - $result=dolSavePageAlias($filealias, $object, $objectpage); - if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpage); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); // Save page of content - $result=dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { - setEventMessages($langs->trans("Saved"), null, 'mesgs'); - //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - //exit; - } - else - { - setEventMessages('Failed to write file '.$filetpl, null, 'errors'); - //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - //exit; - } + $result=dolSavePageContent($filetpl, $object, $objectpage); + if ($result) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } + else + { + setEventMessages('Failed to write file '.$filetpl, null, 'errors'); + //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + //exit; + } - $action='preview'; - } - else - { - $db->rollback(); - } - } + $action='preview'; + } + else + { + $db->rollback(); + } + } } // Update page if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'confirm_createfromclone' || $action == 'confirm_createpagefromclone') || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) { - $object->fetch(0, $website); + $object->fetch(0, $website); if ($action == 'confirm_createfromclone') { @@ -702,7 +915,7 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf if (! $error) { - $objectpage = new WebsitePage($db); + $objectpage = new WebsitePage($db); $result = $objectpage->createFromClone($user, $pageid, GETPOST('pageurl','aZ09'), (GETPOST('newlang','aZ09')?GETPOST('newlang','aZ09'):''), $istranslation, GETPOST('newwebsite','int')); if ($result < 0) { @@ -711,135 +924,135 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $action='createpagefromclone'; } } - } + } - $res = 0; + $res = 0; - if (! $error) - { - // Check symlink to medias and restore it if ko - $pathtomedias=DOL_DATA_ROOT.'/medias'; - $pathtomediasinwebsite=$pathofwebsite.'/medias'; - if (! is_link(dol_osencode($pathtomediasinwebsite))) - { - dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); - dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists - $result = symlink($pathtomedias, $pathtomediasinwebsite); - } + if (! $error) + { + // Check symlink to medias and restore it if ko + $pathtomedias=DOL_DATA_ROOT.'/medias'; + $pathtomediasinwebsite=$pathofwebsite.'/medias'; + if (! is_link(dol_osencode($pathtomediasinwebsite))) + { + dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); + dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists + $result = symlink($pathtomedias, $pathtomediasinwebsite); + } - /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite')) + /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite')) { $object->virtualhost = GETPOST('previewsite', 'alpha'); $object->update($user); }*/ - $objectpage->fk_website = $object->id; + $objectpage->fk_website = $object->id; - if ($pageid > 0) - { - $res = $objectpage->fetch($pageid); - } - else - { - $res=0; - if ($object->fk_default_home > 0) - { - $res = $objectpage->fetch($object->fk_default_home); - } - if (! ($res > 0)) - { - $res = $objectpage->fetch(0, $object->id); - } - } - } + if ($pageid > 0) + { + $res = $objectpage->fetch($pageid); + } + else + { + $res=0; + if ($object->fk_default_home > 0) + { + $res = $objectpage->fetch($object->fk_default_home); + } + if (! ($res > 0)) + { + $res = $objectpage->fetch(0, $object->id); + } + } + } - if (! $error && $res > 0) - { - if ($action == 'updatesource' || $action == 'updatecontent') - { - $db->begin(); + if (! $error && $res > 0) + { + if ($action == 'updatesource' || $action == 'updatecontent') + { + $db->begin(); - $objectpage->content = GETPOST('PAGE_CONTENT','none'); + $objectpage->content = GETPOST('PAGE_CONTENT','none'); - // Clean data. We remove all the head section. - $objectpage->content = preg_replace('/.*<\/head>/s', '', $objectpage->content); - /* $objectpage->content = preg_replace('//s', '', $objectpage->content); */ + // Clean data. We remove all the head section. + $objectpage->content = preg_replace('/.*<\/head>/s', '', $objectpage->content); + /* $objectpage->content = preg_replace('//s', '', $objectpage->content); */ - $res = $objectpage->update($user); - if ($res < 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } + $res = $objectpage->update($user); + if ($res < 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } - if (! $error) - { - $db->commit(); + if (! $error) + { + $db->commit(); - $filemaster=$pathofwebsite.'/master.inc.php'; - //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; - $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + $filemaster=$pathofwebsite.'/master.inc.php'; + //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; - dol_mkdir($pathofwebsite); + dol_mkdir($pathofwebsite); - // Now generate the master.inc.php page - dol_syslog("We regenerate the master file"); - dol_delete_file($filemaster); + // Now generate the master.inc.php page + dol_syslog("We regenerate the master file"); + dol_delete_file($filemaster); - $mastercontent = ''."\n"; - $result = file_put_contents($filemaster, $mastercontent); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); + $mastercontent = ''."\n"; + $result = file_put_contents($filemaster, $mastercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); - if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); - // Now generate the alias.php page - if (! empty($fileoldalias)) - { - dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); - dol_delete_file($fileoldalias); - } + // Now generate the alias.php page + if (! empty($fileoldalias)) + { + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($fileoldalias); + } - // Save page alias - $result=dolSavePageAlias($filealias, $object, $objectpage); - if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + // Save page alias + $result=dolSavePageAlias($filealias, $object, $objectpage); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); // Save page content - $result=dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { - setEventMessages($langs->trans("Saved"), null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - exit; - } - else - { - setEventMessages('Failed to write file '.$filetpl, null, 'errors'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - exit; - } - } - else - { - $db->rollback(); - } - } - else - { - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); - exit; - } - } - else - { - if (! $error) setEventMessages($langs->trans("NoPageYet"), null, 'warnings'); - } + $result=dolSavePageContent($filetpl, $object, $objectpage); + if ($result) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + exit; + } + else + { + setEventMessages('Failed to write file '.$filetpl, null, 'errors'); + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + exit; + } + } + else + { + $db->rollback(); + } + } + else + { + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); + exit; + } + } + else + { + if (! $error) setEventMessages($langs->trans("NoPageYet"), null, 'warnings'); + } } // Export site @@ -847,11 +1060,11 @@ if (GETPOST('exportsite')) { $fileofzip = exportWebSite($object); - $file_name = basename($yourfile); + $file_name = basename($fileofzip); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=".$file_name); - header("Content-Length: " . filesize($yourfile)); + header("Content-Length: " . filesize($fileofzip)); readfile($fileofzip); exit; @@ -869,51 +1082,53 @@ $formwebsite = new FormWebsite($db); $help_url=''; -llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, 0, - array( - '/includes/ace/ace.js', - '/includes/ace/ext-statusbar.js', - '/includes/ace/ext-language_tools.js', - //'/includes/ace/ext-chromevox.js' - ), array()); +$arrayofjs = array( + '/includes/ace/ace.js', + '/includes/ace/ext-statusbar.js', + '/includes/ace/ext-language_tools.js', + //'/includes/ace/ext-chromevox.js' +); +$arrayofcss = array(); + +llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, 0, $arrayofjs, $arrayofcss, '', '', ''."\n".'
    '); print "\n".'
    '; print ''; if ($action == 'createsite') { - print ''; + print ''; } if ($action == 'create') { - print ''; + print ''; } if ($action == 'editcss') { - print ''; + print ''; } if ($action == 'editmenu') { - print ''; + print ''; } if ($action == 'setashome') { - print ''; + print ''; } if ($action == 'editmeta') { - print ''; + print ''; } if ($action == 'editsource') { - print ''; + print ''; } if ($action == 'editcontent') { - print ''; + print ''; } if ($action == 'edit') { - print ''; + print ''; } @@ -926,183 +1141,183 @@ print '
    '; if (count($object->records) > 0) { - // ***** Part for web sites + // ***** Part for web sites print '
    '; print ''; print '
    '; - 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.'/websites/'.$website; + if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; + } - if ($website && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - - print '   '; - - print ''; - //print ''; - print ''; - print ''; + if ($website && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; print '   '; - print ''; - } + print ''; + //print ''; + print ''; + print ''; - print '
    '; + print '   '; - // Button for websites - print '
    '; + print ''; + } - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') - { - print '
    '; - print ''; - //print ''; - $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); - print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helpvirtualhost'); - print '
    '; + print '
    '; - $urlext=$virtualurl; - $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; - 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 ''; + // Button for websites + 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 ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') + { + 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','editmedias'))) - { - if (preg_match('/^create/',$action) && $action != 'editmedias') print ''; - if (preg_match('/^edit/',$action) && $action != 'editmedias') print ''; - if ($action != 'preview') print ''; - } + print '
    '; + print ''; + //print ''; + $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); + print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helpvirtualhost'); + print '
    '; - print '
    '; + $urlext=$virtualurl; + $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; + 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 ''; + } + + if (in_array($action, array('editcss','editmenu','editmedias'))) + { + if (preg_match('/^create/',$action) && $action != 'editmedias') print ''; + if (preg_match('/^edit/',$action) && $action != 'editmedias') print ''; + if ($action != 'preview') print ''; + } + + print '
    '; - // ***** Part for pages + // ***** Part for pages - if ($website && ! in_array($action, array('editcss','editmenu','editmedias'))) - { - print '
    '; // Close current websitebar to open a new one + if ($website && ! in_array($action, array('editcss','editmenu','editmedias'))) + { + print '
    '; // Close current websitebar to open a new one - $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 '
    '; - print ''; - print '
    '; + print '
    '; + print ''; + print '
    '; - print '
    '; - print $langs->trans("Page").': '; - 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 ''; - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - // Confirmation to clone - if ($action == 'createfromclone') { - // Create an array for form - $formquestion = array( - array('type' => 'text', 'name' => 'siteref', 'label'=> $langs->trans("Website") ,'value'=> 'copy_of_'.$object->ref), - //array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("SiteIsANewTranslation"), 'value' => 0), - //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), - //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("Website"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) - ); + // Confirmation to clone + if ($action == 'createfromclone') { + // Create an array for form + $formquestion = array( + array('type' => 'text', 'name' => 'siteref', 'label'=> $langs->trans("Website") ,'value'=> 'copy_of_'.$object->ref), + //array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("SiteIsANewTranslation"), 'value' => 0), + //array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')), + //array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("Website"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) + ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id='.$object->id, $langs->trans('CloneSite'), '', 'confirm_createfromclone', $formquestion, 0, 1, 200); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id='.$object->id, $langs->trans('CloneSite'), '', 'confirm_createfromclone', $formquestion, 0, 1, 200); - print $formconfirm; - } + print $formconfirm; + } - if ($pageid > 0) - { - // Confirmation to clone - if ($action == 'createpagefromclone') { - // Create an array for form + if ($pageid > 0) + { + // Confirmation to clone + if ($action == 'createpagefromclone') { + // Create an array for form $formquestion = array( array('type' => 'text', 'name' => 'pageurl', 'label'=> $langs->trans("WEBSITE_PAGENAME") ,'value'=> 'copy_of_'.$objectpage->pageurl), array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("PageIsANewTranslation"), 'value' => 0), @@ -1110,79 +1325,79 @@ if (count($object->records) > 0) array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("Website"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0)) ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?pageid=' . $pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 250); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?pageid=' . $pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 250); print $formconfirm; - } + } - print '   '; + print '   '; - print ''; - print ''; - print ''; - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; - else print ''; - print ''; - print ''; - } - } + print ''; + print ''; + print ''; + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; + else print ''; + print ''; + print ''; + } + } - print '
    '; // end website selection + print '
    '; // end website selection - print '
    '; + print '
    '; - if ($website && $pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) - { - $websitepage = new WebSitePage($db); - $websitepage->fetch($pageid); + if ($website && $pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) + { + $websitepage = new WebSitePage($db); + $websitepage->fetch($pageid); - $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&pageref='.$websitepage->pageurl; - $pagealias = $websitepage->pageurl; + $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&pageref='.$websitepage->pageurl; + $pagealias = $websitepage->pageurl; - print '
    '; - print ''; - $htmltext=$langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); - print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias'); - 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 - $urlext=$virtualurl.'/'.$pagealias.'.php'; - $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl?$urlext:''.$langs->trans("VirtualHostUrlNotDefined").''), 1, 'preview_ext'); - print ''; + print '
    '; + print ''; + $htmltext=$langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); + print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias'); + 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 ''; + $urlext=$virtualurl.'/'.$pagealias.'.php'; + $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl?$urlext:''.$langs->trans("VirtualHostUrlNotDefined").''), 1, 'preview_ext'); + print ''; + //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','editmedias','createsite','create','createpagefromclone'))) - { - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - if ($action != 'preview') 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','editmedias','createsite','create','createpagefromclone'))) + { + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + if ($action != 'preview') print ''; + } - print '
    '; // end websitetools + print '
    '; // end websitetools - print '
    '; - if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) - { - $htmltext=$langs->transnoentitiesnoconv("YouCanEditHtmlSource"); - print $form->textwithpicto($langs->trans("SyntaxHelp"), $htmltext, 1, 'help', 'inline-block', 0, 2, 'tooltipsubstitution'); - } - print '
    '; // end websitehelp + print '
    '; + if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) + { + $htmltext=$langs->transnoentitiesnoconv("YouCanEditHtmlSource"); + print $form->textwithpicto($langs->trans("SyntaxHelp"), $htmltext, 1, 'help', 'inline-block', 0, 2, 'tooltipsubstitution'); + } + print '
    '; // end websitehelp - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') - { - // 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=''; } @@ -1237,109 +1452,125 @@ $head = array(); if ($action == 'editcss') { - print '
    '; + print '
    '; - print '
    '; + print '
    '; - $csscontent = @file_get_contents($filecss); - // Clean the php css file to remove php code and get only css part - $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $csscontent); - $csscontent.= GETPOST('WEBSITE_CSS_INLINE'); - if (! trim($csscontent)) $csscontent='/* CSS content (all pages) */'."\n".'body.bodywebsite { margin: 0; }'; + $csscontent = @file_get_contents($filecss); + // Clean the php css file to remove php code and get only css part + $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $csscontent); + $csscontent.= GETPOST('WEBSITE_CSS_INLINE'); + if (! trim($csscontent)) $csscontent='/* CSS content (all pages) */'."\n".'body.bodywebsite { margin: 0; }'; - $htmlheader = @file_get_contents($filehtmlheader); - // Clean the php htmlheader file to remove php code and get only html part - $htmlheader = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htmlheader); - if (! trim($htmlheader)) $htmlheader=''; - else $htmlheader=''."\n".trim($htmlheader)."\n".''; + $jscontent = @file_get_contents($filejs); + // Clean the php js file to remove php code and get only js part + $jscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $jscontent); + $jscontent.= GETPOST('WEBSITE_JS_INLINE'); + if (! trim($jscontent)) $jscontent='/* JS content (all pages) */'."\n"; - $robotcontent = @file_get_contents($filerobot); - // Clean the php htmlheader file to remove php code and get only html part - $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $robotcontent); - if (! trim($robotcontent)) - { - $robotcontent.="# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n"; - $robotcontent.="User-agent: *\n"; - $robotcontent.="Allow: /public/\n"; - $robotcontent.="Disallow: /administrator/\n"; - } + $htmlheader = @file_get_contents($filehtmlheader); + // Clean the php htmlheader file to remove php code and get only html part + $htmlheader = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htmlheader); + if (! trim($htmlheader)) $htmlheader=''; + else $htmlheader=''."\n".trim($htmlheader)."\n".''; - $htaccesscontent = @file_get_contents($filehtaccess); - // Clean the php htaccesscontent file to remove php code and get only html part - $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htaccesscontent); - if (! trim($htaccesscontent)) - { - $htaccesscontent.="# Order allow,deny\n"; + $robotcontent = @file_get_contents($filerobot); + // Clean the php htmlheader file to remove php code and get only html part + $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $robotcontent); + if (! trim($robotcontent)) + { + $robotcontent.="# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n"; + $robotcontent.="User-agent: *\n"; + $robotcontent.="Allow: /public/\n"; + $robotcontent.="Disallow: /administrator/\n"; + } + + $htaccesscontent = @file_get_contents($filehtaccess); + // Clean the php htaccesscontent file to remove php code and get only html part + $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htaccesscontent); + if (! trim($htaccesscontent)) + { + $htaccesscontent.="# Order allow,deny\n"; $htaccesscontent.="# Deny from all\n"; - } - //else $htaccesscontent=''."\n".$htaccesscontent."\n".'';*/ + } + //else $htaccesscontent=''."\n".$htaccesscontent."\n".'';*/ - dol_fiche_head(); + dol_fiche_head(); - print ''."\n"; - print ''; + print ''."\n"; + print '
    '; - // Website - print ''; + // Website + print ''; - // CSS file - print ''; + print ''; - // Common HTML header + // JS file print ''; + + // Common HTML header + print ''; + print ''; - // Robot file + // Robot file print ''; + print ''; - // .htaccess + // .htaccess print ''; + print ''; - print '
    '; - print $langs->trans('WebSite'); - print ''; - print $website; - print '
    '; + print $langs->trans('WebSite'); + print ''; + print $website; + print '
    '; - print $langs->trans('WEBSITE_CSS_INLINE'); - print ''; + // CSS file + print '
    '; + print $langs->trans('WEBSITE_CSS_INLINE'); + print ''; - $doleditor=new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor=new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'CSS', 'css'); - print '
    '; - print $langs->trans('WEBSITE_HTML_HEADER'); - print ''; + print $langs->trans('WEBSITE_JS_INLINE'); + print ''; - $doleditor=new DolEditor('WEBSITE_HTML_HEADER', $htmlheader, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor=new DolEditor('WEBSITE_JS_INLINE', $jscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'JS', 'javascript'); + + print '
    '; + print $langs->trans('WEBSITE_HTML_HEADER'); + print ''; + + $doleditor=new DolEditor('WEBSITE_HTML_HEADER', $htmlheader, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'HTML Header', 'html'); - print '
    '; - print $langs->trans('WEBSITE_ROBOT'); - print ''; + print $langs->trans('WEBSITE_ROBOT'); + print ''; - $doleditor=new DolEditor('WEBSITE_ROBOT', $robotcontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor=new DolEditor('WEBSITE_ROBOT', $robotcontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, 'Robot file', 'txt'); - print '
    '; - print $langs->trans('WEBSITE_HTACCESS'); - print ''; + print $langs->trans('WEBSITE_HTACCESS'); + print ''; - $doleditor=new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + $doleditor=new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); print $doleditor->Create(1, '', true, $langs->trans("File").' .htaccess', 'txt'); - print '
    '; + print '
    '; - dol_fiche_end(); + dol_fiche_end(); - print '
    '; + print '
    '; - print '
    '; + print '
    '; } if ($action == 'createsite') { - print '
    '; + print '
    '; - print '
    '; + print '
    '; /*$h = 0; $head = array(); @@ -1353,60 +1584,60 @@ if ($action == 'createsite') */ if ($action == 'create') print_fiche_titre($langs->trans("AddSite")); - print ''."\n"; - //print '
    '; + print ''."\n"; + //print '
    '; - print ''; + print '
    '; - if (GETPOST('WEBSITE_REF')) $siteref=GETPOST('WEBSITE_REF','alpha'); - if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc=GETPOST('WEBSITE_DESCRIPTION','alpha'); + if (GETPOST('WEBSITE_REF')) $siteref=GETPOST('WEBSITE_REF','alpha'); + if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc=GETPOST('WEBSITE_DESCRIPTION','alpha'); - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print '
    '; - print $langs->trans('Ref'); - print ''; - print ''; - print '
    '; + print $langs->trans('Ref'); + print ''; + print ''; + print '
    '; - print $langs->trans('Description'); - print ''; - print ''; - print '
    '; + print $langs->trans('Description'); + print ''; + print ''; + print '
    '; - print $form->textwithpicto($langs->trans('Virtualhost'), $langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/websites/websiteref'), 1, 'help', '', 0, 2, 'tooltipvirtual'); - print ''; - print ''; - print '
    '; + print $form->textwithpicto($langs->trans('Virtualhost'), $langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/websites/websiteref'), 1, 'help', '', 0, 2, 'tooltipvirtual'); + print ''; + print ''; + print '
    '; + print ''; - if ($action == 'createsite') - { - print '
    '; + if ($action == 'createsite') + { + print '
    '; - print ''; - print ''; + print ''; + print ''; - print '
    '; - } + print '
    '; + } //print '
    '; - //dol_fiche_end(); + //dol_fiche_end(); - print '
    '; + print '
    '; - print '
    '; + print '
    '; } if ($action == 'editmeta' || $action == 'create') { - print '
    '; + print '
    '; - print '
    '; + print '
    '; /*$h = 0; $head = array(); @@ -1420,39 +1651,45 @@ if ($action == 'editmeta' || $action == 'create') */ if ($action == 'create') print_fiche_titre($langs->trans("AddPage")); - print ''."\n"; - //print '
    '; + print ''."\n"; + //print '
    '; - if ($action == 'create') - { - print '
    '; + if ($action == 'create') + { + print '
    '; - print ' * '.$langs->trans("CreateByFetchingExternalPage").'

    '; - print ''; - print ''; + print '
    '; - print $langs->trans("URL"); - print ''; - print ' '; + print ' * '.$langs->trans("CreateByFetchingExternalPage").'

    '; + print ''; + print ''; - print '
    '; + print $langs->trans("URL"); + print ''; + print ' '; print ''; - print '
    '; + print '
    '; - print '
    '; + print '
    '; - print ' * '.$langs->trans("OrEnterPageInfoManually").'

    '; - } + print ' * '.$langs->trans("OrEnterPageInfoManually").'

    '; + } - print ''; + print '
    '; - if ($action != 'create') - { - print ''; + if ($action != 'create') + { + print ''; - /* + print ''; + + /* print ''; */ - $pageurl=$objectpage->pageurl; - $pagetitle=$objectpage->title; - $pagedescription=$objectpage->description; - $pagekeywords=$objectpage->keywords; - $pagelang=$objectpage->lang; - } - if (GETPOST('WEBSITE_PAGENAME')) $pageurl=GETPOST('WEBSITE_PAGENAME','alpha'); - if (GETPOST('WEBSITE_TITLE')) $pagetitle=GETPOST('WEBSITE_TITLE','alpha'); - if (GETPOST('WEBSITE_DESCRIPTION')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION','alpha'); - if (GETPOST('WEBSITE_KEYWORDS')) $pagekeywords=GETPOST('WEBSITE_KEYWORDS','alpha'); - if (GETPOST('WEBSITE_LANG')) $pagelang=GETPOST('WEBSITE_LANG','aZ09'); + $pageurl=$objectpage->pageurl; + $pagetitle=$objectpage->title; + $pagedescription=$objectpage->description; + $pagekeywords=$objectpage->keywords; + $pagelang=$objectpage->lang; + $pagehtmlheader=$objectpage->htmlheader; + } + if (GETPOST('WEBSITE_PAGENAME','alpha')) $pageurl=GETPOST('WEBSITE_PAGENAME','alpha'); + if (GETPOST('WEBSITE_TITLE','alpha')) $pagetitle=GETPOST('WEBSITE_TITLE','alpha'); + if (GETPOST('WEBSITE_DESCRIPTION','alpha')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION','alpha'); + if (GETPOST('WEBSITE_KEYWORDS','alpha')) $pagekeywords=GETPOST('WEBSITE_KEYWORDS','alpha'); + if (GETPOST('WEBSITE_LANG','aZ09')) $pagelang=GETPOST('WEBSITE_LANG','aZ09'); + if (GETPOST('htmlheader','none')) $pagehtmlheader=GETPOST('htmlheader','none'); - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print '
    '; - print $langs->trans('WEBSITE_PAGEURL'); - print ''; - print '/public/websites/index.php?website='.urlencode($website).'&pageid='.urlencode($pageid); - print '
    '; + print $langs->trans('IDOfPage'); + print ''; + print $pageid; + print '
    '; + print $langs->trans('WEBSITE_PAGEURL'); + print ''; + print '/public/websites/index.php?website='.urlencode($website).'&pageid='.urlencode($pageid); + print '
    '; print $langs->trans('InitiallyGrabbedFrom'); print ''; @@ -1460,90 +1697,97 @@ if ($action == 'editmeta' || $action == 'create') print '
    '; - print $langs->trans('WEBSITE_PAGENAME'); - print ''; - print ''; - print '
    '; + print $langs->trans('WEBSITE_PAGENAME'); + print ''; + print ''; + print '
    '; - print $langs->trans('WEBSITE_TITLE'); - print ''; - print ''; - print '
    '; + print $langs->trans('WEBSITE_TITLE'); + print ''; + print ''; + print '
    '; - print $langs->trans('WEBSITE_DESCRIPTION'); - print ''; - print ''; - print '
    '; + print $langs->trans('WEBSITE_DESCRIPTION'); + print ''; + print ''; + print '
    '; - print $langs->trans('WEBSITE_KEYWORDS'); - print ''; - print ''; - print '
    '; + print $langs->trans('WEBSITE_KEYWORDS'); + print ''; + print ''; + print '
    '; - print $langs->trans('Language'); - print ''; - print $formadmin->select_language($pagelang?$pagelang:$langs->defaultlang, 'WEBSITE_LANG'); - print '
    '; + print $langs->trans('Language'); + print ''; + print $formadmin->select_language($pagelang?$pagelang:$langs->defaultlang, 'WEBSITE_LANG'); + print '
    '; + print ''; + print $langs->trans('HtmlHeaderPage'); + print ''; + $doleditor=new DolEditor('htmlheader', $pagehtmlheader, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', ''); + print $doleditor->Create(1, '', true, 'HTML Header', 'html'); + print ''; - if ($action == 'create') - { - print '
    '; + print ''; - print ''; - print ''; + if ($action == 'create') + { + print '
    '; - print '
    '; - } + print ''; + print ''; + + print '
    '; + } //print '
    '; - //dol_fiche_end(); + //dol_fiche_end(); - print '
    '; + print '
    '; - print '
    '; + print '
    '; } if ($action == 'editmedias') { - print ''."\n"; - print '
    '.$langs->trans("FeatureNotYetAvailable").''; + print ''."\n"; + print '
    '.$langs->trans("FeatureNotYetAvailable").''; } if ($action == 'editmenu') { - print ''."\n"; - print '
    '.$langs->trans("FeatureNotYetAvailable").''; + print ''."\n"; + print '
    '.$langs->trans("FeatureNotYetAvailable").''; } if ($action == 'editsource') { /* - * Editing global variables not related to a specific theme + * Editing with source editor */ - //$csscontent = @file_get_contents($filecss); - $contentforedit = ''; /*$contentforedit.=''."\n";*/ - $contentforedit .= $objectpage->content; + $contentforedit .= $objectpage->content; - $contentforedit = preg_replace('/(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"; @@ -1582,35 +1824,40 @@ print "
    \n\n"; if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') { - if ($pageid > 0) - { - // Ouput page under the Dolibarr top menu - $objectpage->fetch($pageid); - $csscontent = @file_get_contents($filecss); + if ($pageid > 0) + { + // Ouput page under the Dolibarr top menu + $objectpage->fetch($pageid); + $csscontent = @file_get_contents($filecss); + $jscontent = @file_get_contents($filejs); - $out = ''."\n"; + $out = ''."\n"; - $out.='
    '."\n"; + $out.='
    '."\n"; - // REPLACEMENT OF LINKS When page called by website editor - $out.=''."\n"; + // REPLACEMENT OF LINKS When page called by website editor + + $out.=''."\n"; $out.='
    '."\n"; - $out.=dolWebsiteReplacementOfLinks($object, $objectpage->content)."\n"; + $out.=dolWebsiteReplacementOfLinks($object, $objectpage->content)."\n"; - $out.='
    '; + $out.='
    '; - $out.='
    '; + $out.='
    '; - $out.= "\n".''."\n\n"; + $out.= "\n".''."\n\n"; - print $out; + print $out; - /*file_put_contents($filetpl, $out); + /*file_put_contents($filetpl, $out); if (! empty($conf->global->MAIN_UMASK)) @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); @@ -1628,14 +1875,14 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa //include_once $original_file_osencoded; */ - /*print '';*/ - } - else - { - print '

    '.$langs->trans("PreviewOfSiteNotYetAvailable", $website).'


    '; - print '
    '; - } + } + else + { + print '

    '.$langs->trans("PreviewOfSiteNotYetAvailable", $website).'


    '; + print '
    '; + } } @@ -1717,8 +1964,10 @@ function dolSavePageContent($filetpl, $object, $objectpage) $tplcontent.= ''."\n"; $tplcontent.= ''."\n"; $tplcontent.= ''."\n"; - $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; $tplcontent.= 'ref.'/htmlheader.html"); ?>'."\n"; + $tplcontent.= ''."\n"; + $tplcontent.= $objectpage->htmlheader."\n"; $tplcontent.= ''."\n"; $tplcontent.= ''."\n"; @@ -1737,3 +1986,140 @@ function dolSavePageContent($filetpl, $object, $objectpage) return $result; } + + +/** + * Save content of a page on disk + * + * @param string $filehtmlheader Full path of filename to generate + * @param string $htmlheadercontent Content of file + * @return boolean True if OK + */ +function dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filehtmlheader); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filehtmlheader, $htmlheadercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filehtmlheader, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filecss Full path of filename to generate + * @param string $csscontent Content of file + * @return boolean True if OK + */ +function dolSaveCssFile($filecss, $csscontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filecss); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filecss, $csscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filecss, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filecss, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filejs Full path of filename to generate + * @param string $jscontent Content of file + * @return boolean True if OK + */ +function dolSaveJsFile($filejs, $jscontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filejs); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filejs, $jscontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filejs, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filejs, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filerobot Full path of filename to generate + * @param string $robotcontent Content of file + * @return boolean True if OK + */ +function dolSaveRobotFile($filerobot, $robotcontent) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filerobot); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filerobot, $robotcontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filerobot, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filerobot, null, 'errors'); + return false; + } + + return true; +} + +/** + * Save content of a page on disk + * + * @param string $filehtaccess Full path of filename to generate + * @param string $htaccess Content of file + * @return boolean True if OK + */ +function dolSaveHtaccessFile($filehtaccess, $htaccess) +{ + global $conf, $pathofwebsite; + + dol_syslog("Save html header into ".$filehtaccess); + + dol_mkdir($pathofwebsite); + $result = file_put_contents($filehtaccess, $htaccess); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filehtaccess, octdec($conf->global->MAIN_UMASK)); + + if (! $result) + { + setEventMessages('Failed to write file '.$filehtaccess, null, 'errors'); + return false; + } + + return true; +} + diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php index a6cf54ab40d..a56c2be2055 100755 --- a/scripts/emailings/mailing-send.php +++ b/scripts/emailings/mailing-send.php @@ -32,7 +32,7 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; exit(-1); } @@ -116,10 +116,10 @@ if ($resql) $sql2 = "SELECT mc.rowid, mc.lastname as lastname, mc.firstname as firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag"; $sql2.= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql2.= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id; - if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) - { - $sql2.= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI; - } + if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) + { + $sql2.= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI; + } $resql2=$db->query($sql2); if ($resql2) @@ -157,30 +157,31 @@ if ($resql) // Make subtsitutions on topic and body $other=explode(';',$obj2->other); $tmpfield=explode('=',$other[0],2); $other1=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[1],2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[2],2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[3],2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $tmpfield=explode('=',$other[4],2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); - $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); + $tmpfield=explode('=',$other[1],2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $tmpfield=explode('=',$other[2],2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $tmpfield=explode('=',$other[3],2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $tmpfield=explode('=',$other[4],2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); + $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); - $object = null; // Not defined with mass emailing - $parameters=array('mode'=>'emailing'); - $substitutionarray=getCommonSubstitutionArray($langs, 2, array('object','objectamount'), $object); // Note: On mass emailing, this is null because we don't know object + $object = null; // Not defined with mass emailing + $parameters=array('mode'=>'emailing'); + $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $object); // Note: On mass emailing, this is null because we don't know object - // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) - $substitutionarray['__ID__'] = $obj->source_id; - $substitutionarray['__EMAIL__'] = $obj->email; - $substitutionarray['__LASTNAME__'] = $obj->lastname; - $substitutionarray['__FIRSTNAME__'] = $obj->firstname; - $substitutionarray['__MAILTOEMAIL__'] = ''.$obj->email.''; - $substitutionarray['__OTHER1__'] = $other1; - $substitutionarray['__OTHER2__'] = $other2; - $substitutionarray['__OTHER3__'] = $other3; - $substitutionarray['__OTHER4__'] = $other4; - $substitutionarray['__OTHER5__'] = $other5; - $substitutionarray['__SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) - $substitutionarray['__CHECK_READ__'] = ''; - $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; + // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) + $substitutionarray['__ID__'] = $obj->source_id; + $substitutionarray['__EMAIL__'] = $obj->email; + $substitutionarray['__LASTNAME__'] = $obj->lastname; + $substitutionarray['__FIRSTNAME__'] = $obj->firstname; + $substitutionarray['__MAILTOEMAIL__'] = ''.$obj->email.''; + $substitutionarray['__OTHER1__'] = $other1; + $substitutionarray['__OTHER2__'] = $other2; + $substitutionarray['__OTHER3__'] = $other3; + $substitutionarray['__OTHER4__'] = $other4; + $substitutionarray['__OTHER5__'] = $other5; + $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) + $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility + $substitutionarray['__CHECK_READ__'] = ''; + $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; $onlinepaymentenabled = 0; if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++; @@ -231,22 +232,22 @@ if ($resql) // Fabrication du mail $trackid='emailing-'.$obj2->source_type.$obj2->source_id; $mail = new CMailFile( - $newsubject, - $sendto, - $from, - $newmessage, - array(), - array(), - array(), - '', - '', - 0, - $msgishtml, - $errorsto, - '', - $trackid, - '', - 'emailing' + $newsubject, + $sendto, + $from, + $newmessage, + array(), + array(), + array(), + '', + '', + 0, + $msgishtml, + $errorsto, + '', + $trackid, + '', + 'emailing' ); if ($mail->error) @@ -313,7 +314,7 @@ if ($resql) $error++; } - //Update status communication of contact prospect + //Update status communication of contact prospect $sqlx = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj2->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)"; dol_syslog("card.php: set prospect contact status", LOG_DEBUG); @@ -325,9 +326,9 @@ if ($resql) } } - if (!empty($conf->global->MAILING_DELAY)) { - sleep($conf->global->MAILING_DELAY); - } + if (!empty($conf->global->MAILING_DELAY)) { + sleep($conf->global->MAILING_DELAY); + } } } diff --git a/scripts/invoices/rebuild_merge_pdf.php b/scripts/invoices/rebuild_merge_pdf.php index 6727dc5cab7..30782d3b913 100755 --- a/scripts/invoices/rebuild_merge_pdf.php +++ b/scripts/invoices/rebuild_merge_pdf.php @@ -289,7 +289,7 @@ function usage() print "To exclude deposit invoices, use filter=nodeposit\n"; print "To exclude some thirdparties, use filter=excludethirdparties id1,id2...\n"; print "To limit to some thirdparties, use filter=onlythirdparties id1,id2...\n"; - print "To regenerate existing PDF, use regenerate=crabe\n"; + print "To regenerate existing PDF, use regenerate=templatename\n"; print "To generate invoices in a language, use lang=xx_XX\n"; print "To set prefix of generated file name, use prefix=myfileprefix\n"; print "\n"; diff --git a/scripts/members/sync_members_types_ldap2dolibarr.php b/scripts/members/sync_members_types_ldap2dolibarr.php index fb8fb160d36..55d5606cd30 100755 --- a/scripts/members/sync_members_types_ldap2dolibarr.php +++ b/scripts/members/sync_members_types_ldap2dolibarr.php @@ -69,7 +69,7 @@ $required_fields = array( ); // Remove from required_fields all entries not configured in LDAP (empty) and duplicated -$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElement"))); +$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElementType"))); if (! isset($argv[1])) { @@ -214,7 +214,7 @@ exit($error); * @param string $element Value to test * @return boolean True of false */ -function dolValidElement($element) +function dolValidElementType($element) { return (trim($element) != ''); } diff --git a/scripts/odt2pdf/odt2pdf.sh b/scripts/odt2pdf/odt2pdf.sh index 4cf1ab54013..2a3550de29b 100755 --- a/scripts/odt2pdf/odt2pdf.sh +++ b/scripts/odt2pdf/odt2pdf.sh @@ -3,20 +3,26 @@ # @copyright GPL License 2013 - Florian HEnry - florian.henry@open-concept.pro # @copyright GPL License 2017 - Laurent Destailleur - eldy@users.sourceforge.net # -# Convert an ODT into a PDF using "jodconverter" or "pyodconverter" tool. -# Dolibarr variable MAIN_ODT_AS_PDF must be defined to value "jodconverter" to call jodconverter wrapper after ODT generation +# Convert an ODT into a PDF using "jodconverter" or "pyodconverter" or "unoconv" tool. +# Dolibarr variable MAIN_ODT_AS_PDF must be defined +# to value "unoconv" to call unoconv CLI tool after ODT generation. # or value "pyodconverter" to call DocumentConverter.py after ODT generation. +# or value "jodconverter" to call jodconverter wrapper after ODT generation # or value "/pathto/jodconverter-cli-file.jar" to call jodconverter java tool without wrapper after ODT generation. # Dolibarr variable MAIN_DOL_SCRIPTS_ROOT must be defined to path of script directories (otherwise dolibarr will try to guess). if [ "x$1" == "x" ] then - echo "Usage: odt2pdf.sh fullfilename [jodconverter|pyodconverter|pathtojodconverterjar]" + echo "Usage: odt2pdf.sh fullfilename [unoconv|jodconverter|pyodconverter|pathtojodconverterjar]" + echo "Example: odt2pdf.sh myfile unoconv" echo "Example: odt2pdf.sh myfile ~/jodconverter/jodconverter-cli-2.2.2.jar" exit fi + + + # Full patch where soffice is installed soffice="/usr/bin/soffice" @@ -26,7 +32,21 @@ home_java="/tmp" # Main program if [ -f "$1.odt" ] - then +then + + if [ "x$2" == "xunoconv" ] + then + # See issue https://github.com/dagwieers/unoconv/issues/87 + /usr/bin/unoconv -vvv "$1.odt" + retcode=$? + if [ $retcode -ne 0 ] + then + echo "Error while converting odt to pdf: $retcode" + exit 1 + fi + exit 0 + fi + nbprocess=$(pgrep -c soffice) if [ $nbprocess -ne 1 ] # If there is some soffice process running then @@ -59,8 +79,9 @@ if [ -f "$1.odt" ] echo "Error while converting odt to pdf: $retcode" exit 1 fi + sleep 1 - else +else echo "Error: Odt file $1.odt does not exist" exit 1 fi diff --git a/test/phpunit/FactureTest.php b/test/phpunit/FactureTest.php index 8c3d4a2374a..d3e202f33c2 100644 --- a/test/phpunit/FactureTest.php +++ b/test/phpunit/FactureTest.php @@ -135,7 +135,6 @@ class FactureTest extends PHPUnit_Framework_TestCase $localobject=new Facture($this->savdb); $localobject->initAsSpecimen(); $result=$localobject->create($user); - $this->assertLessThan($result, 0); print __METHOD__." result=".$result."\n"; return $result; @@ -272,12 +271,41 @@ class FactureTest extends PHPUnit_Framework_TestCase $langs=$this->savlangs; $db=$this->savdb; + // Force default setup + unset($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED); + unset($conf->global->INVOICE_CAN_NEVER_BE_REMOVED); + $localobject=new Facture($this->savdb); $result=$localobject->fetch($id); - $result=$localobject->delete($user); - print __METHOD__." id=".$id." result=".$result."\n"; - $this->assertGreaterThanOrEqual(0, $result); + // Create another invoice and validate it after $localobject + $localobject2=new Facture($this->savdb); + $result=$localobject2->initAsSpecimen(); + $result=$localobject2->create($user); + $result=$localobject2->validate($user); + print 'Invoice $localobject ref = '.$localobject->ref."\n"; + print 'Invoice $localobject2 created with ref = '.$localobject2->ref."\n"; + + $conf->global->INVOICE_CAN_NEVER_BE_REMOVED = 1; + + $result=$localobject2->delete($user); // Deletion is KO, option INVOICE_CAN_NEVER_BE_REMOVED is on + print __METHOD__." id=".$localobject2->id." ref=".$localobject2->ref." result=".$result."\n"; + $this->assertEquals(0, $result, 'Deletion should fail, option INVOICE_CAN_NEVER_BE_REMOVED is on'); + + unset($conf->global->INVOICE_CAN_NEVER_BE_REMOVED); + + $result=$localobject->delete($user); // Deletion is KO, it is not last invoice + print __METHOD__." id=".$localobject->id." ref=".$localobject->ref." result=".$result."\n"; + $this->assertEquals(0, $result, 'Deletion should fail, it is not last invoice'); + + $result=$localobject2->delete($user); // Deletion is OK, it is last invoice + print __METHOD__." id=".$localobject2->id." ref=".$localobject2->ref." result=".$result."\n"; + $this->assertGreaterThan(0, $result, 'Deletion should work, it is last invoice'); + + $result=$localobject->delete($user); // Deletion is KO, it is not last invoice + print __METHOD__." id=".$localobject->id." ref=".$localobject->ref." result=".$result."\n"; + $this->assertGreaterThan(0, $result, 'Deletion should work, it is again last invoice'); + return $result; } diff --git a/test/phpunit/NumberingModulesTest.php b/test/phpunit/NumberingModulesTest.php index 401b7ce0058..72229b1c598 100644 --- a/test/phpunit/NumberingModulesTest.php +++ b/test/phpunit/NumberingModulesTest.php @@ -75,7 +75,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase public static function setUpBeforeClass() { global $conf,$user,$langs,$db; - + $db->begin(); // This is to have all actions inside a transaction even if test launched without suite. print __METHOD__."\n"; @@ -128,7 +128,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $user=$this->savuser; $langs=$this->savlangs; $db=$this->savdb; - + require_once dirname(__FILE__).'/../../htdocs/compta/facture/class/facture.class.php'; require_once dirname(__FILE__).'/../../htdocs/core/modules/facture/mod_facture_mercure.php'; @@ -153,7 +153,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $this->assertEquals(1, $result3, 'Test validation of invoice with forced ref is ok'); // counter must start to 1 $result=$localobject->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result, 'Test for is_erasable, 1st invoice'); // Can be deleted + $this->assertGreaterThanOrEqual(1, $result, 'Test for is_erasable, 1st invoice'); // Can be deleted $localobject2=new Facture($this->savdb); $localobject2->initAsSpecimen(); $localobject2->date=dol_mktime(12, 0, 0, 1, 1, 1916); // we use following year for second invoice (there is no reset into mask) @@ -171,7 +171,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $this->assertEquals(1, $result3, 'Test validation of invoice with forced ref is ok'); // counter must start to 1 $result=$localobject2->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result); // Can be deleted + $this->assertGreaterThanOrEqual(1, $result); // Can be deleted $result=$localobject->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; $this->assertEquals(0, $result, 'Test for {yyyy}-{0000} that is_erasable is 0 for 1st invoice'); // 1 can no more be deleted (2 is more recent) @@ -218,7 +218,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $this->assertEquals('192001-0001', $result, 'Test for {yyyy}{mm}-{0000@1} 1st invoice'); // counter must start to 1 $result=$localobject->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result); // Can be deleted + $this->assertGreaterThanOrEqual(1, $result); // Can be deleted $localobject2=new Facture($this->savdb); $localobject2->initAsSpecimen(); $localobject2->date=dol_mktime(12, 0, 0, 1, 1, 1921); // we use following year for second invoice (and there is a reset required) @@ -230,10 +230,10 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $this->assertEquals('192101-0001', $result); // counter must be reseted to 1 $result=$localobject2->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result); // Can be deleted + $this->assertGreaterThanOrEqual(1, $result); // Can be deleted $result=$localobject->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result); // Case 1 can be deleted (because there was a reset for case 2) + $this->assertGreaterThanOrEqual(1, $result); // Case 1 can be deleted (because there was a reset for case 2) // Same but we add month before year and use a year on 2 digits $conf->global->FACTURE_MERCURE_MASK_CREDIT='[mm}{yy}-{0000@1}'; @@ -249,7 +249,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $this->assertEquals('0125-0001', $result, 'Test for {mm}{yy}-{0000@1} 1st invoice'); // counter must start to 1 $result=$localobject->is_erasable(); // This call get getNextNumRef with param 'last' print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result); // Can be deleted + $this->assertGreaterThanOrEqual(1, $result); // Can be deleted $localobject2=new Facture($this->savdb); $localobject2->initAsSpecimen(); $localobject2->date=dol_mktime(12, 0, 0, 1, 1, 1925); // we use same year 1925 for second invoice (and there is a reset required) @@ -261,7 +261,7 @@ class NumberingModulesTest extends PHPUnit_Framework_TestCase $this->assertEquals('0125-0002', $result, 'Test for {mm}{yy}-{0000@1} 2st invoice'); // counter must be now 2 $result=$localobject2->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; - $this->assertEquals(1, $result); // Can be deleted + $this->assertGreaterThanOrEqual(1, $result); // Can be deleted $result=$localobject->is_erasable(); print __METHOD__." is_erasable=".$result."\n"; $this->assertEquals(0, $result); // Case 1 can not be deleted (because there is an invoice 2)