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 d75938891f4..f72e2830106 100644 --- a/ChangeLog +++ b/ChangeLog @@ -16,6 +16,10 @@ Following changes may create regressions for some external modules, but were nec * The substitution key for reference of object is now __REF__ whatever is the object (it replaces __ORDERREF__, __PROPALREF__, ...) * 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 ORDER_SUPPLIER_STATUS_ORDERED +* The trigger ORDER_SUPPLIER_STATUS_RECEIVED_ALL was renamed ORDER_SUPPLIER_STATUS_RECEIVED_COMPLETELY ***** ChangeLog for 6.0.1 compared to 6.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/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/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/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/bookkeeping/thirdparty_lettrage.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php index 5f621a55186..f2cce5bee91 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php @@ -196,7 +196,7 @@ llxHeader ( '', 'Compta - Grand Livre' ); print_liste_field_titre("Docref", "liste.php", "bk.doc_ref" ); // print_liste_field_titre("Numerocompte", "liste.php", "bk.numero_compte" ); // print_liste_field_titre("Code_tiers", "liste.php", "bk.code_tiers" ); - print_liste_field_titre("Labelcompte", "liste.php", "bk_label_compte" ); + print_liste_field_titre("LabelAccount", "liste.php", "bk_label_compte" ); print_liste_field_titre("Debit", "liste.php", "bk.debit" ); print_liste_field_titre("Credit", "liste.php", "bk.credit" ); // print_liste_field_titre("Amount", "liste.php", "bk.montant" ); diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php index 623e54f71fb..f98cb74a456 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php @@ -205,7 +205,7 @@ llxHeader ( '', 'Compta - Grand Livre' ); print_liste_field_titre("Docref", "liste.php", "bk.doc_ref" ); // print_liste_field_titre("Numerocompte", "liste.php", "bk.numero_compte" ); // print_liste_field_titre("Code_tiers", "liste.php", "bk.code_tiers" ); - print_liste_field_titre("Labelcompte", "liste.php", "bk_label_compte" ); + print_liste_field_titre("LabelAccount", "liste.php", "bk_label_compte" ); print_liste_field_titre("Debit", "liste.php", "bk.debit" ); print_liste_field_titre("Credit", "liste.php", "bk.credit" ); print_liste_field_titre("Amount", "liste.php", "bk.montant" ); 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/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/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index bfa0c342245..8f17fad4e17 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -1,12 +1,12 @@ - * Copyright (C) 2007-2010 Jean Heimburger - * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2012 Regis Houssin - * Copyright (C) 2013 Christophe Battarel - * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2014 Olivier Geffroy +/* Copyright (C) 2007-2010 Laurent Destailleur + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013 Christophe Battarel + * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Olivier Geffroy * * 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 @@ -422,7 +422,6 @@ if (! $error && $action == 'writebookkeeping') { $bookkeeping->fk_doc = $key; $bookkeeping->fk_docdet = $val["fk_bank"]; $bookkeeping->numero_compte = $k; - $bookkeeping->label_operation = $val["label"]; $bookkeeping->label_compte = $langs->trans("Bank"); $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; @@ -433,21 +432,28 @@ if (! $error && $action == 'writebookkeeping') { $bookkeeping->fk_user_author = $user->id; $bookkeeping->date_create = $now; - // No subledger_account value for the bank line + // No subledger_account value for the bank line but add a specific label_operation if ($tabtype[$key] == 'payment') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref; } else if ($tabtype[$key] == 'payment_supplier') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref; } else if ($tabtype[$key] == 'payment_expensereport') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref; } else if ($tabtype[$key] == 'payment_salary') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref; } else if ($tabtype[$key] == 'payment_vat') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $ref; } else if ($tabtype[$key] == 'payment_donation') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $ref; } else if ($tabtype[$key] == 'payment_various') { $bookkeeping->subledger_account = ''; + $bookkeeping->label_operation = $ref; } else if ($tabtype[$key] == 'unknown') { // ??? $bookkeeping->subledger_account = ''; @@ -484,7 +490,6 @@ if (! $error && $action == 'writebookkeeping') { $bookkeeping->doc_type = 'bank'; $bookkeeping->fk_doc = $key; $bookkeeping->fk_docdet = $val["fk_bank"]; - $bookkeeping->label_operation = $tabcompany[$key]['name']; $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; $bookkeeping->debit = ($mt < 0 ? - $mt : 0); @@ -495,55 +500,55 @@ if (! $error && $action == 'writebookkeeping') { $bookkeeping->date_create = $now; if ($tabtype[$key] == 'payment') { // If payment is payment of customer invoice, we get ref of invoice - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref; $bookkeeping->subledger_account = $tabcompany[$key]['code_compta']; $bookkeeping->subledger_label = $tabcompany[$key]['name']; $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; $bookkeeping->label_compte = ''; } else if ($tabtype[$key] == 'payment_supplier') { // If payment is payment of supplier invoice, we get ref of invoice - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref; $bookkeeping->subledger_account = $tabcompany[$key]['code_compta']; $bookkeeping->subledger_label = $tabcompany[$key]['name']; $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER; $bookkeeping->label_compte = ''; } else if ($tabtype[$key] == 'payment_expensereport') { - $bookkeeping->label_operation = $tabuser[$key]['name']; + $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref; $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code']; $bookkeeping->subledger_label = $tabuser[$key]['name']; $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT; $bookkeeping->label_compte = ''; } else if ($tabtype[$key] == 'payment_salary') { - $bookkeeping->label_operation = $tabuser[$key]['name']; + $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref; $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code']; $bookkeeping->subledger_label = $tabuser[$key]['name']; $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT; $bookkeeping->label_compte = ''; } else if (in_array($tabtype[$key], array('sc', 'payment_sc'))) { // If payment is payment of social contribution - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $ref; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; $bookkeeping->label_compte = $objmid->labelc; } else if ($tabtype[$key] == 'payment_vat') { - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $ref; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; $bookkeeping->label_compte = ''; } else if ($tabtype[$key] == 'payment_donation') { - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $ref; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; $bookkeeping->label_compte = ''; } else if ($tabtype[$key] == 'payment_various') { - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $ref; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; $bookkeeping->label_compte = ''; } else if ($tabtype[$key] == 'banktransfert') { - $bookkeeping->label_operation = ''; + $bookkeeping->label_operation = $ref; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; @@ -676,9 +681,9 @@ if ($action == 'exportcsv') { // ISO and not UTF8 ! print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print " " . $sep; if ($companystatic->name == '') { - print '"' . $langs->trans('Bank') . " - " . utf8_decode($reflabel) . '"' . $sep; + print '"' . $val['bank_account_ref'] . " - " . utf8_decode($reflabel) . '"' . $sep; } else { - print '"' . $langs->trans("Bank") . ' - ' . utf8_decode($companystatic->name) . '"' . $sep; + print '"' . $val['bank_account_ref'] . ' - ' . utf8_decode($companystatic->name) . '"' . $sep; } print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; @@ -720,9 +725,9 @@ if ($action == 'exportcsv') { // ISO and not UTF8 ! print '"' . length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) . '"' . $sep; print " " . $sep; if ($companystatic->name == '') { - print '"' . $langs->trans("Bank") . ' - ' . utf8_decode($reflabel) . '"' . $sep; + print '"' . $val['bank_account_ref'] . ' - ' . utf8_decode($reflabel) . '"' . $sep; } else { - print '"' . $langs->trans("Bank") . ' - ' . utf8_decode($companystatic->name) . '"' . $sep; + print '"' . $val['bank_account_ref'] . ' - ' . utf8_decode($companystatic->name) . '"' . $sep; } print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"'; @@ -823,7 +828,7 @@ if (empty($action) || $action == 'view') { print "" . $langs->trans("Piece") . ' (' . $langs->trans("ObjectsRef") . ")"; print "" . $langs->trans("AccountAccounting") . ""; print "" . $langs->trans("SubledgerAccount") . ""; - print "" . $langs->trans("Label") . ""; + print "" . $langs->trans("LabelOperation") . ""; print "" . $langs->trans("PaymentMode") . ""; print "" . $langs->trans("Debit") . ""; print "" . $langs->trans("Credit") . ""; diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php index f5ad584399e..c73286a8bdd 100644 --- a/htdocs/accountancy/journal/expensereportsjournal.php +++ b/htdocs/accountancy/journal/expensereportsjournal.php @@ -1,11 +1,11 @@ - * Copyright (C) 2007-2010 Jean Heimburger - * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2012 Regis Houssin - * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2013-2016 Olivier Geffroy - * Copyright (C) 2013-2016 Florian Henry +/* Copyright (C) 2007-2010 Laurent Destailleur + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2016 Olivier Geffroy + * Copyright (C) 2013-2016 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -298,7 +298,7 @@ if ($action == 'writebookkeeping') { $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; - $bookkeeping->label_operation = $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]); + $bookkeeping->label_operation = $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'; $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt < 0) ? 'C' : 'D'; $bookkeeping->debit = ($mt > 0) ? $mt : 0; @@ -552,7 +552,7 @@ if (empty($action) || $action == 'view') { print "" . $langs->trans("Piece") . ' (' . $langs->trans("ExpenseReportRef") . ")"; print "" . $langs->trans("AccountAccounting") . ""; print "" . $langs->trans("SubledgerAccount") . ""; - print "" . $langs->trans("Label") . ""; + print "" . $langs->trans("LabelOperation") . ""; print "" . $langs->trans("Debit") . ""; print "" . $langs->trans("Credit") . ""; print "\n"; @@ -659,7 +659,7 @@ if (empty($action) || $action == 'view') { // Subledger account print ""; print ''; - print "" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).($numtax?' - Localtax '.$numtax:''); + print "" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:''); print ""; print '' . ($mt >= 0 ? price($mt) : '') . ""; print '' . ($mt < 0 ? price(- $mt) : '') . ""; diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index 4838e1814bd..0f9081bdc98 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -100,9 +100,9 @@ $sql .= " WHERE f.fk_statut > 0"; // TODO Facture annulée ? $sql .= " AND fd.fk_code_ventilation > 0"; $sql .= " AND f.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $sql .= " AND f.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_SITUATION . ")"; } else { - $sql .= " AND f.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_DEPOSIT . "," . FactureFournisseur::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_DEPOSIT . "," . FactureFournisseur::TYPE_SITUATION . ")"; } if ($date_start && $date_end) $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'"; @@ -151,7 +151,7 @@ if ($result) { // Define array to display all VAT rates that use this accounting account $compta_tva if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code)) { - $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')]=(vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')); + $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')]=(vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')); } $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df); @@ -224,7 +224,7 @@ if ($action == 'writebookkeeping') { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; $bookkeeping->date_lim_reglement = $val["datereg"]; - $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_ref = $val["refsologest"]; $bookkeeping->date_create = $now; $bookkeeping->doc_type = 'supplier_invoice'; $bookkeeping->fk_doc = $key; @@ -272,12 +272,12 @@ if ($action == 'writebookkeeping') { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; $bookkeeping->date_lim_reglement = $val["datereg"]; - $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_ref = $val["refsologest"]; $bookkeeping->date_create = $now; $bookkeeping->doc_type = 'supplier_invoice'; $bookkeeping->fk_doc = $key; $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add - $bookkeeping->thirdparty_code = $companystatic->code_fournisseur; + $bookkeeping->thirdparty_code = $companystatic->code_fournisseur; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; @@ -326,7 +326,7 @@ if ($action == 'writebookkeeping') { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; $bookkeeping->date_lim_reglement = $val["datereg"]; - $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_ref = $val["refsologest"]; $bookkeeping->date_create = $now; $bookkeeping->doc_type = 'supplier_invoice'; $bookkeeping->fk_doc = $key; @@ -335,7 +335,7 @@ if ($action == 'writebookkeeping') { $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; - $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) . ($numtax?' - Localtax '.$numtax:''); + $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:''); $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt < 0) ? 'C' : 'D'; $bookkeeping->debit = ($mt > 0) ? $mt : 0; @@ -374,8 +374,8 @@ if ($action == 'writebookkeeping') { if ($error >= 10) { - setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors'); - break; // Break in the foreach + setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors'); + break; // Break in the foreach } } } @@ -419,7 +419,6 @@ $form = new Form($db); // Export if ($action == 'exportcsv') { $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL; include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; @@ -445,7 +444,7 @@ if ($action == 'exportcsv') { foreach ( $tabttc[$key] as $k => $mt ) { print '"' . $key . '"' . $sep; print '"' . $date . '"' . $sep; - print '"' . $val["refsuppliersologest"] . '"' . $sep; + print '"' . $val["refsologest"] . '"' . $sep; print '"' . utf8_decode ( dol_trunc($companystatic->name, 32) ). '"' . $sep; print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; print '"' . $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER . '"' . $sep; @@ -465,11 +464,11 @@ if ($action == 'exportcsv') { if ($mt) { print '"' . $key . '"' . $sep; print '"' . $date . '"' . $sep; - print '"' . $val["refsuppliersologest"] . '"' . $sep; + print '"' . $val["refsologest"] . '"' . $sep; print '"' . utf8_decode ( dol_trunc($companystatic->name, 32) ) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print " " . $sep; + print '""' . $sep; print '"' . utf8_decode ( dol_trunc($accountingaccount->label, 32) ) . '"' . $sep; print '"' . utf8_decode ( dol_trunc($companystatic->name, 16) ) . ' - ' . $val["refsuppliersologest"] . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; @@ -478,6 +477,7 @@ if ($action == 'exportcsv') { print "\n"; } } + // VAT $listoftax = array(0, 1, 2); foreach ($listoftax as $numtax) { @@ -489,13 +489,13 @@ if ($action == 'exportcsv') { if ($mt) { print '"' . $key . '"' . $sep; print '"' . $date . '"' . $sep; - print '"' . $val["refsuppliersologest"] . '"' . $sep; + print '"' . $val["refsologest"] . '"' . $sep; print '"' . utf8_decode ( dol_trunc($companystatic->name, 32) ) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print " " . $sep; + print '""' . $sep; print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . '"' . $sep; - print '"' . utf8_decode(dol_trunc($companystatic->name, 16) ) . ' - ' . $val["refsuppliersologest"] . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep; + print '"' . utf8_decode(dol_trunc($companystatic->name, 16) ) . ' - ' . $val["refsuppliersologest"] . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"'. $sep; print '"' . $journal . '"' ; @@ -531,15 +531,15 @@ if (empty($action) || $action == 'view') { // Button to write into Ledger if (empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') { - print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); - print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); + print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); + print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); } print '
'; if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') { - print ''; + print ''; } else { - print ''; + print ''; } print ''; print '
'; @@ -565,7 +565,7 @@ if (empty($action) || $action == 'view') { print '
'; $i = 0; - print '
'; + print '
'; print ""; print ""; print ""; @@ -573,7 +573,7 @@ if (empty($action) || $action == 'view') { print ""; print ""; print ""; - print ""; + print ""; print ""; print ""; print "\n"; @@ -625,8 +625,9 @@ if (empty($action) || $action == 'view') { print ""; print '"; print '"; - print ""; + print ""; } + // Product / Service foreach ( $tabht[$key] as $k => $mt ) { $accountingaccount = new AccountingAccount($db); @@ -683,7 +684,7 @@ if (empty($action) || $action == 'view') { // Subledger account print "'; - print ""; print '"; print '"; diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php index c5cd4f53910..42fbb7ff681 100644 --- a/htdocs/accountancy/journal/sellsjournal.php +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -156,7 +156,7 @@ if ($result) { $compta_localtax2 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva); // Define array to display all VAT rates that use this accounting account $compta_tva - if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code)) + if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code)) { $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')]=(vatrate($obj->tva_tx).($obj->vat_src_code?' ('.$obj->vat_src_code.')':'')); } @@ -295,7 +295,7 @@ if ($action == 'writebookkeeping') { $bookkeeping->doc_type = 'customer_invoice'; $bookkeeping->fk_doc = $key; $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add - $bookkeeping->thirdparty_code = $companystatic->code_client; + $bookkeeping->thirdparty_code = $companystatic->code_client; $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; @@ -353,7 +353,7 @@ if ($action == 'writebookkeeping') { $bookkeeping->subledger_account = ''; $bookkeeping->subledger_label = ''; $bookkeeping->numero_compte = $k; - $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) . ($numtax?' - Localtax '.$numtax:''); + $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:''); $bookkeeping->montant = $mt; $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; $bookkeeping->debit = ($mt < 0) ? -$mt : 0; @@ -392,8 +392,8 @@ if ($action == 'writebookkeeping') { if ($error >= 10) { - setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors'); - break; // Break in the foreach + setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors'); + break; // Break in the foreach } } @@ -441,7 +441,6 @@ $form = new Form($db); if ($action == 'exportcsv') { $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $sell_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; @@ -472,7 +471,7 @@ if ($action == 'exportcsv') { print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; - print '"' . $sell_journal . '"'; + print '"' . $journal . '"'; print "\n"; } @@ -487,12 +486,12 @@ if ($action == 'exportcsv') { print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print " " . $sep; + print '""' . $sep; print '"' . utf8_decode(dol_trunc($accountingaccount->label, 32)) . '"' . $sep; print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . $sell_journal . '"'; + print '"' . $journal . '"'; print "\n"; } } @@ -512,12 +511,12 @@ if ($action == 'exportcsv') { print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print " " . $sep; - print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . '"' . $sep; - print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep; + print '""' . $sep; + print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . ' %"' . $sep; + print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep; print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . $sell_journal . '"'; + print '"' . $journal . '"'; print "\n"; } } @@ -551,12 +550,12 @@ if (empty($action) || $action == 'view') { // Button to write into Ledger if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') { - print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); - print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); + print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone"); + print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); } print '
'; if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') { - print ''; + print ''; } else { print ''; @@ -593,7 +592,7 @@ if (empty($action) || $action == 'view') { print "
"; print ""; print ""; - print ""; + print ""; print ""; print ""; print "\n"; @@ -699,7 +698,7 @@ if (empty($action) || $action == 'view') { // Subledger account print "'; - print ""; print '"; print '"; diff --git a/htdocs/adherents/agenda.php b/htdocs/adherents/agenda.php index 145bcf4e497..1228dc92bf9 100644 --- a/htdocs/adherents/agenda.php +++ b/htdocs/adherents/agenda.php @@ -38,6 +38,28 @@ $langs->load("members"); $id = GETPOST('id','int')?GETPOST('id','int'):GETPOST('rowid','int'); +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) $sortfield='a.datep,a.id'; +if (! $sortorder) $sortorder='DESC'; + +if (GETPOST('actioncode','array')) +{ + $actioncode=GETPOST('actioncode','array',3); + if (! count($actioncode)) $actioncode='0'; +} +else +{ + $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); +} +$search_agenda_label=GETPOST('search_agenda_label'); + // Security check $result=restrictedArea($user,'adherent',$id); @@ -56,7 +78,26 @@ if ($result > 0) * Actions */ -// None +$parameters=array('id'=>$id, 'objcanvas'=>$objcanvas); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) +{ + // Cancel + if (GETPOST('cancel','alpha') && ! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { + $actioncode=''; + $search_agenda_label=''; + } +} @@ -87,41 +128,49 @@ if ($object->id > 0) dol_fiche_head($head, 'agenda', $langs->trans("Member"), -1, 'user'); - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + dol_banner_tab($object, 'rowid', $linkback); - + print '
'; - + print '
'; - + $object->info($id); print dol_print_object_info($object, 1); - - print '
'; + + print ''; dol_fiche_end(); - - /* - * Barre d'action - */ - print '
'; + //print '
'; + //print '
'; + + $morehtmlcenter = ''; if (! empty($conf->agenda->enabled)) { - print ''; + $morehtmlcenter.=''.$langs->trans("AddAction").''; } - print '
'; + if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) + { + print '
'; - $out=''; + $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("ActionsOnMember"),$out,''); + print_barre_liste($langs->trans("ActionsOnMember"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); - // List of actions - show_actions_done($conf,$langs,$db,$object,null,0,'',''); + // List of all actions + $filters=array(); + $filters['search_agenda_label']=$search_agenda_label; + + // TODO Replace this with same code than into listactions.php + show_actions_done($conf,$langs,$db,$object,null,0,$actioncode, '', $filters, $sortfield, $sortorder); + } } diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 0ef0a4e3dc3..5ab8ff1cc99 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -1431,7 +1431,7 @@ else if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; if (! empty($conf->societe->enabled)) $rowspan++; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); @@ -1799,10 +1799,16 @@ else print '
'; + $MAX = 10; + + $morehtmlright = ''; + $morehtmlright.= $langs->trans("SeeAll"); + $morehtmlright.= ''; + // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'member', $socid, 1, 'listactions', 10); + $somethingshown = $formactions->showactions($object, 'member', $socid, 1, 'listactions', $MAX, '', $morehtmlright); print '
'; } diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 5eb757c0c5c..c197d1a2362 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -41,13 +41,13 @@ require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; */ class Adherent extends CommonObject { - public $element='member'; - public $table_element='adherent'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $element='member'; + public $table_element='adherent'; + protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - var $mesgs; + var $mesgs; - var $login; + var $login; //! Clear password in memory var $pass; @@ -57,128 +57,128 @@ class Adherent extends CommonObject var $pass_indatabase_crypted; var $societe; - var $company; - var $address; - var $zip; - var $town; + var $company; + var $address; + var $zip; + var $town; - var $state_id; // Id of department - var $state_code; // Code of department - var $state; // Label of department + var $state_id; // Id of department + var $state_code; // Code of department + var $state; // Label of department - var $email; - var $skype; - var $phone; - var $phone_perso; - var $phone_mobile; + var $email; + var $skype; + var $phone; + var $phone_perso; + var $phone_mobile; - var $morphy; - var $public; - var $statut; // -1:brouillon, 0:resilie, >=1:valide,paye - var $photo; + var $morphy; + var $public; + var $statut; // -1:brouillon, 0:resilie, >=1:valide,paye + var $photo; - var $datec; - var $datem; - var $datefin; - var $datevalid; - var $birth; + var $datec; + var $datem; + var $datefin; + var $datevalid; + var $birth; - var $note_public; - var $note_private; + var $note_public; + var $note_private; - var $typeid; // Id type adherent - var $type; // Libelle type adherent - var $need_subscription; + var $typeid; // Id type adherent + var $type; // Libelle type adherent + var $need_subscription; - var $user_id; - var $user_login; + var $user_id; + var $user_login; - var $fk_soc; + var $fk_soc; - // Fields loaded by fetch_subscriptions() - var $first_subscription_date; - var $first_subscription_amount; - var $last_subscription_date; - var $last_subscription_date_start; - var $last_subscription_date_end; - var $last_subscription_amount; - var $subscriptions=array(); + // Fields loaded by fetch_subscriptions() + var $first_subscription_date; + var $first_subscription_amount; + var $last_subscription_date; + var $last_subscription_date_start; + var $last_subscription_date_end; + var $last_subscription_amount; + var $subscriptions=array(); - var $oldcopy; // To contains a clone of this when we need to save old properties of object + var $oldcopy; // To contains a clone of this when we need to save old properties of object - public $entity; + public $entity; - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - $this->statut = -1; - // l'adherent n'est pas public par defaut - $this->public = 0; - // les champs optionnels sont vides - $this->array_options=array(); - } + */ + function __construct($db) + { + $this->db = $db; + $this->statut = -1; + // l'adherent n'est pas public par defaut + $this->public = 0; + // les champs optionnels sont vides + $this->array_options=array(); + } - /** - * Function sending an email has the adherent with the text supplied in parameter. - * - * @param string $text Content of message (not html entities encoded) - * @param string $subject Subject of message - * @param array $filename_list Array of attached files - * @param array $mimetype_list Array of mime types of attached files - * @param array $mimefilename_list Array of public names of attached files - * @param string $addr_cc Email cc - * @param string $addr_bcc Email bcc - * @param int $deliveryreceipt Ask a delivery receipt - * @param int $msgishtml 1=String IS already html, 0=String IS NOT html, -1=Unknown need autodetection - * @param string $errors_to erros to - * @return int <0 if KO, >0 if OK - */ - function send_an_email($text, $subject, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=-1, $errors_to='') - { - global $conf,$langs; + /** + * Function sending an email has the adherent with the text supplied in parameter. + * + * @param string $text Content of message (not html entities encoded) + * @param string $subject Subject of message + * @param array $filename_list Array of attached files + * @param array $mimetype_list Array of mime types of attached files + * @param array $mimefilename_list Array of public names of attached files + * @param string $addr_cc Email cc + * @param string $addr_bcc Email bcc + * @param int $deliveryreceipt Ask a delivery receipt + * @param int $msgishtml 1=String IS already html, 0=String IS NOT html, -1=Unknown need autodetection + * @param string $errors_to erros to + * @return int <0 if KO, >0 if OK + */ + function send_an_email($text, $subject, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=-1, $errors_to='') + { + global $conf,$langs; - // Detect if message is HTML - if ($msgishtml == -1) - { - $msgishtml = 0; - if (dol_textishtml($text,1)) $msgishtml = 1; - } + // Detect if message is HTML + if ($msgishtml == -1) + { + $msgishtml = 0; + if (dol_textishtml($text,1)) $msgishtml = 1; + } - $texttosend=$this->makeSubstitution($text); - $subjecttosend=$this->makeSubstitution($subject); - if ($msgishtml) $texttosend=dol_htmlentitiesbr($texttosend); + $texttosend=$this->makeSubstitution($text); + $subjecttosend=$this->makeSubstitution($subject); + if ($msgishtml) $texttosend=dol_htmlentitiesbr($texttosend); - // Envoi mail confirmation - $from=$conf->email_from; - if (! empty($conf->global->ADHERENT_MAIL_FROM)) $from=$conf->global->ADHERENT_MAIL_FROM; + // Envoi mail confirmation + $from=$conf->email_from; + if (! empty($conf->global->ADHERENT_MAIL_FROM)) $from=$conf->global->ADHERENT_MAIL_FROM; - // Send email (substitutionarray must be done just before this) - include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($subjecttosend, $this->email, $from, $texttosend, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml); - if ($mailfile->sendfile()) - { - return 1; - } - else - { - $this->error=$langs->trans("ErrorFailedToSendMail",$from,$this->email).'. '.$mailfile->error; - return -1; - } - } + // Send email (substitutionarray must be done just before this) + include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $mailfile = new CMailFile($subjecttosend, $this->email, $from, $texttosend, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml); + if ($mailfile->sendfile()) + { + return 1; + } + else + { + $this->error=$langs->trans("ErrorFailedToSendMail",$from,$this->email).'. '.$mailfile->error; + return -1; + } + } - /** - * Make substitution of tags into text with value of current object. - * - * @param string $text Text to make substitution to - * @return string Value of input text string with substitutions done - */ + /** + * Make substitution of tags into text with value of current object. + * + * @param string $text Text to make substitution to + * @return string Value of input text string with substitutions done + */ function makeSubstitution($text) { global $conf,$langs; @@ -199,13 +199,13 @@ class Adherent extends CommonObject $infos.= $langs->transnoentities("Town").": ".$this->town."\n"; $infos.= $langs->transnoentities("Country").": ".$this->country."\n"; $infos.= $langs->transnoentities("EMail").": ".$this->email."\n"; - $infos.= $langs->transnoentities("PhonePro").": ".$this->phone."\n"; - $infos.= $langs->transnoentities("PhonePerso").": ".$this->phone_perso."\n"; - $infos.= $langs->transnoentities("PhoneMobile").": ".$this->phone_mobile."\n"; + $infos.= $langs->transnoentities("PhonePro").": ".$this->phone."\n"; + $infos.= $langs->transnoentities("PhonePerso").": ".$this->phone_perso."\n"; + $infos.= $langs->transnoentities("PhoneMobile").": ".$this->phone_mobile."\n"; if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { - $infos.= $langs->transnoentities("Login").": ".$this->login."\n"; - $infos.= $langs->transnoentities("Password").": ".$this->pass."\n"; + $infos.= $langs->transnoentities("Login").": ".$this->login."\n"; + $infos.= $langs->transnoentities("Password").": ".$this->pass."\n"; } $infos.= $langs->transnoentities("Birthday").": ".$birthday."\n"; $infos.= $langs->transnoentities("Photo").": ".$this->photo."\n"; @@ -238,164 +238,164 @@ class Adherent extends CommonObject } - /** - * Return translated label by the nature of a adherent (physical or moral) - * - * @param string $morphy Nature of the adherent (physical or moral) - * @return string Label - */ - function getmorphylib($morphy='') - { - global $langs; - if (! $morphy) { $morphy=$this->morphy; } - if ($morphy == 'phy') { return $langs->trans("Physical"); } - if ($morphy == 'mor') { return $langs->trans("Moral"); } - return $morphy; - } + /** + * Return translated label by the nature of a adherent (physical or moral) + * + * @param string $morphy Nature of the adherent (physical or moral) + * @return string Label + */ + function getmorphylib($morphy='') + { + global $langs; + if (! $morphy) { $morphy=$this->morphy; } + if ($morphy == 'phy') { return $langs->trans("Physical"); } + if ($morphy == 'mor') { return $langs->trans("Moral"); } + return $morphy; + } - /** - * Create a member into database - * - * @param User $user Objet user qui demande la creation - * @param int $notrigger 1 ne declenche pas les triggers, 0 sinon - * @return int <0 if KO, >0 if OK - */ - function create($user,$notrigger=0) - { - global $conf,$langs; + /** + * Create a member into database + * + * @param User $user Objet user qui demande la creation + * @param int $notrigger 1 ne declenche pas les triggers, 0 sinon + * @return int <0 if KO, >0 if OK + */ + function create($user,$notrigger=0) + { + global $conf,$langs; $error=0; - $now=dol_now(); + $now=dol_now(); - // Clean parameters - $this->import_key = trim($this->import_key); + // Clean parameters + $this->import_key = trim($this->import_key); - // Check parameters - if (! empty($conf->global->ADHERENT_MAIL_REQUIRED) && ! isValidEMail($this->email)) - { - $langs->load("errors"); - $this->error = $langs->trans("ErrorBadEMail",$this->email); - return -1; - } - if (! $this->datec) $this->datec=$now; - if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) - { - if (empty($this->login)) - { - $this->error = $langs->trans("ErrorWrongValueForParameterX","Login"); - return -1; - } - } + // Check parameters + if (! empty($conf->global->ADHERENT_MAIL_REQUIRED) && ! isValidEMail($this->email)) + { + $langs->load("errors"); + $this->error = $langs->trans("ErrorBadEMail",$this->email); + return -1; + } + if (! $this->datec) $this->datec=$now; + if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) + { + if (empty($this->login)) + { + $this->error = $langs->trans("ErrorWrongValueForParameterX","Login"); + return -1; + } + } - $this->db->begin(); + $this->db->begin(); - // Insert member - $sql = "INSERT INTO ".MAIN_DB_PREFIX."adherent"; - $sql.= " (datec,login,fk_user_author,fk_user_mod,fk_user_valid,morphy,fk_adherent_type,entity,import_key)"; - $sql.= " VALUES ("; - $sql.= " '".$this->db->idate($this->datec)."'"; - $sql.= ", ".($this->login?"'".$this->db->escape($this->login)."'":"null"); - $sql.= ", ".($user->id>0?$user->id:"null"); // Can be null because member can be created by a guest or a script - $sql.= ", null, null, '".$this->db->escape($this->morphy)."'"; - $sql.= ", ".$this->typeid; - $sql.= ", ".$conf->entity; - $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ")"; + // Insert member + $sql = "INSERT INTO ".MAIN_DB_PREFIX."adherent"; + $sql.= " (datec,login,fk_user_author,fk_user_mod,fk_user_valid,morphy,fk_adherent_type,entity,import_key)"; + $sql.= " VALUES ("; + $sql.= " '".$this->db->idate($this->datec)."'"; + $sql.= ", ".($this->login?"'".$this->db->escape($this->login)."'":"null"); + $sql.= ", ".($user->id>0?$user->id:"null"); // Can be null because member can be created by a guest or a script + $sql.= ", null, null, '".$this->db->escape($this->morphy)."'"; + $sql.= ", ".$this->typeid; + $sql.= ", ".$conf->entity; + $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null"); + $sql.= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $id = $this->db->last_insert_id(MAIN_DB_PREFIX."adherent"); - if ($id > 0) - { - $this->id=$id; - $this->ref=(string) $id; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $id = $this->db->last_insert_id(MAIN_DB_PREFIX."adherent"); + if ($id > 0) + { + $this->id=$id; + $this->ref=(string) $id; - // Update minor fields - $result=$this->update($user,1,1,0,0,'add'); // nosync is 1 to avoid update data of user - if ($result < 0) - { - $this->db->rollback(); - return -1; - } + // Update minor fields + $result=$this->update($user,1,1,0,0,'add'); // nosync is 1 to avoid update data of user + if ($result < 0) + { + $this->db->rollback(); + return -1; + } - // Add link to user - if ($this->user_id) - { - // Add link to user - $sql = "UPDATE ".MAIN_DB_PREFIX."user SET"; - $sql.= " fk_member = ".$this->id; - $sql.= " WHERE rowid = ".$this->user_id; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error='Failed to update user to make link with member'; - $this->db->rollback(); - return -4; - } - } + // Add link to user + if ($this->user_id) + { + // Add link to user + $sql = "UPDATE ".MAIN_DB_PREFIX."user SET"; + $sql.= " fk_member = ".$this->id; + $sql.= " WHERE rowid = ".$this->user_id; + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error='Failed to update user to make link with member'; + $this->db->rollback(); + return -4; + } + } - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('MEMBER_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('MEMBER_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - if (count($this->errors)) - { - dol_syslog(get_class($this)."::create ".implode(',',$this->errors), LOG_ERR); - $this->db->rollback(); - return -3; - } - else - { - $this->db->commit(); - return $this->id; - } - } - else - { - $this->error='Failed to get last insert id'; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } + if (count($this->errors)) + { + dol_syslog(get_class($this)."::create ".implode(',',$this->errors), LOG_ERR); + $this->db->rollback(); + return -3; + } + else + { + $this->db->commit(); + return $this->id; + } + } + else + { + $this->error='Failed to get last insert id'; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Update a member in database (standard information and password) - * - * @param User $user User making update - * @param int $notrigger 1=disable trigger UPDATE (when called by create) - * @param int $nosyncuser 0=Synchronize linked user (standard info), 1=Do not synchronize linked user - * @param int $nosyncuserpass 0=Synchronize linked user (password), 1=Do not synchronize linked user - * @param int $nosyncthirdparty 0=Synchronize linked thirdparty (standard info), 1=Do not synchronize linked thirdparty - * @param string $action Current action for hookmanager - * @return int <0 if KO, >0 if OK - */ - function update($user,$notrigger=0,$nosyncuser=0,$nosyncuserpass=0,$nosyncthirdparty=0,$action='update') - { - global $conf, $langs, $hookmanager; + /** + * Update a member in database (standard information and password) + * + * @param User $user User making update + * @param int $notrigger 1=disable trigger UPDATE (when called by create) + * @param int $nosyncuser 0=Synchronize linked user (standard info), 1=Do not synchronize linked user + * @param int $nosyncuserpass 0=Synchronize linked user (password), 1=Do not synchronize linked user + * @param int $nosyncthirdparty 0=Synchronize linked thirdparty (standard info), 1=Do not synchronize linked thirdparty + * @param string $action Current action for hookmanager + * @return int <0 if KO, >0 if OK + */ + function update($user,$notrigger=0,$nosyncuser=0,$nosyncuserpass=0,$nosyncthirdparty=0,$action='update') + { + global $conf, $langs, $hookmanager; - $nbrowsaffected=0; - $error=0; + $nbrowsaffected=0; + $error=0; - dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncuser=".$nosyncuser.", nosyncuserpass=".$nosyncuserpass." nosyncthirdparty=".$nosyncthirdparty.", email=".$this->email); + dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncuser=".$nosyncuser.", nosyncuserpass=".$nosyncuserpass." nosyncthirdparty=".$nosyncthirdparty.", email=".$this->email); - // Clean parameters + // Clean parameters $this->lastname=trim($this->lastname)?trim($this->lastname):trim($this->lastname); $this->firstname=trim($this->firstname)?trim($this->firstname):trim($this->firstname); $this->address=($this->address?$this->address:$this->address); @@ -408,288 +408,288 @@ class Adherent extends CommonObject $this->note_public=($this->note_public?$this->note_public:$this->note_public); $this->note_private=($this->note_private?$this->note_private:$this->note_private); - // Check parameters - if (! empty($conf->global->ADHERENT_MAIL_REQUIRED) && ! isValidEMail($this->email)) - { - $langs->load("errors"); - $this->error = $langs->trans("ErrorBadEMail",$this->email); - return -1; - } + // Check parameters + if (! empty($conf->global->ADHERENT_MAIL_REQUIRED) && ! isValidEMail($this->email)) + { + $langs->load("errors"); + $this->error = $langs->trans("ErrorBadEMail",$this->email); + return -1; + } - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " civility = ".($this->civility_id>0?$this->db->escape($this->civility_id):"null"); - $sql.= ", firstname = ".($this->firstname?"'".$this->db->escape($this->firstname)."'":"null"); - $sql.= ", lastname = ".($this->lastname?"'".$this->db->escape($this->lastname)."'":"null"); - $sql.= ", login = ".($this->login?"'".$this->db->escape($this->login)."'":"null"); - $sql.= ", societe = ".($this->societe?"'".$this->db->escape($this->societe)."'":"null"); - $sql.= ", fk_soc = ".($this->fk_soc > 0?$this->db->escape($this->fk_soc):"null"); - $sql.= ", address = ".($this->address?"'".$this->db->escape($this->address)."'":"null"); - $sql.= ", zip = ".($this->zip?"'".$this->db->escape($this->zip)."'":"null"); - $sql.= ", town = ".($this->town?"'".$this->db->escape($this->town)."'":"null"); - $sql.= ", country = ".($this->country_id>0?$this->db->escape($this->country_id):"null"); - $sql.= ", state_id = ".($this->state_id>0?$this->db->escape($this->state_id):"null"); - $sql.= ", email = '".$this->db->escape($this->email)."'"; - $sql.= ", skype = '".$this->db->escape($this->skype)."'"; - $sql.= ", phone = ".($this->phone?"'".$this->db->escape($this->phone)."'":"null"); - $sql.= ", phone_perso = ".($this->phone_perso?"'".$this->db->escape($this->phone_perso)."'":"null"); - $sql.= ", phone_mobile = ".($this->phone_mobile?"'".$this->db->escape($this->phone_mobile)."'":"null"); - $sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); - $sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); - $sql.= ", photo = ".($this->photo?"'".$this->db->escape($this->photo)."'":"null"); - $sql.= ", public = '".$this->db->escape($this->public)."'"; - $sql.= ", statut = ".$this->statut; - $sql.= ", fk_adherent_type = ".$this->typeid; - $sql.= ", morphy = '".$this->db->escape($this->morphy)."'"; - $sql.= ", birth = ".($this->birth?"'".$this->db->idate($this->birth)."'":"null"); - if ($this->datefin) $sql.= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription - if ($this->datevalid) $sql.= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member - $sql.= ", fk_user_mod = ".($user->id>0?$user->id:'null'); // Can be null because member can be create by a guest - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; + $sql.= " civility = ".($this->civility_id?"'".$this->db->escape($this->civility_id)."'":"null"); + $sql.= ", firstname = ".($this->firstname?"'".$this->db->escape($this->firstname)."'":"null"); + $sql.= ", lastname = ".($this->lastname?"'".$this->db->escape($this->lastname)."'":"null"); + $sql.= ", login = ".($this->login?"'".$this->db->escape($this->login)."'":"null"); + $sql.= ", societe = ".($this->societe?"'".$this->db->escape($this->societe)."'":"null"); + $sql.= ", fk_soc = ".($this->fk_soc > 0?$this->db->escape($this->fk_soc):"null"); + $sql.= ", address = ".($this->address?"'".$this->db->escape($this->address)."'":"null"); + $sql.= ", zip = ".($this->zip?"'".$this->db->escape($this->zip)."'":"null"); + $sql.= ", town = ".($this->town?"'".$this->db->escape($this->town)."'":"null"); + $sql.= ", country = ".($this->country_id>0?$this->db->escape($this->country_id):"null"); + $sql.= ", state_id = ".($this->state_id>0?$this->db->escape($this->state_id):"null"); + $sql.= ", email = '".$this->db->escape($this->email)."'"; + $sql.= ", skype = '".$this->db->escape($this->skype)."'"; + $sql.= ", phone = ".($this->phone?"'".$this->db->escape($this->phone)."'":"null"); + $sql.= ", phone_perso = ".($this->phone_perso?"'".$this->db->escape($this->phone_perso)."'":"null"); + $sql.= ", phone_mobile = ".($this->phone_mobile?"'".$this->db->escape($this->phone_mobile)."'":"null"); + $sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); + $sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); + $sql.= ", photo = ".($this->photo?"'".$this->db->escape($this->photo)."'":"null"); + $sql.= ", public = '".$this->db->escape($this->public)."'"; + $sql.= ", statut = ".$this->statut; + $sql.= ", fk_adherent_type = ".$this->typeid; + $sql.= ", morphy = '".$this->db->escape($this->morphy)."'"; + $sql.= ", birth = ".($this->birth?"'".$this->db->idate($this->birth)."'":"null"); + if ($this->datefin) $sql.= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription + if ($this->datevalid) $sql.= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member + $sql.= ", fk_user_mod = ".($user->id>0?$user->id:'null'); // Can be null because member can be create by a guest + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update update member", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - unset($this->country_code); - unset($this->country); - unset($this->state_code); - unset($this->state); + dol_syslog(get_class($this)."::update update member", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + unset($this->country_code); + unset($this->country); + unset($this->state_code); + unset($this->state); - $nbrowsaffected+=$this->db->affected_rows($resql); + $nbrowsaffected+=$this->db->affected_rows($resql); - $action='update'; + $action='update'; - // Actions on extra fields (by external module) + // Actions on extra fields (by external module) // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('memberdao')); - $parameters=array('id'=>$this->id); - $action=''; - $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++; + $hookmanager->initHooks(array('memberdao')); + $parameters=array('id'=>$this->id); + $action=''; + $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++; - // Update password - if (! $error && $this->pass) - { - dol_syslog(get_class($this)."::update update password"); - if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) - { - $isencrypted = empty($conf->global->DATABASE_PWD_ENCRYPTED)?0:1; + // Update password + if (! $error && $this->pass) + { + dol_syslog(get_class($this)."::update update password"); + if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) + { + $isencrypted = empty($conf->global->DATABASE_PWD_ENCRYPTED)?0:1; - // If password to set differs from the one found into database - $result=$this->setPassword($user,$this->pass,$isencrypted,$notrigger,$nosyncuserpass); - if (! $nbrowsaffected) $nbrowsaffected++; - } - } + // If password to set differs from the one found into database + $result=$this->setPassword($user,$this->pass,$isencrypted,$notrigger,$nosyncuserpass); + if (! $nbrowsaffected) $nbrowsaffected++; + } + } - // Remove links to user and replace with new one - if (! $error) - { - dol_syslog(get_class($this)."::update update link to user"); - $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".$this->id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } - // If there is a user linked to this member - if ($this->user_id > 0) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".$this->id." WHERE rowid = ".$this->user_id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } - } - } + // Remove links to user and replace with new one + if (! $error) + { + dol_syslog(get_class($this)."::update update link to user"); + $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".$this->id; + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } + // If there is a user linked to this member + if ($this->user_id > 0) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".$this->id." WHERE rowid = ".$this->user_id; + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -5; } + } + } - if (! $error && $nbrowsaffected) // If something has change in main data - { - // Update information on linked user if it is an update - if (! $error && $this->user_id > 0 && ! $nosyncuser) - { - require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + if (! $error && $nbrowsaffected) // If something has change in main data + { + // Update information on linked user if it is an update + if (! $error && $this->user_id > 0 && ! $nosyncuser) + { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - dol_syslog(get_class($this)."::update update linked user"); + dol_syslog(get_class($this)."::update update linked user"); - $luser=new User($this->db); - $result=$luser->fetch($this->user_id); + $luser=new User($this->db); + $result=$luser->fetch($this->user_id); - if ($result >= 0) - { - //var_dump($this->user_login);exit; - //var_dump($this->login);exit; - $luser->login=$this->login; - $luser->civility_id=$this->civility_id; - $luser->firstname=$this->firstname; - $luser->lastname=$this->lastname; - $luser->pass=$this->pass; - $luser->societe_id=$this->societe; + if ($result >= 0) + { + //var_dump($this->user_login);exit; + //var_dump($this->login);exit; + $luser->login=$this->login; + $luser->civility_id=$this->civility_id; + $luser->firstname=$this->firstname; + $luser->lastname=$this->lastname; + $luser->pass=$this->pass; + $luser->societe_id=$this->societe; - $luser->email=$this->email; - $luser->skype=$this->skype; - $luser->office_phone=$this->phone; - $luser->user_mobile=$this->phone_mobile; + $luser->email=$this->email; + $luser->skype=$this->skype; + $luser->office_phone=$this->phone; + $luser->user_mobile=$this->phone_mobile; - $luser->fk_member=$this->id; + $luser->fk_member=$this->id; - $result=$luser->update($user,0,1,1); // Use nosync to 1 to avoid cyclic updates - if ($result < 0) - { - $this->error=$luser->error; - dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); - $error++; - } - } - else - { - $this->error=$luser->error; - $error++; - } - } + $result=$luser->update($user,0,1,1); // Use nosync to 1 to avoid cyclic updates + if ($result < 0) + { + $this->error=$luser->error; + dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); + $error++; + } + } + else + { + $this->error=$luser->error; + $error++; + } + } - // Update information on linked thirdparty if it is an update - if (! $error && $this->fk_soc > 0 && ! $nosyncthirdparty) - { - require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + // Update information on linked thirdparty if it is an update + if (! $error && $this->fk_soc > 0 && ! $nosyncthirdparty) + { + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - dol_syslog(get_class($this)."::update update linked thirdparty"); + dol_syslog(get_class($this)."::update update linked thirdparty"); - // This member is linked with a thirdparty, so we also update thirdparty informations - // if this is an update. - $lthirdparty=new Societe($this->db); - $result=$lthirdparty->fetch($this->fk_soc); + // This member is linked with a thirdparty, so we also update thirdparty informations + // if this is an update. + $lthirdparty=new Societe($this->db); + $result=$lthirdparty->fetch($this->fk_soc); - if ($result >= 0) - { - $lthirdparty->address=$this->address; - $lthirdparty->zip=$this->zip; - $lthirdparty->town=$this->town; - $lthirdparty->email=$this->email; - $lthirdparty->skype=$this->skype; - $lthirdparty->phone=$this->phone; - $lthirdparty->state_id=$this->state_id; - $lthirdparty->country_id=$this->country_id; - $lthirdparty->country_id=$this->country_id; - //$lthirdparty->phone_mobile=$this->phone_mobile; + if ($result >= 0) + { + $lthirdparty->address=$this->address; + $lthirdparty->zip=$this->zip; + $lthirdparty->town=$this->town; + $lthirdparty->email=$this->email; + $lthirdparty->skype=$this->skype; + $lthirdparty->phone=$this->phone; + $lthirdparty->state_id=$this->state_id; + $lthirdparty->country_id=$this->country_id; + $lthirdparty->country_id=$this->country_id; + //$lthirdparty->phone_mobile=$this->phone_mobile; - $result=$lthirdparty->update($this->fk_soc,$user,0,1,1,'update'); // Use sync to 0 to avoid cyclic updates - if ($result < 0) - { - $this->error=$lthirdparty->error; - dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); - $error++; - } - } - else - { - $this->error=$lthirdparty->error; - $error++; - } - } + $result=$lthirdparty->update($this->fk_soc,$user,0,1,1,'update'); // Use sync to 0 to avoid cyclic updates + if ($result < 0) + { + $this->error=$lthirdparty->error; + dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); + $error++; + } + } + else + { + $this->error=$lthirdparty->error; + $error++; + } + } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('MEMBER_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('MEMBER_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + } - if (! $error) - { - $this->db->commit(); - return $nbrowsaffected; - } - else - { - $this->db->rollback(); - return -1; - } - } - else - { - $this->db->rollback(); - $this->error=$this->db->lasterror(); - return -2; - } - } + if (! $error) + { + $this->db->commit(); + return $nbrowsaffected; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->db->rollback(); + $this->error=$this->db->lasterror(); + return -2; + } + } - /** - * Update denormalized last subscription date. - * This function is called when we delete a subscription for example. - * - * @param User $user User making change - * @return int <0 if KO, >0 if OK - */ - function update_end_date($user) - { - $this->db->begin(); + /** + * Update denormalized last subscription date. + * This function is called when we delete a subscription for example. + * + * @param User $user User making change + * @return int <0 if KO, >0 if OK + */ + function update_end_date($user) + { + $this->db->begin(); - // Search for last subscription id and end date - $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."subscription"; - $sql.= " WHERE fk_adherent=".$this->id; - $sql.= " ORDER by dateadh DESC"; // Sort by start subscription date + // Search for last subscription id and end date + $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin"; + $sql.= " FROM ".MAIN_DB_PREFIX."subscription"; + $sql.= " WHERE fk_adherent=".$this->id; + $sql.= " ORDER by dateadh DESC"; // Sort by start subscription date - dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $obj=$this->db->fetch_object($resql); - $dateop=$this->db->jdate($obj->dateop); - $datedeb=$this->db->jdate($obj->datedeb); - $datefin=$this->db->jdate($obj->datefin); + dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj=$this->db->fetch_object($resql); + $dateop=$this->db->jdate($obj->dateop); + $datedeb=$this->db->jdate($obj->datedeb); + $datefin=$this->db->jdate($obj->datefin); - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " datefin=".($datefin != '' ? "'".$this->db->idate($datefin)."'" : "null"); - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; + $sql.= " datefin=".($datefin != '' ? "'".$this->db->idate($datefin)."'" : "null"); + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->last_subscription_date=$dateop; - $this->last_subscription_date_start=$datedeb; - $this->last_subscription_date_end=$datefin; - $this->datefin=$datefin; - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } + dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $this->last_subscription_date=$dateop; + $this->last_subscription_date_start=$datedeb; + $this->last_subscription_date_end=$datefin; + $this->datefin=$datefin; + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } - } + } - /** - * Fonction qui supprime l'adherent et les donnees associees - * - * @param int $rowid Id of member to delete - * @param User $user User object - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * @return int <0 if KO, 0=nothing to do, >0 if OK - */ + /** + * Fonction qui supprime l'adherent et les donnees associees + * + * @param int $rowid Id of member to delete + * @param User $user User object + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, 0=nothing to do, >0 if OK + */ function delete($rowid, $user, $notrigger=0) { global $conf, $langs; @@ -701,15 +701,15 @@ class Adherent extends CommonObject // Check parameters if (empty($rowid)) $rowid=$this->id; - $this->db->begin(); + $this->db->begin(); - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('MEMBER_DELETE',$user); - if ($result < 0) $error++; - // End call triggers - } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('MEMBER_DELETE',$user); + if ($result < 0) $error++; + // End call triggers + } // Remove category $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_member WHERE fk_member = ".$rowid; @@ -790,1265 +790,1325 @@ class Adherent extends CommonObject } - /** - * Change password of a user - * - * @param User $user Object user de l'utilisateur qui fait la modification - * @param string $password New password (to generate if empty) - * @param int $isencrypted 0 ou 1 si il faut crypter le mot de passe en base (0 par defaut) - * @param int $notrigger 1=Ne declenche pas les triggers - * @param int $nosyncuser Do not synchronize linked user - * @return string If OK return clear password, 0 if no change, < 0 if error - */ - function setPassword($user, $password='', $isencrypted=0, $notrigger=0, $nosyncuser=0) - { - global $conf, $langs; + /** + * Change password of a user + * + * @param User $user Object user de l'utilisateur qui fait la modification + * @param string $password New password (to generate if empty) + * @param int $isencrypted 0 ou 1 si il faut crypter le mot de passe en base (0 par defaut) + * @param int $notrigger 1=Ne declenche pas les triggers + * @param int $nosyncuser Do not synchronize linked user + * @return string If OK return clear password, 0 if no change, < 0 if error + */ + function setPassword($user, $password='', $isencrypted=0, $notrigger=0, $nosyncuser=0) + { + global $conf, $langs; - $error=0; + $error=0; - dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i','*',$password)." isencrypted=".$isencrypted); + dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i','*',$password)." isencrypted=".$isencrypted); - // If new password not provided, we generate one - if (! $password) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; - $password=getRandomPassword(false); - } + // If new password not provided, we generate one + if (! $password) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $password=getRandomPassword(false); + } - // Crypt password - $password_crypted = dol_hash($password); + // Crypt password + $password_crypted = dol_hash($password); - $password_indatabase = ''; - if (! $isencrypted) - { - $password_indatabase = $password; - } + $password_indatabase = ''; + if (! $isencrypted) + { + $password_indatabase = $password; + } - $this->db->begin(); + $this->db->begin(); - // Mise a jour - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; - $sql.= " SET pass_crypted = '".$this->db->escape($password_crypted)."'"; - //if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) - if ($isencrypted) - { - $sql.= ", pass = null"; - } - else - { - $sql.= ", pass = '".$this->db->escape($password_indatabase)."'"; - } - $sql.= " WHERE rowid = ".$this->id; + // Mise a jour + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; + $sql.= " SET pass_crypted = '".$this->db->escape($password_crypted)."'"; + //if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) + if ($isencrypted) + { + $sql.= ", pass = null"; + } + else + { + $sql.= ", pass = '".$this->db->escape($password_indatabase)."'"; + } + $sql.= " WHERE rowid = ".$this->id; - //dol_syslog("Adherent::Password sql=hidden"); - dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $nbaffectedrows=$this->db->affected_rows($result); + //dol_syslog("Adherent::Password sql=hidden"); + dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $nbaffectedrows=$this->db->affected_rows($result); - if ($nbaffectedrows) - { - $this->pass=$password; - $this->pass_indatabase=$password_indatabase; - $this->pass_indatabase_crypted=$password_crypted; + if ($nbaffectedrows) + { + $this->pass=$password; + $this->pass_indatabase=$password_indatabase; + $this->pass_indatabase_crypted=$password_crypted; - if ($this->user_id && ! $nosyncuser) - { - require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + if ($this->user_id && ! $nosyncuser) + { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - // This member is linked with a user, so we also update users informations - // if this is an update. - $luser=new User($this->db); - $result=$luser->fetch($this->user_id); + // This member is linked with a user, so we also update users informations + // if this is an update. + $luser=new User($this->db); + $result=$luser->fetch($this->user_id); - if ($result >= 0) - { - $result=$luser->setPassword($user,$this->pass,0,0,1); - if ($result < 0) - { - $this->error=$luser->error; - dol_syslog(get_class($this)."::setPassword ".$this->error,LOG_ERR); - $error++; - } - } - else - { - $this->error=$luser->error; - $error++; - } - } + if ($result >= 0) + { + $result=$luser->setPassword($user,$this->pass,0,0,1); + if ($result < 0) + { + $this->error=$luser->error; + dol_syslog(get_class($this)."::setPassword ".$this->error,LOG_ERR); + $error++; + } + } + else + { + $this->error=$luser->error; + $error++; + } + } - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('MEMBER_NEW_PASSWORD',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers - } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('MEMBER_NEW_PASSWORD',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers + } - $this->db->commit(); - return $this->pass; - } - else - { - $this->db->rollback(); - return 0; - } - } - else - { - $this->db->rollback(); - dol_print_error($this->db); - return -1; - } - } + $this->db->commit(); + return $this->pass; + } + else + { + $this->db->rollback(); + return 0; + } + } + else + { + $this->db->rollback(); + dol_print_error($this->db); + return -1; + } + } - /** - * Set link to a user - * - * @param int $userid Id of user to link to - * @return int 1=OK, -1=KO - */ - function setUserId($userid) - { - global $conf, $langs; + /** + * Set link to a user + * + * @param int $userid Id of user to link to + * @return int 1=OK, -1=KO + */ + function setUserId($userid) + { + global $conf, $langs; - $this->db->begin(); + $this->db->begin(); - // If user is linked to this member, remove old link to this member - $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".$this->id; - dol_syslog(get_class($this)."::setUserId", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -1; } + // If user is linked to this member, remove old link to this member + $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".$this->id; + dol_syslog(get_class($this)."::setUserId", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -1; } - // Set link to user - if ($userid > 0) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".$this->id; - $sql.= " WHERE rowid = ".$userid; - dol_syslog(get_class($this)."::setUserId", LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -2; } - } + // Set link to user + if ($userid > 0) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".$this->id; + $sql.= " WHERE rowid = ".$userid; + dol_syslog(get_class($this)."::setUserId", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $this->error=$this->db->error(); $this->db->rollback(); return -2; } + } - $this->db->commit(); + $this->db->commit(); - return 1; - } + return 1; + } - /** - * Set link to a third party - * - * @param int $thirdpartyid Id of user to link to - * @return int 1=OK, -1=KO - */ - function setThirdPartyId($thirdpartyid) - { - global $conf, $langs; + /** + * Set link to a third party + * + * @param int $thirdpartyid Id of user to link to + * @return int 1=OK, -1=KO + */ + function setThirdPartyId($thirdpartyid) + { + global $conf, $langs; - $this->db->begin(); + $this->db->begin(); - // Remove link to third party onto any other members - if ($thirdpartyid > 0) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = null"; - $sql.= " WHERE fk_soc = '".$thirdpartyid."'"; - $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG); - $resql = $this->db->query($sql); - } + // Remove link to third party onto any other members + if ($thirdpartyid > 0) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = null"; + $sql.= " WHERE fk_soc = '".$thirdpartyid."'"; + $sql.= " AND entity = ".$conf->entity; + dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG); + $resql = $this->db->query($sql); + } - // Add link to third party for current member - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = ".($thirdpartyid>0 ? $thirdpartyid : 'null'); - $sql.= " WHERE rowid = ".$this->id; + // Add link to third party for current member + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = ".($thirdpartyid>0 ? $thirdpartyid : 'null'); + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } + dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Method to load member from its login - * - * @param string $login login of member - * @return void - */ - function fetch_login($login) - { - global $conf; + /** + * Method to load member from its login + * + * @param string $login login of member + * @return void + */ + function fetch_login($login) + { + global $conf; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; - $sql.= " WHERE login='".$this->db->escape($login)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; + $sql.= " WHERE login='".$this->db->escape($login)."'"; + $sql.= " AND entity = ".$conf->entity; - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - $this->fetch($obj->rowid); - } - } - else - { - dol_print_error($this->db); - } - } + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + $this->fetch($obj->rowid); + } + } + else + { + dol_print_error($this->db); + } + } - /** - * Method to load member from its name - * - * @param string $firstname Firstname - * @param string $lastname Lastname - * @return void - */ - function fetch_name($firstname,$lastname) - { - global $conf; + /** + * Method to load member from its name + * + * @param string $firstname Firstname + * @param string $lastname Lastname + * @return void + */ + function fetch_name($firstname,$lastname) + { + global $conf; - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; - $sql.= " WHERE firstname='".$this->db->escape($firstname)."'"; - $sql.= " AND lastname='".$this->db->escape($lastname)."'"; - $sql.= " AND entity = ".$conf->entity; + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent"; + $sql.= " WHERE firstname='".$this->db->escape($firstname)."'"; + $sql.= " AND lastname='".$this->db->escape($lastname)."'"; + $sql.= " AND entity = ".$conf->entity; - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - $this->fetch($obj->rowid); - } - } - else - { - dol_print_error($this->db); - } - } + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + $this->fetch($obj->rowid); + } + } + else + { + dol_print_error($this->db); + } + } - /** - * Load member from database - * - * @param int $rowid Id of object to load - * @param string $ref To load member from its ref - * @param int $fk_soc To load member from its link to third party - * @param string $ref_ext External reference - * @return int >0 if OK, 0 if not found, <0 if KO - */ - function fetch($rowid,$ref='',$fk_soc='',$ref_ext='') - { - global $langs; + /** + * Load member from database + * + * @param int $rowid Id of object to load + * @param string $ref To load member from its ref + * @param int $fk_soc To load member from its link to third party + * @param string $ref_ext External reference + * @return int >0 if OK, 0 if not found, <0 if KO + */ + function fetch($rowid,$ref='',$fk_soc='',$ref_ext='') + { + global $langs; - $sql = "SELECT d.rowid, d.ref_ext, d.civility as civility_id, d.firstname, d.lastname, d.societe as company, d.fk_soc, d.statut, d.public, d.address, d.zip, d.town, d.note_private,"; - $sql.= " d.note_public,"; - $sql.= " d.email, d.skype, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,"; - $sql.= " d.photo, d.fk_adherent_type, d.morphy, d.entity,"; - $sql.= " d.datec as datec,"; - $sql.= " d.tms as datem,"; - $sql.= " d.datefin as datefin,"; - $sql.= " d.birth as birthday,"; - $sql.= " d.datevalid as datev,"; - $sql.= " d.country,"; - $sql.= " d.state_id,"; - $sql.= " d.model_pdf,"; - $sql.= " c.rowid as country_id, c.code as country_code, c.label as country,"; - $sql.= " dep.nom as state, dep.code_departement as state_code,"; - $sql.= " t.libelle as type, t.subscription as subscription,"; - $sql.= " u.rowid as user_id, u.login as user_login"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as dep ON d.state_id = dep.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON d.rowid = u.fk_member"; - $sql.= " WHERE d.fk_adherent_type = t.rowid"; - if ($rowid) $sql.= " AND d.rowid=".$rowid; - elseif ($ref || $fk_soc) { - $sql.= " AND d.entity IN (".getEntity('adherent').")"; - if ($ref) $sql.= " AND d.rowid='".$this->db->escape($ref)."'"; - elseif ($fk_soc > 0) $sql.= " AND d.fk_soc=".$fk_soc; - } - elseif ($ref_ext) - { - $sql.= " AND d.ref_ext='".$this->db->escape($ref_ext)."'"; - } + $sql = "SELECT d.rowid, d.ref_ext, d.civility as civility_id, d.firstname, d.lastname, d.societe as company, d.fk_soc, d.statut, d.public, d.address, d.zip, d.town, d.note_private,"; + $sql.= " d.note_public,"; + $sql.= " d.email, d.skype, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,"; + $sql.= " d.photo, d.fk_adherent_type, d.morphy, d.entity,"; + $sql.= " d.datec as datec,"; + $sql.= " d.tms as datem,"; + $sql.= " d.datefin as datefin,"; + $sql.= " d.birth as birthday,"; + $sql.= " d.datevalid as datev,"; + $sql.= " d.country,"; + $sql.= " d.state_id,"; + $sql.= " d.model_pdf,"; + $sql.= " c.rowid as country_id, c.code as country_code, c.label as country,"; + $sql.= " dep.nom as state, dep.code_departement as state_code,"; + $sql.= " t.libelle as type, t.subscription as subscription,"; + $sql.= " u.rowid as user_id, u.login as user_login"; + $sql.= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as dep ON d.state_id = dep.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON d.rowid = u.fk_member"; + $sql.= " WHERE d.fk_adherent_type = t.rowid"; + if ($rowid) $sql.= " AND d.rowid=".$rowid; + elseif ($ref || $fk_soc) { + $sql.= " AND d.entity IN (".getEntity('adherent').")"; + if ($ref) $sql.= " AND d.rowid='".$this->db->escape($ref)."'"; + elseif ($fk_soc > 0) $sql.= " AND d.fk_soc=".$fk_soc; + } + elseif ($ref_ext) + { + $sql.= " AND d.ref_ext='".$this->db->escape($ref_ext)."'"; + } - 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->entity = $obj->entity; - $this->ref = $obj->rowid; - $this->id = $obj->rowid; - $this->ref_ext = $obj->ref_ext; - $this->civility_id = $obj->civility_id; - $this->firstname = $obj->firstname; - $this->lastname = $obj->lastname; - $this->login = $obj->login; - $this->societe = $obj->company; - $this->company = $obj->company; - $this->fk_soc = $obj->fk_soc; - $this->address = $obj->address; - $this->zip = $obj->zip; - $this->town = $obj->town; + $this->entity = $obj->entity; + $this->ref = $obj->rowid; + $this->id = $obj->rowid; + $this->ref_ext = $obj->ref_ext; + $this->civility_id = $obj->civility_id; + $this->firstname = $obj->firstname; + $this->lastname = $obj->lastname; + $this->login = $obj->login; + $this->societe = $obj->company; + $this->company = $obj->company; + $this->fk_soc = $obj->fk_soc; + $this->address = $obj->address; + $this->zip = $obj->zip; + $this->town = $obj->town; - $this->pass = $obj->pass; - $this->pass_indatabase = $obj->pass; - $this->pass_indatabase_crypted = $obj->pass_crypted; + $this->pass = $obj->pass; + $this->pass_indatabase = $obj->pass; + $this->pass_indatabase_crypted = $obj->pass_crypted; - $this->state_id = $obj->state_id; - $this->state_code = $obj->state_id?$obj->state_code:''; - $this->state = $obj->state_id?$obj->state:''; + $this->state_id = $obj->state_id; + $this->state_code = $obj->state_id?$obj->state_code:''; + $this->state = $obj->state_id?$obj->state:''; - $this->country_id = $obj->country_id; - $this->country_code = $obj->country_code; - if ($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code) - $this->country = $langs->transnoentitiesnoconv("Country".$obj->country_code); - else - $this->country=$obj->country; + $this->country_id = $obj->country_id; + $this->country_code = $obj->country_code; + if ($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code) + $this->country = $langs->transnoentitiesnoconv("Country".$obj->country_code); + else + $this->country=$obj->country; - $this->phone = $obj->phone; - $this->phone_perso = $obj->phone_perso; - $this->phone_mobile = $obj->phone_mobile; - $this->email = $obj->email; - $this->skype = $obj->skype; + $this->phone = $obj->phone; + $this->phone_perso = $obj->phone_perso; + $this->phone_mobile = $obj->phone_mobile; + $this->email = $obj->email; + $this->skype = $obj->skype; - $this->photo = $obj->photo; - $this->statut = $obj->statut; - $this->public = $obj->public; + $this->photo = $obj->photo; + $this->statut = $obj->statut; + $this->public = $obj->public; - $this->datec = $this->db->jdate($obj->datec); - $this->datem = $this->db->jdate($obj->datem); - $this->datefin = $this->db->jdate($obj->datefin); - $this->datevalid = $this->db->jdate($obj->datev); - $this->birth = $this->db->jdate($obj->birthday); + $this->datec = $this->db->jdate($obj->datec); + $this->datem = $this->db->jdate($obj->datem); + $this->datefin = $this->db->jdate($obj->datefin); + $this->datevalid = $this->db->jdate($obj->datev); + $this->birth = $this->db->jdate($obj->birthday); - $this->note_private = $obj->note_private; - $this->note_public = $obj->note_public; - $this->morphy = $obj->morphy; + $this->note_private = $obj->note_private; + $this->note_public = $obj->note_public; + $this->morphy = $obj->morphy; - $this->typeid = $obj->fk_adherent_type; - $this->type = $obj->type; - $this->need_subscription = $obj->subscription; + $this->typeid = $obj->fk_adherent_type; + $this->type = $obj->type; + $this->need_subscription = $obj->subscription; - $this->user_id = $obj->user_id; - $this->user_login = $obj->user_login; + $this->user_id = $obj->user_id; + $this->user_login = $obj->user_login; - $this->model_pdf = $obj->model_pdf; + $this->model_pdf = $obj->model_pdf; - // 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); - // Load other properties - $result=$this->fetch_subscriptions(); + // Load other properties + $result=$this->fetch_subscriptions(); - return $this->id; - } - else - { - return 0; - } - } - else - { - $this->error=$this->db->lasterror(); - return -1; - } - } + return $this->id; + } + else + { + return 0; + } + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } - /** - * Fonction qui recupere pour un adherent les parametres - * first_subscription_date - * first_subscription_amount - * last_subscription_date - * last_subscription_amount - * - * @return int <0 si KO, >0 si OK - */ - function fetch_subscriptions() - { - global $langs; + /** + * Fonction qui recupere pour un adherent les parametres + * first_subscription_date + * first_subscription_amount + * last_subscription_date + * last_subscription_amount + * + * @return int <0 si KO, >0 si OK + */ + function fetch_subscriptions() + { + global $langs; require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; - $sql = "SELECT c.rowid, c.fk_adherent, c.subscription, c.note, c.fk_bank,"; - $sql.= " c.tms as datem,"; - $sql.= " c.datec as datec,"; - $sql.= " c.dateadh as dateh,"; - $sql.= " c.datef as datef"; - $sql.= " FROM ".MAIN_DB_PREFIX."subscription as c"; - $sql.= " WHERE c.fk_adherent = ".$this->id; - $sql.= " ORDER BY c.dateadh"; - dol_syslog(get_class($this)."::fetch_subscriptions", LOG_DEBUG); + $sql = "SELECT c.rowid, c.fk_adherent, c.subscription, c.note, c.fk_bank,"; + $sql.= " c.tms as datem,"; + $sql.= " c.datec as datec,"; + $sql.= " c.dateadh as dateh,"; + $sql.= " c.datef as datef"; + $sql.= " FROM ".MAIN_DB_PREFIX."subscription as c"; + $sql.= " WHERE c.fk_adherent = ".$this->id; + $sql.= " ORDER BY c.dateadh"; + dol_syslog(get_class($this)."::fetch_subscriptions", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $this->subscriptions=array(); + $resql=$this->db->query($sql); + if ($resql) + { + $this->subscriptions=array(); - $i=0; - while ($obj = $this->db->fetch_object($resql)) - { - if ($i==0) - { - $this->first_subscription_date=$obj->dateh; - $this->first_subscription_amount=$obj->subscription; - } - $this->last_subscription_date=$obj->dateh; - $this->last_subscription_amount=$obj->subscription; + $i=0; + while ($obj = $this->db->fetch_object($resql)) + { + if ($i==0) + { + $this->first_subscription_date=$obj->dateh; + $this->first_subscription_amount=$obj->subscription; + } + $this->last_subscription_date=$obj->dateh; + $this->last_subscription_amount=$obj->subscription; - $subscription=new Subscription($this->db); - $subscription->id=$obj->rowid; - $subscription->fk_adherent=$obj->fk_adherent; - $subscription->amount=$obj->subscription; - $subscription->note=$obj->note; - $subscription->fk_bank=$obj->fk_bank; - $subscription->datem=$this->db->jdate($obj->datem); - $subscription->datec=$this->db->jdate($obj->datec); - $subscription->dateh=$this->db->jdate($obj->dateh); - $subscription->datef=$this->db->jdate($obj->datef); + $subscription=new Subscription($this->db); + $subscription->id=$obj->rowid; + $subscription->fk_adherent=$obj->fk_adherent; + $subscription->amount=$obj->subscription; + $subscription->note=$obj->note; + $subscription->fk_bank=$obj->fk_bank; + $subscription->datem=$this->db->jdate($obj->datem); + $subscription->datec=$this->db->jdate($obj->datec); + $subscription->dateh=$this->db->jdate($obj->dateh); + $subscription->datef=$this->db->jdate($obj->datef); - $this->subscriptions[]=$subscription; + $this->subscriptions[]=$subscription; - $i++; - } - return 1; - } - else - { - $this->error=$this->db->error().' sql='.$sql; - return -1; - } - } + $i++; + } + return 1; + } + else + { + $this->error=$this->db->error().' sql='.$sql; + return -1; + } + } - /** - * Insert subscription into database and eventually add links to banks, mailman, etc... - * - * @param int $date Date of effect of subscription - * @param double $montant Amount of subscription (0 accepted for some members) - * @param int $accountid Id bank account - * @param string $operation Type operation (if Id bank account provided) - * @param string $label Label operation (if Id bank account provided) - * @param string $num_chq Numero cheque (if Id bank account provided) - * @param string $emetteur_nom Name of cheque writer - * @param string $emetteur_banque Name of bank of cheque - * @param int $datesubend Date end subscription - * @return int rowid of record added, <0 if KO - */ - function subscription($date, $montant, $accountid=0, $operation='', $label='', $num_chq='', $emetteur_nom='', $emetteur_banque='', $datesubend=0) - { - global $conf,$langs,$user; + /** + * Insert subscription into database and eventually add links to banks, mailman, etc... + * + * @param int $date Date of effect of subscription + * @param double $montant Amount of subscription (0 accepted for some members) + * @param int $accountid Id bank account + * @param string $operation Type operation (if Id bank account provided) + * @param string $label Label operation (if Id bank account provided) + * @param string $num_chq Numero cheque (if Id bank account provided) + * @param string $emetteur_nom Name of cheque writer + * @param string $emetteur_banque Name of bank of cheque + * @param int $datesubend Date end subscription + * @return int rowid of record added, <0 if KO + */ + function subscription($date, $montant, $accountid=0, $operation='', $label='', $num_chq='', $emetteur_nom='', $emetteur_banque='', $datesubend=0) + { + global $conf,$langs,$user; require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $error=0; - // Clean parameters - if (! $montant) $montant=0; + // Clean parameters + if (! $montant) $montant=0; - $this->db->begin(); + $this->db->begin(); - if ($datesubend) - { - $datefin=$datesubend; - } - else - { - // If no end date, end date = date + 1 year - 1 day - $datefin = dol_time_plus_duree($date,1,'y'); - $datefin = dol_time_plus_duree($datefin,-1,'d'); - } + if ($datesubend) + { + $datefin=$datesubend; + } + else + { + // If no end date, end date = date + 1 year - 1 day + $datefin = dol_time_plus_duree($date,1,'y'); + $datefin = dol_time_plus_duree($datefin,-1,'d'); + } - // Create subscription - $subscription=new Subscription($this->db); - $subscription->fk_adherent=$this->id; - $subscription->dateh=$date; // Date of new subscription - $subscription->datef=$datefin; // End data of new subscription - $subscription->amount=$montant; - $subscription->note=$label; + // Create subscription + $subscription=new Subscription($this->db); + $subscription->fk_adherent=$this->id; + $subscription->dateh=$date; // Date of new subscription + $subscription->datef=$datefin; // End data of new subscription + $subscription->amount=$montant; + $subscription->note=$label; - $rowid=$subscription->create($user); - if ($rowid > 0) - { - // Update denormalized subscription end date (read database subscription to find values) - // This will also update this->datefin - $result=$this->update_end_date($user); - if ($result > 0) - { - // Change properties of object (used by triggers) - $this->last_subscription_date=dol_now(); - $this->last_subscription_amount=$montant; - $this->last_subscription_date_start=$date; - $this->last_subscription_date_end=$datefin; - - // Call trigger - $result=$this->call_trigger('MEMBER_SUBSCRIPTION',$user); - if ($result < 0) { $error++; } - // End call triggers - } - - if (! $error) - { - $this->db->commit(); - return $rowid; - } - else + $rowid=$subscription->create($user); + if ($rowid > 0) + { + // Update denormalized subscription end date (read database subscription to find values) + // This will also update this->datefin + $result=$this->update_end_date($user); + if ($result > 0) { - $this->db->rollback(); - return -2; - } - } - else - { - $this->error=$subscription->error; - $this->db->rollback(); - return -1; - } - } + // Change properties of object (used by triggers) + $this->last_subscription_date=dol_now(); + $this->last_subscription_amount=$montant; + $this->last_subscription_date_start=$date; + $this->last_subscription_date_end=$datefin; - /** - * Function that validate a member - * - * @param User $user user adherent qui valide - * @return int <0 if KO, 0 if nothing done, >0 if OK - */ - function validate($user) - { - global $langs,$conf; + // Call trigger + $result=$this->call_trigger('MEMBER_SUBSCRIPTION',$user); + if ($result < 0) { $error++; } + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return $rowid; + } + else + { + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$subscription->error; + $this->db->rollback(); + return -1; + } + } + + /** + * Function that validate a member + * + * @param User $user user adherent qui valide + * @return int <0 if KO, 0 if nothing done, >0 if OK + */ + function validate($user) + { + global $langs,$conf; $error=0; $now=dol_now(); // Check parameters - if ($this->statut == 1) - { - dol_syslog(get_class($this)."::validate statut of member does not allow this", LOG_WARNING); - return 0; - } + if ($this->statut == 1) + { + dol_syslog(get_class($this)."::validate statut of member does not allow this", LOG_WARNING); + return 0; + } - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " statut = 1"; - $sql.= ", datevalid = '".$this->db->idate($now)."'"; - $sql.= ", fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; + $sql.= " statut = 1"; + $sql.= ", datevalid = '".$this->db->idate($now)."'"; + $sql.= ", fk_user_valid=".$user->id; + $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::validate", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $this->statut=1; + dol_syslog(get_class($this)."::validate", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->statut=1; - // Call trigger - $result=$this->call_trigger('MEMBER_VALIDATE',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('MEMBER_VALIDATE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Fonction qui resilie un adherent - * - * @param User $user User making change - * @return int <0 if KO, >0 if OK - */ - function resiliate($user) - { - global $langs,$conf; + /** + * Fonction qui resilie un adherent + * + * @param User $user User making change + * @return int <0 if KO, >0 if OK + */ + function resiliate($user) + { + global $langs,$conf; $error=0; // Check paramaters - if ($this->statut == 0) - { - dol_syslog(get_class($this)."::resiliate statut of member does not allow this", LOG_WARNING); - return 0; - } + if ($this->statut == 0) + { + dol_syslog(get_class($this)."::resiliate statut of member does not allow this", LOG_WARNING); + return 0; + } - $this->db->begin(); + $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; - $sql.= " statut = 0"; - $sql.= ", fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET"; + $sql.= " statut = 0"; + $sql.= ", fk_user_valid=".$user->id; + $sql.= " WHERE rowid = ".$this->id; - $result = $this->db->query($sql); - if ($result) - { - $this->statut=0; + $result = $this->db->query($sql); + if ($result) + { + $this->statut=0; - // Call trigger - $result=$this->call_trigger('MEMBER_RESILIATE',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + // Call trigger + $result=$this->call_trigger('MEMBER_RESILIATE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers - $this->db->commit(); - return 1; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } - /** - * Function to add member into external tools mailing-list, spip, etc. - * - * @return int <0 if KO, >0 if OK - */ - function add_to_abo() - { - global $conf,$langs; + /** + * Function to add member into external tools mailing-list, spip, etc. + * + * @return int <0 if KO, >0 if OK + */ + function add_to_abo() + { + global $conf,$langs; - include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; - $mailmanspip=new MailmanSpip($this->db); + include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; + $mailmanspip=new MailmanSpip($this->db); - $err=0; + $err=0; - // mailman - if (! empty($conf->global->ADHERENT_USE_MAILMAN) && ! empty($conf->mailmanspip->enabled)) - { - $result=$mailmanspip->add_to_mailman($this); + // mailman + if (! empty($conf->global->ADHERENT_USE_MAILMAN) && ! empty($conf->mailmanspip->enabled)) + { + $result=$mailmanspip->add_to_mailman($this); - if ($result < 0) - { - if (! empty($mailmanspip->error)) $this->errors[]=$mailmanspip->error; - $err+=1; - } - foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) - { - $langs->load("errors"); - $this->errors[]=$langs->trans("ErrorFailedToAddToMailmanList",$tmpemail,$tmplist); - } - foreach ($mailmanspip->mladded_ok as $tmplist => $tmpemail) - { - $langs->load("mailmanspip"); - $this->mesgs[]=$langs->trans("SuccessToAddToMailmanList",$tmpemail,$tmplist); - } - } + if ($result < 0) + { + if (! empty($mailmanspip->error)) $this->errors[]=$mailmanspip->error; + $err+=1; + } + foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) + { + $langs->load("errors"); + $this->errors[]=$langs->trans("ErrorFailedToAddToMailmanList",$tmpemail,$tmplist); + } + foreach ($mailmanspip->mladded_ok as $tmplist => $tmpemail) + { + $langs->load("mailmanspip"); + $this->mesgs[]=$langs->trans("SuccessToAddToMailmanList",$tmpemail,$tmplist); + } + } - // spip - if (! empty($conf->global->ADHERENT_USE_SPIP) && ! empty($conf->mailmanspip->enabled)) - { - $result=$mailmanspip->add_to_spip($this); - if ($result < 0) - { - $this->errors[]=$mailmanspip->error; - $err+=1; - } - } - if ($err) - { - return -$err; - } - else - { - return 1; - } - } + // spip + if (! empty($conf->global->ADHERENT_USE_SPIP) && ! empty($conf->mailmanspip->enabled)) + { + $result=$mailmanspip->add_to_spip($this); + if ($result < 0) + { + $this->errors[]=$mailmanspip->error; + $err+=1; + } + } + if ($err) + { + return -$err; + } + else + { + return 1; + } + } - /** - * Function to delete a member from external tools like mailing-list, spip, etc. - * - * @return int <0 if KO, >0 if OK - */ - function del_to_abo() - { - global $conf,$langs; + /** + * Function to delete a member from external tools like mailing-list, spip, etc. + * + * @return int <0 if KO, >0 if OK + */ + function del_to_abo() + { + global $conf,$langs; - include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; - $mailmanspip=new MailmanSpip($this->db); + include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; + $mailmanspip=new MailmanSpip($this->db); - $err=0; + $err=0; - // mailman - if (! empty($conf->global->ADHERENT_USE_MAILMAN)) - { - $result=$mailmanspip->del_to_mailman($this); - if ($result < 0) - { - if (! empty($mailmanspip->error)) $this->errors[]=$mailmanspip->error; - $err+=1; - } + // mailman + if (! empty($conf->global->ADHERENT_USE_MAILMAN)) + { + $result=$mailmanspip->del_to_mailman($this); + if ($result < 0) + { + if (! empty($mailmanspip->error)) $this->errors[]=$mailmanspip->error; + $err+=1; + } - foreach ($mailmanspip->mlremoved_ko as $tmplist => $tmpemail) - { - $langs->load("errors"); - $this->errors[]=$langs->trans("ErrorFailedToRemoveToMailmanList",$tmpemail,$tmplist); - } - foreach ($mailmanspip->mlremoved_ok as $tmplist => $tmpemail) - { - $langs->load("mailmanspip"); - $this->mesgs[]=$langs->trans("SuccessToRemoveToMailmanList",$tmpemail,$tmplist); - } - } + foreach ($mailmanspip->mlremoved_ko as $tmplist => $tmpemail) + { + $langs->load("errors"); + $this->errors[]=$langs->trans("ErrorFailedToRemoveToMailmanList",$tmpemail,$tmplist); + } + foreach ($mailmanspip->mlremoved_ok as $tmplist => $tmpemail) + { + $langs->load("mailmanspip"); + $this->mesgs[]=$langs->trans("SuccessToRemoveToMailmanList",$tmpemail,$tmplist); + } + } - if ($conf->global->ADHERENT_USE_SPIP && ! empty($conf->mailmanspip->enabled)) - { - $result=$mailmanspip->del_to_spip($this); - if ($result < 0) - { - $this->errors[]=$mailmanspip->error; - $err+=1; - } - } - if ($err) - { - // error - return -$err; - } - else - { - return 1; - } - } + if ($conf->global->ADHERENT_USE_SPIP && ! empty($conf->mailmanspip->enabled)) + { + $result=$mailmanspip->del_to_spip($this); + if ($result < 0) + { + $this->errors[]=$mailmanspip->error; + $err+=1; + } + } + if ($err) + { + // error + return -$err; + } + else + { + return 1; + } + } - /** - * Return civility label of a member - * - * @return string Translated name of civility (translated with transnoentitiesnoconv) - */ - function getCivilityLabel() - { - global $langs; - $langs->load("dict"); + /** + * Return civility label of a member + * + * @return string Translated name of civility (translated with transnoentitiesnoconv) + */ + function getCivilityLabel() + { + global $langs; + $langs->load("dict"); - $code=(empty($this->civility_id)?'':$this->civility_id); - if (empty($code)) return ''; - return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); - } + $code=(empty($this->civility_id)?'':$this->civility_id); + if (empty($code)) return ''; + return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); + } - /** - * Return clicable name (with picto eventually) - * - * @param int $withpictoimg 0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small) - * @param int $maxlen length max label - * @param string $option Page for link - * @param string $mode ''=Show firstname and lastname, 'firstname'=Show only firstname, 'login'=Show login, 'ref'=Show ref - * @param string $morecss Add more css on link - * @return string Chaine avec URL - */ - function getNomUrl($withpictoimg=0,$maxlen=0,$option='card',$mode='',$morecss='') - { - global $conf, $langs; + /** + * Return clicable name (with picto eventually) + * + * @param int $withpictoimg 0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small) + * @param int $maxlen length max label + * @param string $option Page for link ('card', 'category', 'subscription', ...) + * @param string $mode ''=Show firstname and lastname, 'firstname'=Show only firstname, 'login'=Show login, 'ref'=Show ref + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL + */ + function getNomUrl($withpictoimg=0, $maxlen=0, $option='card', $mode='', $morecss='', $save_lastsearch_value=-1) + { + global $conf, $langs; - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg=0; + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg=0; - $result=''; $label=''; - $link=''; $linkstart=''; $linkend=''; + $result=''; $label=''; + $link=''; $linkstart=''; $linkend=''; - if (! empty($this->photo)) - { - $label.= '
'; - $label.= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photowithmargin photologintooltip', 'small', 0, 1); - $label.= '
'; - } + if (! empty($this->photo)) + { + $label.= '
'; + $label.= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photowithmargin photologintooltip', 'small', 0, 1); + $label.= '
'; + } - $label.= '
'; - $label.= '' . $langs->trans("Member") . ''; - if (! empty($this->ref)) - $label.= '
' . $langs->trans('Ref') . ': ' . $this->ref; - if (! empty($this->firstname) || ! empty($this->lastname)) - $label.= '
' . $langs->trans('Name') . ': ' . $this->getFullName($langs); - $label.='
'; + $label.= '
'; + $label.= '' . $langs->trans("Member") . ''; + if (! empty($this->ref)) + $label.= '
' . $langs->trans('Ref') . ': ' . $this->ref; + if (! empty($this->firstname) || ! empty($this->lastname)) + $label.= '
' . $langs->trans('Name') . ': ' . $this->getFullName($langs); + $label.='
'; - if ($option == 'card' || $option == 'category') - { - $link = 'id; + if ($option == 'subscription') + { + $url = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$this->id; + } - $linkclose=""; - if (empty($notooltip)) - { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $langs->load("users"); - $label=$langs->trans("ShowUser"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.= ' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; - } + 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.=$linkclose.'>'; - $linkend=''; + $link = 'global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $langs->load("users"); + $label=$langs->trans("ShowUser"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.= ' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + } - //if ($withpictoimg == -1) $result.='
'; - $result.=$link; - if ($withpictoimg) - { - $paddafterimage=''; - if (abs($withpictoimg) == 1) $paddafterimage='style="margin-right: 3px;"'; - // Only picto - if ($withpictoimg > 0) $picto='
'.img_object('', 'user', $paddafterimage.' '.($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).'
'; - // Picto must be a photo - else $picto='
'.Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg==-3?'small':''), 'mini', 0, 1).'
'; - $result.=$picto; - } - if ($withpictoimg > -2 && $withpictoimg != 2) - { - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result.='
'; - if ($mode == 'login') $result.=dol_trunc($this->login, $maxlen); - elseif ($mode == 'ref') $result.=$this->id; - else $result.=$this->getFullName($langs,'',($mode == 'firstname' ? 2 : -1),$maxlen); - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result.='
'; - } - $result.=$linkend; - //if ($withpictoimg == -1) $result.='
'; + $link.=$linkclose.'>'; + $linkend='
'; - return $result; - } + //if ($withpictoimg == -1) $result.='
'; + $result.=$link; + if ($withpictoimg) + { + $paddafterimage=''; + if (abs($withpictoimg) == 1) $paddafterimage='style="margin-right: 3px;"'; + // Only picto + if ($withpictoimg > 0) $picto='
'.img_object('', 'user', $paddafterimage.' '.($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).'
'; + // Picto must be a photo + else $picto='
'.Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg==-3?'small':''), 'mini', 0, 1).'
'; + $result.=$picto; + } + if ($withpictoimg > -2 && $withpictoimg != 2) + { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result.='
'; + if ($mode == 'login') $result.=dol_trunc($this->login, $maxlen); + elseif ($mode == 'ref') $result.=$this->id; + else $result.=$this->getFullName($langs,'',($mode == 'firstname' ? 2 : -1),$maxlen); + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result.='
'; + } + $result.=$linkend; + //if ($withpictoimg == -1) $result.='
'; - /** - * Retourne le libelle du statut d'un adherent (brouillon, valide, resilie) - * - * @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 - */ - function getLibStatut($mode=0) - { - return $this->LibStatut($this->statut,$this->need_subscription,$this->datefin,$mode); - } + return $result; + } - /** - * Renvoi le libelle d'un statut donne - * - * @param int $statut Id statut - * @param int $need_subscription 1 if member type need subscription, 0 otherwise - * @param int $date_end_subscription Date fin adhesion - * @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 - */ - function LibStatut($statut,$need_subscription,$date_end_subscription,$mode=0) - { - global $langs; - $langs->load("members"); - if ($mode == 0) - { - if ($statut == -1) return $langs->trans("MemberStatusDraft"); - if ($statut >= 1) - { - if (! $date_end_subscription) return $langs->trans("MemberStatusActive"); - elseif ($date_end_subscription < time()) return $langs->trans("MemberStatusActiveLate"); - else return $langs->trans("MemberStatusPaid"); - } - if ($statut == 0) return $langs->trans("MemberStatusResiliated"); - } - if ($mode == 1) - { - if ($statut == -1) return $langs->trans("MemberStatusDraftShort"); - if ($statut >= 1) - { - if (! $date_end_subscription) return $langs->trans("MemberStatusActiveShort"); - elseif ($date_end_subscription < time()) return $langs->trans("MemberStatusActiveLateShort"); - else return $langs->trans("MemberStatusPaidShort"); - } - if ($statut == 0) return $langs->trans("MemberStatusResiliatedShort"); - } - if ($mode == 2) - { - if ($statut == -1) return img_picto($langs->trans('MemberStatusDraft'),'statut0').' '.$langs->trans("MemberStatusDraftShort"); - if ($statut >= 1) - { - if (! $date_end_subscription) return img_picto($langs->trans('MemberStatusActive'),'statut1').' '.$langs->trans("MemberStatusActiveShort"); - elseif ($date_end_subscription < time()) return img_picto($langs->trans('MemberStatusActiveLate'),'statut3').' '.$langs->trans("MemberStatusActiveLateShort"); - else return img_picto($langs->trans('MemberStatusPaid'),'statut4').' '.$langs->trans("MemberStatusPaidShort"); - } - if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5').' '.$langs->trans("MemberStatusResiliatedShort"); - } - if ($mode == 3) - { - if ($statut == -1) return img_picto($langs->trans('MemberStatusDraft'),'statut0'); - if ($statut >= 1) - { - if (! $date_end_subscription) return img_picto($langs->trans('MemberStatusActive'),'statut1'); - elseif ($date_end_subscription < time()) return img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); - else return img_picto($langs->trans('MemberStatusPaid'),'statut4'); - } - if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5'); - } - if ($mode == 4) - { - if ($statut == -1) return img_picto($langs->trans('MemberStatusDraft'),'statut0').' '.$langs->trans("MemberStatusDraft"); - if ($statut >= 1) - { - if (! $date_end_subscription) return img_picto($langs->trans('MemberStatusActive'),'statut1').' '.$langs->trans("MemberStatusActive"); - elseif ($date_end_subscription < time()) return img_picto($langs->trans('MemberStatusActiveLate'),'statut3').' '.$langs->trans("MemberStatusActiveLate"); - else return img_picto($langs->trans('MemberStatusPaid'),'statut4').' '.$langs->trans("MemberStatusPaid"); - } - if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5').' '.$langs->trans("MemberStatusResiliated"); - } - if ($mode == 5) - { - if ($statut == -1) return $langs->trans("MemberStatusDraft").' '.img_picto($langs->trans('MemberStatusDraft'),'statut0'); - if ($statut >= 1) - { - if (! $date_end_subscription) return ''.$langs->trans("MemberStatusActiveShort").' '.img_picto($langs->trans('MemberStatusActive'),'statut1'); - elseif ($date_end_subscription < time()) return ''.$langs->trans("MemberStatusActiveLateShort").' '.img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); - else return ''.$langs->trans("MemberStatusPaidShort").' '.img_picto($langs->trans('MemberStatusPaid'),'statut4'); - } - if ($statut == 0) return ''.$langs->trans("MemberStatusResiliated").' '.img_picto($langs->trans('MemberStatusResiliated'),'statut5'); - } - if ($mode == 6) - { - if ($statut == -1) return $langs->trans("MemberStatusDraft").' '.img_picto($langs->trans('MemberStatusDraft'),'statut0'); - if ($statut >= 1) - { - if (! $date_end_subscription) return ''.$langs->trans("MemberStatusActive").' '.img_picto($langs->trans('MemberStatusActive'),'statut1'); - elseif ($date_end_subscription < time()) return ''.$langs->trans("MemberStatusActiveLate").' '.img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); - else return ''.$langs->trans("MemberStatusPaid").' '.img_picto($langs->trans('MemberStatusPaid'),'statut4'); - } - if ($statut == 0) return ''.$langs->trans("MemberStatusResiliated").' '.img_picto($langs->trans('MemberStatusResiliated'),'statut5'); - } - } + /** + * Retourne le libelle du statut d'un adherent (brouillon, valide, resilie) + * + * @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 + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$this->need_subscription,$this->datefin,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @param int $need_subscription 1 if member type need subscription, 0 otherwise + * @param int $date_end_subscription Date fin adhesion + * @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 + */ + function LibStatut($statut,$need_subscription,$date_end_subscription,$mode=0) + { + global $langs; + $langs->load("members"); + if ($mode == 0) + { + if ($statut == -1) return $langs->trans("MemberStatusDraft"); + if ($statut >= 1) + { + if (! $date_end_subscription) return $langs->trans("MemberStatusActive"); + elseif ($date_end_subscription < time()) return $langs->trans("MemberStatusActiveLate"); + else return $langs->trans("MemberStatusPaid"); + } + if ($statut == 0) return $langs->trans("MemberStatusResiliated"); + } + if ($mode == 1) + { + if ($statut == -1) return $langs->trans("MemberStatusDraftShort"); + if ($statut >= 1) + { + if (! $date_end_subscription) return $langs->trans("MemberStatusActiveShort"); + elseif ($date_end_subscription < time()) return $langs->trans("MemberStatusActiveLateShort"); + else return $langs->trans("MemberStatusPaidShort"); + } + if ($statut == 0) return $langs->trans("MemberStatusResiliatedShort"); + } + if ($mode == 2) + { + if ($statut == -1) return img_picto($langs->trans('MemberStatusDraft'),'statut0').' '.$langs->trans("MemberStatusDraftShort"); + if ($statut >= 1) + { + if (! $date_end_subscription) return img_picto($langs->trans('MemberStatusActive'),'statut1').' '.$langs->trans("MemberStatusActiveShort"); + elseif ($date_end_subscription < time()) return img_picto($langs->trans('MemberStatusActiveLate'),'statut3').' '.$langs->trans("MemberStatusActiveLateShort"); + else return img_picto($langs->trans('MemberStatusPaid'),'statut4').' '.$langs->trans("MemberStatusPaidShort"); + } + if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5').' '.$langs->trans("MemberStatusResiliatedShort"); + } + if ($mode == 3) + { + if ($statut == -1) return img_picto($langs->trans('MemberStatusDraft'),'statut0'); + if ($statut >= 1) + { + if (! $date_end_subscription) return img_picto($langs->trans('MemberStatusActive'),'statut1'); + elseif ($date_end_subscription < time()) return img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); + else return img_picto($langs->trans('MemberStatusPaid'),'statut4'); + } + if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5'); + } + if ($mode == 4) + { + if ($statut == -1) return img_picto($langs->trans('MemberStatusDraft'),'statut0').' '.$langs->trans("MemberStatusDraft"); + if ($statut >= 1) + { + if (! $date_end_subscription) return img_picto($langs->trans('MemberStatusActive'),'statut1').' '.$langs->trans("MemberStatusActive"); + elseif ($date_end_subscription < time()) return img_picto($langs->trans('MemberStatusActiveLate'),'statut3').' '.$langs->trans("MemberStatusActiveLate"); + else return img_picto($langs->trans('MemberStatusPaid'),'statut4').' '.$langs->trans("MemberStatusPaid"); + } + if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5').' '.$langs->trans("MemberStatusResiliated"); + } + if ($mode == 5) + { + if ($statut == -1) return $langs->trans("MemberStatusDraft").' '.img_picto($langs->trans('MemberStatusDraft'),'statut0'); + if ($statut >= 1) + { + if (! $date_end_subscription) return ''.$langs->trans("MemberStatusActiveShort").' '.img_picto($langs->trans('MemberStatusActive'),'statut1'); + elseif ($date_end_subscription < time()) return ''.$langs->trans("MemberStatusActiveLateShort").' '.img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); + else return ''.$langs->trans("MemberStatusPaidShort").' '.img_picto($langs->trans('MemberStatusPaid'),'statut4'); + } + if ($statut == 0) return ''.$langs->trans("MemberStatusResiliated").' '.img_picto($langs->trans('MemberStatusResiliated'),'statut5'); + } + if ($mode == 6) + { + if ($statut == -1) return $langs->trans("MemberStatusDraft").' '.img_picto($langs->trans('MemberStatusDraft'),'statut0'); + if ($statut >= 1) + { + if (! $date_end_subscription) return ''.$langs->trans("MemberStatusActive").' '.img_picto($langs->trans('MemberStatusActive'),'statut1'); + elseif ($date_end_subscription < time()) return ''.$langs->trans("MemberStatusActiveLate").' '.img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); + else return ''.$langs->trans("MemberStatusPaid").' '.img_picto($langs->trans('MemberStatusPaid'),'statut4'); + } + if ($statut == 0) return ''.$langs->trans("MemberStatusResiliated").' '.img_picto($langs->trans('MemberStatusResiliated'),'statut5'); + } + } - /** - * Charge indicateurs this->nb de tableau de bord - * - * @return int <0 if KO, >0 if OK - */ - function load_state_board() - { - global $conf; + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 if KO, >0 if OK + */ + function load_state_board() + { + global $conf; - $this->nb=array(); + $this->nb=array(); - $sql = "SELECT count(a.rowid) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; - $sql.= " WHERE a.statut > 0"; - $sql.= " AND a.entity IN (".getEntity('adherent').")"; + $sql = "SELECT count(a.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; + $sql.= " WHERE a.statut > 0"; + $sql.= " AND a.entity IN (".getEntity('adherent').")"; - $resql=$this->db->query($sql); - if ($resql) - { - while ($obj=$this->db->fetch_object($resql)) - { - $this->nb["members"]=$obj->nb; - } - $this->db->free($resql); - return 1; - } - else - { - dol_print_error($this->db); - $this->error=$this->db->error(); - return -1; - } + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["members"]=$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) - * - * @param User $user Objet user - * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK - */ - function load_board($user) - { - global $conf, $langs; + /** + * 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) + { + 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 - $now=dol_now(); + $now=dol_now(); - $sql = "SELECT a.rowid, a.datefin, a.statut"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; - $sql.= " WHERE a.statut = 1"; - $sql.= " AND a.entity IN (".getEntity('adherent').")"; - $sql.= " AND (a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."')"; + $sql = "SELECT a.rowid, a.datefin, a.statut"; + $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; + $sql.= " WHERE a.statut = 1"; + $sql.= " AND a.entity IN (".getEntity('adherent').")"; + $sql.= " AND (a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."')"; - $resql=$this->db->query($sql); - if ($resql) - { - $langs->load("members"); + $resql=$this->db->query($sql); + if ($resql) + { + $langs->load("members"); - $response = new WorkboardResponse(); - $response->warning_delay=$conf->adherent->subscription->warning_delay/60/60/24; - $response->label=$langs->trans("MembersWithSubscriptionToReceive"); - $response->url=DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&statut=1&filter=outofdate'; - $response->img=img_object('',"user"); + $response = new WorkboardResponse(); + $response->warning_delay=$conf->adherent->subscription->warning_delay/60/60/24; + $response->label=$langs->trans("MembersWithSubscriptionToReceive"); + $response->url=DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&statut=1&filter=outofdate'; + $response->img=img_object('',"user"); - $adherentstatic = new Adherent($this->db); + $adherentstatic = new Adherent($this->db); - while ($obj=$this->db->fetch_object($resql)) - { - $response->nbtodo++; + while ($obj=$this->db->fetch_object($resql)) + { + $response->nbtodo++; - $adherentstatic->datefin = $this->db->jdate($obj->datefin); - $adherentstatic->statut = $obj->statut; + $adherentstatic->datefin = $this->db->jdate($obj->datefin); + $adherentstatic->statut = $obj->statut; - if ($adherentstatic->hasDelay()) { - $response->nbtodolate++; - } - } + if ($adherentstatic->hasDelay()) { + $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; + } + } - /** - * Create a document onto disk according to template module. - * - * @param string $modele Force template to use ('' to not force) - * @param Translate $outputlangs objet lang a utiliser pour traduction - * @param int $hidedetails Hide details of lines - * @param int $hidedesc Hide description - * @param int $hideref Hide ref - * @return int 0 if KO, 1 if OK - */ - public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) - { - global $conf,$langs; + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf,$langs; - $langs->load("orders"); + $langs->load("orders"); if (! dol_strlen($modele)) { - $modele = 'standard'; + $modele = 'standard'; - if ($this->modelpdf) { - $modele = $this->modelpdf; - } elseif (! empty($conf->global->ADHERENT_ADDON_PDF)) { - $modele = $conf->global->ADHERENT_ADDON_PDF; - } - } + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (! empty($conf->global->ADHERENT_ADDON_PDF)) { + $modele = $conf->global->ADHERENT_ADDON_PDF; + } + } - $modelpath = "core/modules/member/doc/"; + $modelpath = "core/modules/member/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); - } + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } - /** - * 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 parametres - $this->id=0; - $this->specimen=1; - $this->civility_id = 0; - $this->lastname = 'DOLIBARR'; - $this->firstname = 'SPECIMEN'; - $this->login='dolibspec'; - $this->pass='dolibspec'; - $this->societe = 'Societe ABC'; - $this->address = '61 jump street'; - $this->zip = '75000'; - $this->town = 'Paris'; - $this->country_id = 1; - $this->country_code = 'FR'; - $this->country = 'France'; - $this->morphy = 1; - $this->email = 'specimen@specimen.com'; - $this->skype = 'tom.hanson'; - $this->phone = '0999999999'; - $this->phone_perso = '0999999998'; - $this->phone_mobile = '0999999997'; - $this->note_private='No comment'; - $this->birth=time(); - $this->photo=''; - $this->public=1; - $this->statut=0; + // Initialise parametres + $this->id=0; + $this->specimen=1; + $this->civility_id = 0; + $this->lastname = 'DOLIBARR'; + $this->firstname = 'SPECIMEN'; + $this->login='dolibspec'; + $this->pass='dolibspec'; + $this->societe = 'Societe ABC'; + $this->address = '61 jump street'; + $this->zip = '75000'; + $this->town = 'Paris'; + $this->country_id = 1; + $this->country_code = 'FR'; + $this->country = 'France'; + $this->morphy = 1; + $this->email = 'specimen@specimen.com'; + $this->skype = 'tom.hanson'; + $this->phone = '0999999999'; + $this->phone_perso = '0999999998'; + $this->phone_mobile = '0999999997'; + $this->note_private='No comment'; + $this->birth=time(); + $this->photo=''; + $this->public=1; + $this->statut=0; - $this->datefin=time(); - $this->datevalid=time(); + $this->datefin=time(); + $this->datevalid=time(); - $this->typeid=1; // Id type adherent - $this->type='Type adherent'; // Libelle type adherent - $this->need_subscription=0; + $this->typeid=1; // Id type adherent + $this->type='Type adherent'; // Libelle type adherent + $this->need_subscription=0; - $this->first_subscription_date=time(); - $this->first_subscription_amount=10; - $this->last_subscription_date=time(); - $this->last_subscription_amount=10; - } + $this->first_subscription_date=time(); + $this->first_subscription_amount=10; + $this->last_subscription_date=time(); + $this->last_subscription_amount=10; + } - /** - * Retourne chaine DN complete dans l'annuaire LDAP pour l'objet - * - * @param array $info Info array loaded by _load_ldap_info - * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb) - * 1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb) - * 2=Return key only (uid=qqq) - * @return string DN - */ - function _load_ldap_dn($info,$mode=0) - { - global $conf; - $dn=''; - if ($mode==0) $dn=$conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; - if ($mode==1) $dn=$conf->global->LDAP_MEMBER_DN; - if ($mode==2) $dn=$conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; - return $dn; - } + /** + * Retourne chaine DN complete dans l'annuaire LDAP pour l'objet + * + * @param array $info Info array loaded by _load_ldap_info + * @param int $mode 0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb) + * 1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb) + * 2=Return key only (uid=qqq) + * @return string DN + */ + function _load_ldap_dn($info,$mode=0) + { + global $conf; + $dn=''; + if ($mode==0) $dn=$conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; + if ($mode==1) $dn=$conf->global->LDAP_MEMBER_DN; + if ($mode==2) $dn=$conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; + return $dn; + } - /** - * Initialise tableau info (tableau des attributs LDAP) - * - * @return array Tableau info des attributs - */ - function _load_ldap_info() - { - global $conf,$langs; + /** + * Initialise tableau info (tableau des attributs LDAP) + * + * @return array Tableau info des attributs + */ + function _load_ldap_info() + { + global $conf,$langs; - $info=array(); + $info=array(); + $keymodified=false; - // Object classes - $info["objectclass"]=explode(',',$conf->global->LDAP_MEMBER_OBJECT_CLASS); + // Object classes + $info["objectclass"]=explode(',',$conf->global->LDAP_MEMBER_OBJECT_CLASS); - $this->fullname=$this->getFullName($langs); + $this->fullname=$this->getFullName($langs); - // Member - if ($this->fullname && ! empty($conf->global->LDAP_MEMBER_FIELD_FULLNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FULLNAME] = $this->fullname; - if ($this->lastname && ! empty($conf->global->LDAP_MEMBER_FIELD_NAME)) $info[$conf->global->LDAP_MEMBER_FIELD_NAME] = $this->lastname; - if ($this->firstname && ! empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; - if ($this->login && ! empty($conf->global->LDAP_MEMBER_FIELD_LOGIN)) $info[$conf->global->LDAP_MEMBER_FIELD_LOGIN] = $this->login; - if ($this->pass && ! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte - if ($this->pass && ! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // md5 for OpenLdap TODO add type of encryption - if ($this->poste && ! empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; - if ($this->address && ! empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; - if ($this->zip && ! empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; - if ($this->town && ! empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; - if ($this->country_code && ! empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; - if ($this->email && ! empty($conf->global->LDAP_MEMBER_FIELD_MAIL)) $info[$conf->global->LDAP_MEMBER_FIELD_MAIL] = $this->email; - if ($this->skype && ! empty($conf->global->LDAP_MEMBER_FIELD_SKYPE)) $info[$conf->global->LDAP_MEMBER_FIELD_SKYPE] = $this->skype; - if ($this->phone && ! empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; - if ($this->phone_perso && ! empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; - if ($this->phone_mobile && ! empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; - if ($this->fax && ! empty($conf->global->LDAP_MEMBER_FIELD_FAX)) $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; - if ($this->note_private && ! empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = $this->note_private; - if ($this->note_public && ! empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = $this->note_public; - if ($this->birth && ! empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth,'dayhourldap'); - if (isset($this->statut) && ! empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; - if ($this->datefin && ! empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin,'dayhourldap'); + // For avoid ldap error when firstname and lastname are empty + if ($this->morphy == 'mor' && empty($this->fullname)) { + $this->fullname = $this->societe; + $this->lastname = $this->societe; + } - // Subscriptions - if ($this->first_subscription_date && ! empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date,'dayhourldap'); - if (isset($this->first_subscription_amount) && ! empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; - if ($this->last_subscription_date && ! empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date,'dayhourldap'); - if (isset($this->last_subscription_amount) && ! empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; + // Possible LDAP KEY (constname => varname) + $ldapkey = array( + 'LDAP_MEMBER_FIELD_FULLNAME' => 'fullname', + 'LDAP_MEMBER_FIELD_NAME' => 'lastname', + 'LDAP_MEMBER_FIELD_LOGIN' => 'login', + 'LDAP_MEMBER_FIELD_LOGIN_SAMBA' => 'login', + 'LDAP_MEMBER_FIELD_MAIL' => 'email' + ); - return $info; - } + // Member + foreach ($ldapkey as $constname => $varname) + { + if (! empty($this->$varname) && ! empty($conf->global->$constname)) + { + $info[$conf->global->$constname] = $this->$varname; + + // Check if it is the LDAP key and if its value has been changed + if (! empty($conf->global->LDAP_KEY_MEMBERS) && $conf->global->LDAP_KEY_MEMBERS == $conf->global->$constname) + { + if (! empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified=true; // For check if LDAP key has been modified + } + } + } + if ($this->firstname && ! empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; + if ($this->poste && ! empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; + if ($this->societe && ! empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) $info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->societe; + if ($this->address && ! empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; + if ($this->zip && ! empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; + if ($this->town && ! empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; + if ($this->country_code && ! empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; + if ($this->skype && ! empty($conf->global->LDAP_MEMBER_FIELD_SKYPE)) $info[$conf->global->LDAP_MEMBER_FIELD_SKYPE] = $this->skype; + if ($this->phone && ! empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; + if ($this->phone_perso && ! empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; + if ($this->phone_mobile && ! empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; + if ($this->fax && ! empty($conf->global->LDAP_MEMBER_FIELD_FAX)) $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; + if ($this->note_private && ! empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = $this->note_private; + if ($this->note_public && ! empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = $this->note_public; + if ($this->birth && ! empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth,'dayhourldap'); + if (isset($this->statut) && ! empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; + if ($this->datefin && ! empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin,'dayhourldap'); + + // When password is modified + if (! empty($this->pass)) + { + if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass; // this->pass = mot de passe non crypte + if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) + } + // Set LDAP password if possible + else if ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password + { + if (! empty($conf->global->DATABASE_PWD_ENCRYPTED)) + { + // Just for the default MD5 ! + if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) + { + if ($this->pass_indatabase_crypted && ! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) { + // Create OpenLDAP MD5 password from Dolibarr MD5 password + // Note: This suppose that "pass_indatabase_crypted" is a md5 (guaranted by the previous test if "(empty($conf->global->MAIN_SECURITY_HASH_ALGO))" + $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = '{md5}'.base64_encode(hex2bin($this->pass_indatabase_crypted)); + } + } + } + // Use $this->pass_indatabase value if exists + else if (! empty($this->pass_indatabase)) + { + if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte + if (! empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + } + } + + // Subscriptions + if ($this->first_subscription_date && ! empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date,'dayhourldap'); + if (isset($this->first_subscription_amount) && ! empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; + if ($this->last_subscription_date && ! empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date,'dayhourldap'); + if (isset($this->last_subscription_amount) && ! empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; + + return $info; + } - /** - * Charge les informations d'ordre info dans l'objet adherent - * - * @param int $id Id of member to load - * @return void - */ - function info($id) - { - $sql = 'SELECT a.rowid, a.datec as datec,'; - $sql.= ' a.datevalid as datev,'; - $sql.= ' a.tms as datem,'; - $sql.= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'adherent as a'; - $sql.= ' WHERE a.rowid = '.$id; + /** + * Charge les informations d'ordre info dans l'objet adherent + * + * @param int $id Id of member to load + * @return void + */ + function info($id) + { + $sql = 'SELECT a.rowid, a.datec as datec,'; + $sql.= ' a.datevalid as datev,'; + $sql.= ' a.tms as datem,'; + $sql.= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'adherent as a'; + $sql.= ' WHERE a.rowid = '.$id; - dol_syslog(get_class($this)."::info", 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; - if ($obj->fk_user_author) - { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } + dol_syslog(get_class($this)."::info", 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; + 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_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } - if ($obj->fk_user_mod) - { - $muser = new User($this->db); - $muser->fetch($obj->fk_user_mod); - $this->user_modification = $muser; - } + if ($obj->fk_user_mod) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_mod); + $this->user_modification = $muser; + } - $this->date_creation = $this->db->jdate($obj->datec); - $this->date_validation = $this->db->jdate($obj->datev); - $this->date_modification = $this->db->jdate($obj->datem); - } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_validation = $this->db->jdate($obj->datev); + $this->date_modification = $this->db->jdate($obj->datem); + } - $this->db->free($result); + $this->db->free($result); - } - else - { - dol_print_error($this->db); - } - } + } + else + { + dol_print_error($this->db); + } + } /** * Sets object to supplied categories. @@ -2117,17 +2177,17 @@ class Adherent extends CommonObject * * @return boolean True if late, False if not late */ - public function hasDelay() - { - global $conf; + public function hasDelay() + { + global $conf; - //Only valid members - if ($this->statut <= 0) return false; - if (! $this->datefin) return false; + //Only valid members + if ($this->statut <= 0) return false; + if (! $this->datefin) return false; - $now = dol_now(); + $now = dol_now(); - return $this->datefin < ($now - $conf->adherent->subscription->warning_delay); - } + return $this->datefin < ($now - $conf->adherent->subscription->warning_delay); + } } diff --git a/htdocs/adherents/class/adherent_type.class.php b/htdocs/adherents/class/adherent_type.class.php index 30c85618bfa..f5f6a161ec5 100644 --- a/htdocs/adherents/class/adherent_type.class.php +++ b/htdocs/adherents/class/adherent_type.class.php @@ -55,11 +55,11 @@ class AdherentType extends CommonObject * @since 5.0 */ public $subscription; - /** @var string Public note */ + /** @var string Public note */ public $note; - /** @var bool Can vote*/ + /** @var integer Can vote */ public $vote; - /** @var bool Email sent during validation */ + /** @var string Email sent during validation */ public $mail_valid; /** @var array Array of members */ public $members=array(); @@ -481,7 +481,7 @@ class AdherentType extends CommonObject // Initialise parametres $this->id = 0; - $this->ref = 0; + $this->ref = 'MTSPEC'; $this->specimen=1; $this->label='MEMBERS TYPE SPECIMEN'; diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php index 4d13b6347ec..99a4f401171 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -1,5 +1,6 @@ +/* Copyright (C) 2016 Xebax Christy + * 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,6 +20,7 @@ use Luracast\Restler\RestException; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; /** * API class for members @@ -357,4 +359,38 @@ class Members extends DolibarrApi return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date); } + /** + * Get categories for a member + * + * @param int $id ID of member + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * + * @return mixed + * + * @url GET {id}/categories + */ + function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + if (! DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $categories = new Categorie($this->db); + + $result = $categories->getListForItem($id, 'member', $sortfield, $sortorder, $limit, $page); + + if (empty($result)) { + throw new RestException(404, 'No category found'); + } + + if ($result < 0) { + throw new RestException(503, 'Error when retrieve category list : '.$categories->error); + } + + return $result; + } + } diff --git a/htdocs/adherents/document.php b/htdocs/adherents/document.php index 65dbadb11a6..6cc0ddd0c4f 100644 --- a/htdocs/adherents/document.php +++ b/htdocs/adherents/document.php @@ -94,7 +94,7 @@ if ($id > 0) $result=$membert->fetch($object->typeid); if ($result > 0) { - + // 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; @@ -102,7 +102,7 @@ if ($id > 0) { $totalsize+=$file['size']; } - + if (! empty($conf->notification->enabled)) $langs->load("mails"); @@ -110,12 +110,12 @@ if ($id > 0) dol_fiche_head($head, 'document', $langs->trans("Member"), -1, 'user'); - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + dol_banner_tab($object, 'rowid', $linkback); - + print '
'; - + print '
'; print '
" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("AccountAccounting") . "" . $langs->trans("SubledgerAccount") . "" . $langs->trans("Label") . "" . $langs->trans("LabelOperation") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("SubledgerAccount") . "' . ($mt < 0 ? - price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; print '" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).($numtax?' - Localtax '.$numtax:''); + print "" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:''); print "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("AccountAccounting") . "" . $langs->trans("SubledgerAccount") . "" . $langs->trans("Label") . "" . $langs->trans("LabelOperation") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
"; print '" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).($numtax?' - Localtax '.$numtax:''); + print "" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:''); print "' . ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
'; @@ -153,7 +153,7 @@ if ($id > 0) print '
'; print '
'; - + dol_fiche_end(); $modulepart = 'member'; diff --git a/htdocs/adherents/ldap.php b/htdocs/adherents/ldap.php index 65aea951d76..ff0bad063bd 100644 --- a/htdocs/adherents/ldap.php +++ b/htdocs/adherents/ldap.php @@ -59,26 +59,23 @@ if (! $result) if ($action == 'dolibarr2ldap') { - $db->begin(); - $ldap=new Ldap(); $result=$ldap->connect_bind(); - $info=$object->_load_ldap_info(); - $dn=$object->_load_ldap_dn($info); - $olddn=$dn; // We can say that old dn = dn as we force synchro - - $result=$ldap->update($dn,$info,$user,$olddn); - - if ($result >= 0) + if ($result > 0) { - setEventMessages($langs->trans("MemberSynchronized"), null, 'mesgs'); - $db->commit(); + $info=$object->_load_ldap_info(); + $dn=$object->_load_ldap_dn($info); + $olddn=$dn; // We can say that old dn = dn as we force synchro + + $result=$ldap->update($dn,$info,$user,$olddn); } - else - { + + if ($result >= 0) { + setEventMessages($langs->trans("MemberSynchronized"), null, 'mesgs'); + } + else { setEventMessages($ldap->errors, $ldap->error, 'errors'); - $db->rollback(); } } @@ -96,7 +93,7 @@ $head = member_prepare_head($object); dol_fiche_head($head, 'ldap', $langs->trans("Member"), 0, 'user'); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); diff --git a/htdocs/adherents/note.php b/htdocs/adherents/note.php index 325b14680e7..1b887406df3 100644 --- a/htdocs/adherents/note.php +++ b/htdocs/adherents/note.php @@ -74,12 +74,12 @@ if ($id) print "
"; print ''; - $linkback = ''.$langs->trans("BackToList").''; - + $linkback = ''.$langs->trans("BackToList").''; + dol_banner_tab($object, 'rowid', $linkback); - + print '
'; - + print '
'; print ''; diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index bddb8efb50b..4b8f3b50648 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -461,7 +461,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! $paiement = new Paiement($db); $paiement->datepaye = $paymentdate; $paiement->amounts = $amounts; - $paiement->paiementid = dol_getIdFromCode($db,$operation,'c_paiement'); + $paiement->paiementid = dol_getIdFromCode($db,$operation,'c_paiement','code','id',1); $paiement->num_paiement = $num_chq; $paiement->note = $label; @@ -601,7 +601,7 @@ if ($rowid > 0) dol_fiche_head($head, 'subscription', $langs->trans("Member"), -1, 'user'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); diff --git a/htdocs/adherents/type.php b/htdocs/adherents/type.php index b59d8b7530d..c9edce35f60 100644 --- a/htdocs/adherents/type.php +++ b/htdocs/adherents/type.php @@ -365,7 +365,7 @@ if ($rowid > 0) dol_fiche_head($head, 'card', $langs->trans("MemberType"), -1, 'group'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); diff --git a/htdocs/adherents/type_ldap.php b/htdocs/adherents/type_ldap.php index d4de1a2afdb..b8fc22f8f75 100644 --- a/htdocs/adherents/type_ldap.php +++ b/htdocs/adherents/type_ldap.php @@ -93,7 +93,7 @@ $head = member_type_prepare_head($object); dol_fiche_head($head, 'ldap', $langs->trans("MemberType"), -1, 'group'); -$linkback = ''.$langs->trans("BackToList").''; +$linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); diff --git a/htdocs/admin/agenda.php b/htdocs/admin/agenda.php index 50676e4c3af..cd07b4db587 100644 --- a/htdocs/admin/agenda.php +++ b/htdocs/admin/agenda.php @@ -80,8 +80,7 @@ if ($action == "save" && empty($cancel)) { $param='MAIN_AGENDA_ACTIONAUTO_'.$trigger['code']; //print "param=".$param." - ".$_POST[$param]; - if (GETPOST($param,'alpha')) $res = dolibarr_set_const($db,$param,GETPOST($param,'alpha'),'chaine',0,'',$conf->entity); - else $res = dolibarr_del_const($db,$param,$conf->entity); + $res = dolibarr_set_const($db,$param,(GETPOST($param,'alpha')?GETPOST($param,'alpha'):''),'chaine',0,'',$conf->entity); if (! $res > 0) $error++; } diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index bd84c1d6339..517c57c7d0b 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -1,10 +1,10 @@ +/* Copyright (C) 2001-2007 Rodolphe Quiedeville * Copyright (C) 2004-2013 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2005-2017 Regis Houssin * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2011-2017 Philippe Grand - * Copyright (C) 2015 Alexandre Spangaro + * Copyright (C) 2015 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -45,10 +45,18 @@ if (! $user->admin) accessforbidden(); $error=0; +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$contextpage=array('admincompany','globaladmin'); +$hookmanager->initHooks($contextpage); + /* * Actions */ +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ( ($action == 'update' && ! GETPOST("cancel",'alpha')) || ($action == 'updateedit') ) { diff --git a/htdocs/admin/defaultvalues.php b/htdocs/admin/defaultvalues.php index b758506f8b5..e4ba112511e 100644 --- a/htdocs/admin/defaultvalues.php +++ b/htdocs/admin/defaultvalues.php @@ -269,12 +269,12 @@ if ($mode != 'focus') { if ($mode != 'sortorder') { - $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object')); // Must match list into GETPOST - $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); + $substitutionarray=getCommonSubstitutionArray($langs, 2, array('object','objectamount')); // Must match list into GETPOST + unset($substitutionarray['__USER_SIGNATURE__']); $texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
'; foreach($substitutionarray as $key => $val) { - $texthelp.=$key.'
'; + $texthelp.=$key.' -> '.$val.'
'; } $textvalue=$form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, ''); // No tooltip on click, this also triggers the sort click } diff --git a/htdocs/admin/delais.php b/htdocs/admin/delais.php index d3ef125f2a7..37f66427225 100644 --- a/htdocs/admin/delais.php +++ b/htdocs/admin/delais.php @@ -137,7 +137,17 @@ if ($action == 'update') } } - dolibarr_set_const($db, "MAIN_DISABLE_METEO",$_POST["MAIN_DISABLE_METEO"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_METEO",$_POST["MAIN_DISABLE_METEO"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_USE_METEO_WITH_PERCENTAGE",GETPOST("MAIN_USE_METEO_WITH_PERCENTAGE"),'chaine',0,'',$conf->entity); + + // For update value with percentage + $plus=''; + if(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $plus = '_PERCENTAGE'; + // Update values + for($i=0;$i<4;$i++) { + if(isset($_POST['MAIN_METEO'.$plus.'_LEVEL'.$i])) dolibarr_set_const($db, 'MAIN_METEO'.$plus.'_LEVEL'.$i, GETPOST('MAIN_METEO'.$plus.'_LEVEL'.$i, 'int'),'chaine',0,'',$conf->entity); + } + } @@ -196,13 +206,6 @@ if ($action == 'edit') print '
'; print '
'.$langs->trans("MAIN_DISABLE_METEO").'' .$form->selectyesno('MAIN_DISABLE_METEO',(empty($conf->global->MAIN_DISABLE_METEO)?0:1),1) . '
'; - - print '
'; - - print '
'; - print '
'; - - print ''; } else { @@ -244,21 +247,30 @@ else print ''; - print '
'; - - // Boutons d'action - print '
'; - print ''.$langs->trans("Modify").''; - print '
'; - } print '
'; - // Show logo for weather print $langs->trans("DescWeather").'
'; +if($action == 'edit') { + + $str_mode_std = $langs->trans('MeteoStdModEnabled').' : '.$langs->trans('MeteoUseMod', $langs->trans('MeteoPercentageMod')); + $str_mode_percentage = $langs->trans('MeteoPercentageModEnabled').' : '.$langs->trans('MeteoUseMod', $langs->trans('MeteoStdMod')); + if(empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $str_mode_enabled = $str_mode_std; + else $str_mode_enabled = $str_mode_percentage; + print ''.$str_mode_enabled.''; + print ''; + + print '

'; + +} else { + if(empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) print $langs->trans('MeteoStdModEnabled'); + else print $langs->trans('MeteoPercentageModEnabled'); + print '

'; +} + $offset=0; $cursor=10; // By default //if (! empty($conf->global->MAIN_METEO_OFFSET)) $offset=$conf->global->MAIN_METEO_OFFSET; @@ -267,36 +279,143 @@ $level0=$offset; if (! empty($conf->global->MAIN_METEO_LEVEL0)) $level $level1=$offset+1*$cursor; if (! empty($conf->global->MAIN_METEO_LEVEL1)) $level1=$conf->global->MAIN_METEO_LEVEL1; $level2=$offset+2*$cursor; if (! empty($conf->global->MAIN_METEO_LEVEL2)) $level2=$conf->global->MAIN_METEO_LEVEL2; $level3=$offset+3*$cursor; if (! empty($conf->global->MAIN_METEO_LEVEL3)) $level3=$conf->global->MAIN_METEO_LEVEL3; -$text=''; $options='height="60px"'; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; +$text=''; $options='class="valignmiddle" height="60px"'; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print '
'; -print img_weather($text,'weather-clear.png',$options); -print '= '.$level0.'         '; -print img_weather($text,'weather-few-clouds.png',$options); -print '<= '.$level1.'         '; -print img_weather($text,'weather-clouds.png',$options); -print '<= '.$level2.'
'; -print img_weather($text,'weather-many-clouds.png',$options); -print '<= '.$level3.'         '; -print img_weather($text,'weather-storm.png',$options); -print '> '.$level3.'                        
'; +if ($action == 'edit') { + print '
global->MAIN_USE_METEO_WITH_PERCENTAGE) ? '' : 'style="display:none;"').'>'; + + print '
'; + print '
'; + print img_weather($text,'weather-clear.png', $options); + print '= '; + print '
'; + print img_weather($text,'weather-few-clouds.png',$options); + print '<= '; + print '
'; + print img_weather($text,'weather-clouds.png',$options); + print '<= '; + print '
'; + print img_weather($text,'weather-many-clouds.png',$options); + print '<= '; + print '
'; + print '
'; + + print '
'; + + print '
global->MAIN_USE_METEO_WITH_PERCENTAGE) ? 'style="display:none;"' : '').'>'; + + print '
'; + print '
'; + print img_weather($text,'weather-clear.png',$options); + print '=  %'; + print '
'; + print img_weather($text,'weather-few-clouds.png',$options); + print '<=  %'; + print '
'; + print img_weather($text,'weather-clouds.png',$options); + print '<=  %'; + print '
'; + print img_weather($text,'weather-many-clouds.png',$options); + print '<=  %'; + print '
'; + print '
'; + + 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/ihm.php b/htdocs/admin/ihm.php index 2322ae7a057..9d140d5a370 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -57,19 +57,19 @@ if (! defined("MAIN_MOTD")) define("MAIN_MOTD",""); 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 +89,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 +151,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 +218,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 +279,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 +346,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 +383,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 +422,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 +405,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 +454,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 +477,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 +517,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 +531,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_templates.php b/htdocs/admin/mails_templates.php index 755440a47fd..20aa084760e 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -53,7 +53,6 @@ $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'); @@ -94,26 +93,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 +146,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,6 +170,7 @@ 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['user']=$langs->trans('MailToUser'); $elementList['all'] =$langs->trans('VisibleEverywhere'); $elementList['none']=$langs->trans('VisibleNowhere'); @@ -229,10 +223,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 +252,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) { @@ -322,17 +298,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 +310,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 +326,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 +339,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 +361,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 +375,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) @@ -475,7 +438,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) @@ -541,11 +504,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 +526,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 +550,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 +563,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 ' '; + // 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 +690,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 +721,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 +742,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 +763,8 @@ if ($resql) // Show fields if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit'); - print ''; + print ''; + print ''; print ''; print ''; print ''; @@ -785,10 +772,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 +786,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 +855,12 @@ if ($resql) { $align="center"; } + if ($value == 'joinfiles') + { + $align="center"; + if ($valuetoshow) $valuetoshow=1; + else $valuetoshow=''; + } $class='tddict'; // Show value for field @@ -880,24 +885,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 +1044,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/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/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_dictionary.class.php b/htdocs/api/class/api_dictionary.class.php index 93f16d44377..b0d5bb00b0a 100644 --- a/htdocs/api/class/api_dictionary.class.php +++ b/htdocs/api/class/api_dictionary.class.php @@ -1,5 +1,9 @@ +/* Copyright (C) 2016 Xebax Christy + * 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 @@ -21,7 +25,7 @@ require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; /** - * API class for payment type (content of the paiement dictionary) + * API class for dictionaries * * @access protected * @class DolibarrApiAccess {@requires user,external} @@ -47,13 +51,14 @@ class Dictionary extends DolibarrApi * @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. Syntax example "(t.code:=:'CHQ')" + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" * - * @url GET payments + * @url GET payment/types * - * @return List of payment types - * - * @throws RestException + * @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 = '') { @@ -67,9 +72,9 @@ class Dictionary extends DolibarrApi { if (! DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } @@ -94,7 +99,7 @@ class Dictionary extends DolibarrApi $list[] = $this->db->fetch_object($result); } } else { - throw new RestException(503, 'Error when retrieving list of payment types : '.$this->db->lasterror()); + throw new RestException(400, $this->db->lasterror()); } return $list; @@ -447,6 +452,68 @@ class Dictionary extends DolibarrApi } 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_documents.class.php b/htdocs/api/class/api_documents.class.php index e26486981fa..52ed728a769 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -22,6 +22,7 @@ use Luracast\Restler\Format\UploadFormat; require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; /** * API class for receive files @@ -32,85 +33,148 @@ 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 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', ...) + * @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); - } + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $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); @@ -119,86 +183,86 @@ class Documents extends DolibarrApi $entity = $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."); - } + if ($modulepart == 'facture' || $modulepart == 'invoice') + { + $modulepart='facture'; + $object=new Facture($db); + $result = $object->fetch('', $ref); + } - $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 (! ($object->id > 0)) + { + throw new RestException(500, 'The object '.$modulepart." with ref '".$ref."' was not found."); + } + + $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.'); + } } 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/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..6242691d1f1 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -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 * 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/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index ec1c84dd652..12c11f863f1 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -907,59 +907,66 @@ class ActionComm extends CommonObject return $db->lasterror(); } } - + /** * 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; - - $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 . ")"; - - $resql=$this->db->query($sql); - if ($resql) - { - $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)) - { - $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; - } + global $conf, $langs; + + 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) + { + 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; + } + + $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/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/propal/card.php b/htdocs/comm/propal/card.php index a7540c69840..bc5beef8be7 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 ' @@ -1587,7 +1587,7 @@ if ($action == 'create') if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { - print '
'; + print '
'; // For backward compatibility print ''; @@ -1690,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); } @@ -1757,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 '
'; @@ -1933,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 @@ -2097,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 '
'; @@ -2046,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); @@ -2084,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 ''; @@ -2130,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 @@ -2154,7 +2162,7 @@ if ($action == 'create') // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print ''; @@ -2193,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)) @@ -2215,7 +2223,7 @@ if ($action == 'create') } print '
'; - print '
'; + print ''; print "\n"; @@ -2229,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') @@ -2237,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 diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 42dbdbf9d2c..325fad1a326 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 $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, '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/commande/card.php b/htdocs/commande/card.php index 5da8423c0a2..8d500f55e69 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -1716,7 +1716,7 @@ if ($action == 'create' && $user->rights->commande->creer) print '
'; print ''; print '     '; - print ''; + print ''; print '
'; print ''; diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index 11d3fe7260a..d41fd9cee1d 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -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..6ffca33a4ce 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -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..824d8faeb88 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -169,15 +169,11 @@ 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; /** - * Closed (Sent/Received, billed or not) + * Closed (Sent, billed or not) */ const STATUS_CLOSED = 3; @@ -1559,10 +1555,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 +3221,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 +3306,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 +3316,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 +3326,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 +3336,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 +3346,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 +3356,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 fed61c1fc17..c5cc5f9b715 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -213,7 +213,7 @@ if (empty($reshook)) // TODO Move this into mass action include if ($massaction == 'confirm_createbills') { - $orders = GETPOST('toselect'); + $orders = GETPOST('toselect','array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); $validate_invoices = GETPOST('valdate_invoices', 'int'); @@ -224,13 +224,13 @@ if (empty($reshook)) $db->begin(); - foreach($orders as $id_order) { - + foreach($orders as $id_order) + { $cmd = new Commande($db); - if($cmd->fetch($id_order) <= 0) continue; + 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. + 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; @@ -252,12 +252,10 @@ if (empty($reshook)) $res = $object->create($user); if($res > 0) $nb_bills_created++; - } - if($object->id > 0) { - - $db->begin(); + if ($object->id > 0) + { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; $sql.= "fk_source"; $sql.= ", sourcetype"; @@ -270,115 +268,113 @@ if (empty($reshook)) $sql.= ", '".$object->element."'"; $sql.= ")"; - if ($db->query($sql)) + if (! $db->query($sql)) { - $db->commit(); - } - else - { - $db->rollback(); + $error++; } - $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) + if (! $error) { - $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); + + 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; + } + } + } } - - $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; - } - } - } - } //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. @@ -391,27 +387,29 @@ if (empty($reshook)) $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; $toselect = array(); - if(!empty($validate_invoices)) { - + 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; + } - foreach($TAllFact as &$object) { - $object->validate($user); - $toselect[] = $object->id; // For builddoc action + $id = $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'; } - $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'; - + $massaction = $action = 'confirm_createbills'; } if (! $error) 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 99% rename from htdocs/compta/bank/bankentries.php rename to htdocs/compta/bank/bankentries_list.php index a04d9cf0f2e..271cb03cd6d 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 */ @@ -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) { @@ -1161,7 +1161,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..27de7b6e863 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..95e73183154 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -328,7 +328,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,7 +340,7 @@ 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").''; } diff --git a/htdocs/compta/bank/treso.php b/htdocs/compta/bank/treso.php index 0e2d3b35f38..cc0d58945e0 100644 --- a/htdocs/compta/bank/treso.php +++ b/htdocs/compta/bank/treso.php @@ -93,14 +93,14 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $head=bank_prepare_head($object); dol_fiche_head($head, 'cash', $langs->trans("FinancialAccount"), -1, 'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); dol_fiche_end(); - + print '
'; - + $solde = $object->solde(0); // Show next coming entries @@ -120,13 +120,13 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $var=true; // Current balance - + print ''; print ''; print ''; print ''; - + print ''; print ''; print ''; @@ -295,7 +295,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) // We discard lines with a remainder to pay to 0 if (price2num($total_ttc) != 0) { - + // Show line print ''; @@ -320,7 +320,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) } // Solde actuel - + print ''; print ''; print ''; diff --git a/htdocs/compta/bank/various_payment/index.php b/htdocs/compta/bank/various_payment/index.php index 48f37d24235..db668b47eef 100644 --- a/htdocs/compta/bank/various_payment/index.php +++ b/htdocs/compta/bank/various_payment/index.php @@ -96,7 +96,7 @@ $sql = "SELECT v.rowid, v.amount, v.label, v.datep as datep, v.datev as datev, v $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number as bank_account_number, ba.fk_accountancy_journal as accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_various as v"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id AND pst.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON v.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE v.entity = ".$conf->entity; diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index e048de2deb7..a504a730976 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -139,7 +139,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.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE cs.fk_type = c.id"; @@ -260,7 +260,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."tva as pv"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.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 pct ON pv.fk_typepayment = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " WHERE pv.entity = ".$conf->entity; if ($year > 0) { @@ -474,7 +474,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read) $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; $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.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id AND pct.entity = " . getEntity('c_paiement'); $sql.= " , ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE s.entity IN (".getEntity('user').")"; $sql.= " AND u.rowid = s.fk_user"; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 940ada5e04b..d2617d55429 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -38,6 +38,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php'; +require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; @@ -716,9 +717,13 @@ if (empty($reshook)) if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT - $sql = 'SELECT SUM(pf.amount) as total_paiements - FROM llx_c_paiement as c, llx_paiement_facture as pf, llx_paiement as p - WHERE pf.fk_facture = '.$object->id.' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; + + $sql = 'SELECT SUM(pf.amount) as total_paiements'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'c_paiement as c, '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; + $sql.= ' WHERE pf.fk_facture = '.$object->id; + $sql.= ' 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'; $resql = $db->query($sql); if (! $resql) dol_print_error($db); @@ -3798,6 +3803,7 @@ else if ($id > 0 || ! empty($ref)) $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); @@ -3810,18 +3816,21 @@ else if ($id > 0 || ! empty($ref)) 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)) { + if (! empty($conf->banque->enabled)) + { $bankaccountstatic->id = $objp->baid; $bankaccountstatic->ref = $objp->baref; $bankaccountstatic->label = $objp->baref; @@ -4324,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..d8a5a231593 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, @@ -378,7 +428,59 @@ class Invoices extends DolibarrApi } /** - * 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..0a9fa2872eb 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)."'"; diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index b22816f1473..fcf41e090cc 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -1076,18 +1076,19 @@ class Facture extends CommonInvoice } /** - * 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; @@ -1100,6 +1101,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 @@ -1197,8 +1206,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; @@ -1744,9 +1753,9 @@ class Facture extends CommonInvoice 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); // Test to avoid invoice deletion (allowed if draft) $test = $this->is_erasable(); @@ -2076,7 +2085,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) { @@ -2088,6 +2097,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) { @@ -2110,9 +2123,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 { @@ -3171,6 +3181,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); @@ -3217,6 +3228,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"; @@ -3364,36 +3377,39 @@ class Facture extends CommonInvoice * 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; - // on verifie si la facture est en numerotation provisoire - $facref = substr($this->ref, 1, 4); + // we check if invoice is a temporary number (PROVxxxx) + $tmppart = substr($this->ref, 1, 4); - if ($this->statut == self::STATUS_DRAFT && $facref == 'PROV') // If draft invoice and ref not yet defined + 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 1; + if (! empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) return 2; if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0; // 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(); @@ -3659,7 +3675,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/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..60156e0d047 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -1169,7 +1169,7 @@ 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); 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/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 '
'; - + 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,11 @@ else if ($object->type == Account::TYPE_SAVINGS || $object->type == Account::TYPE_CURRENT) { - print '
'; + 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 +764,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 +865,15 @@ else print ''; // Conciliable - print ''; - print ''; + print ''; + print ''; - // Balance + // Balance print ''; print ''; @@ -881,28 +881,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 +954,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 +834,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 +911,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 +929,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..8ff51305e08 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -412,8 +412,9 @@ class Account extends CommonObject 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 = "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) { @@ -1161,50 +1162,88 @@ class Account extends CommonObject */ function load_board(User $user, $filteraccountid = 0) { - global $conf, $langs; + 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; + } } @@ -1241,14 +1280,15 @@ class Account extends CommonObject } /** - * Return clicable name (with picto eventually) + * 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 + * @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='') + function getNomUrl($withpicto=0, $mode='', $option='', $save_lastsearch_value=-1) { global $conf, $langs; @@ -1266,22 +1306,27 @@ class Account extends CommonObject } $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - if (empty($mode)) + $url = DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id; + if ($mode == 'transactions') { - $link = ''; + $url = DOL_URL_ROOT.'/compta/bank/bankentries_list.php?id='.$this->id; } else if ($mode == 'receipts') { - $link = 'ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; return $result; 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 99% rename from htdocs/compta/bank/index.php rename to htdocs/compta/bank/list.php index 31c777740ac..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 */ @@ -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 '
'.$langs->trans("CurrentBalance").''.price($solde).'
'.$langs->trans("RemainderToPay").' 
'.$langs->trans("FutureBalance").' ('.$object->currency_code.')'.price($solde, 0, $langs, 0, 0, -1, $object->currency_code).'
'; + $paymentstatic->id = $objp->rowid; $paymentstatic->datepaye = $db->jdate($objp->dp); $paymentstatic->ref = $objp->ref; $paymentstatic->num_paiement = $objp->num_paiement; $paymentstatic->payment_code = $objp->payment_code; + + print '
'; print $paymentstatic->getNomUrl(1); print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . '
'.$langs->trans("RIB").''; print $object->thirdparty->display_rib(); 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..3d2daf5a53d 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'); 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..398f70ad36a 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'; } @@ -266,7 +271,7 @@ if ($action == 'create') { $objp = $charge; - + print ''; 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 ''; // 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/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 8b67cf318c7..eea830dfbc5 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -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"; @@ -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"; } diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 49d8766127e..bd1d8effcc7 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)) 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..13a2d29aff9 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,106 @@ 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 ''.$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/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 ac3c52ae8f5..dc6d19614f9 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -1064,7 +1064,7 @@ else } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref='
'; if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) 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 '
'.$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/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 "
"; - + $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..02970135b76 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -327,7 +327,7 @@ 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); @@ -440,6 +440,14 @@ if (empty($reshook)) $error++; } + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $error++; + } + // Extrafields $extrafieldsline = new ExtraFields($db); $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); @@ -638,90 +646,100 @@ if (empty($reshook)) 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) @@ -1311,7 +1329,7 @@ else // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; $morehtmlref=''; diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 61cd62bd338..071ae75e5b7 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -1938,19 +1938,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) { 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 ''; + 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 as we keep a method available on overloaded objects. + * + * @return void + */ + function printOriginLinesList() + { + 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); - } + 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); + } - $i++; - } - } + $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; + /** + * 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,98 @@ 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; - } - } + // 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 +3876,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 +3911,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 +3963,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 +3998,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 +4028,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 +4043,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 +4148,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,255 +4355,255 @@ 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 - * - * @param Extrafields $extrafields Extrafield Object - * @param string $mode Show output (view) or input (edit) for extrafield - * @param array $params Optional parameters - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * - * @return string - */ - function showOptionals($extrafields, $mode='view', $params=null, $keyprefix='') - { + * Function to show lines of extrafields with output datas + * + * @param Extrafields $extrafields Extrafield Object + * @param string $mode Show output (view) or input (edit) for extrafield + * @param array $params Optional parameters + * @param string $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; $out = ''; @@ -4594,23 +4627,28 @@ abstract class CommonObject }else { $colspan='3'; } + switch($mode) { case "view": $value=$this->array_options["options_".$key]; 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]); + // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc') + $getposttemp = GETPOST('options_'.$key, 'none'); // GETPOST can get value from GET, POST or setup of default values. + if (isset($getposttemp)) { + 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 +4671,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]); } + // Convert float submited string into real php numeric (value in memory must be a php numeric) + if (in_array($extrafields->attribute_type[$key],array('price','double'))) + { + $value = isset($_POST["options_".$key])?price2num($_POST["options_".$key]):$this->array_options['options_'.$key]; + } $labeltoshow = $langs->trans($label); + if($extrafields->attribute_required[$key]) { $labeltoshow = ''.$labeltoshow.''; @@ -4650,12 +4694,12 @@ abstract class CommonObject $out .=''; @@ -4736,9 +4780,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 +5043,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 +5086,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 +5098,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 +5113,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 +5186,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 +5222,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 +5247,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 +5281,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 +5323,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/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 4c7fb824559..277ff7a3895 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -804,7 +804,7 @@ 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) @@ -893,7 +893,7 @@ 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, $keysuffix.'options_'.$key.$keyprefix, $showtime, $showtime, $required, '', 1, ($keysuffix != 'search_' ? 1 : 0), 1, 0, 1); } elseif (in_array($type,array('int'))) { @@ -927,11 +927,14 @@ class ExtraFields } 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=' '; @@ -1323,7 +1326,8 @@ class ExtraFields } 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=''; @@ -1683,7 +1687,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 f33ab83ee29..dd8a0b967de 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -46,527 +46,527 @@ */ 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.='
'.$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 64f2b6b94f2..dfc00f95e11 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"); @@ -126,6 +129,7 @@ $arrayfields=array( '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 @@ -157,6 +161,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $day=''; $month=''; $year=''; + $search_dfmonth=''; + $search_dfyear=''; + $search_op2df=''; $search_name=""; $search_email=""; $search_town=''; @@ -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,'; @@ -278,10 +286,16 @@ $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,6 +303,11 @@ $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; @@ -323,16 +342,22 @@ if ($resql) } $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_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; + 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) { @@ -537,6 +562,18 @@ if ($resql) print ''; } + // First end date + if (! empty($arrayfields['lower_planned_end_date']['checked'])) + { + print ''; + } // Status if (! empty($arrayfields['status']['checked'])) { @@ -581,6 +618,7 @@ if ($resql) 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['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"'); @@ -600,6 +638,11 @@ if ($resql) $contracttmp->ref_customer=$obj->ref_customer; $contracttmp->ref_supplier=$obj->ref_supplier; + if ($obj->socid > 0) + { + $result=$socstatic->fetch($obj->socid); + } + print ''; if (! empty($arrayfields['c.ref']['checked'])) { @@ -631,7 +674,13 @@ if ($resql) } if (! empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['s.email']['checked'])) { @@ -683,7 +732,6 @@ if ($resql) 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'])) { 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 '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'; 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 '
'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; + //print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; + if ($obj->socid > 0) + { + print $socstatic->getNomUrl(1, ''); + } + print ''; if ($obj->socid > 0) { - $result=$socstatic->fetch($obj->socid); $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); if ($listsalesrepresentatives < 0) dol_print_error($db); $nbofsalesrepresentative=count($listsalesrepresentatives); @@ -759,6 +807,14 @@ if ($resql) print ''; + print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day'); + 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/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_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_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 4439f0034ce..7b1db834d22 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; 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 91da8072922..937634de5d4 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -419,9 +419,9 @@ abstract class CommonDocGenerator } // Fetch project information if there is a project assigned to this object - if ($object->element != "project" && $object->fk_project > 0) + if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0) { - if(!isset($object->project)) + if (! is_object($object->project)) { $object->fetch_projet(); } 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..a09ae3722d4 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 '
  '.$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, '', $keyprefix, '', 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 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; - $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; + } + } + return $ret; + } - /** - * 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; + /** + * 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; - $out=''; + $out=''; - // 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'); + // 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 ($condition) - { - $element = false; - $table_element = false; - $fk_element = false; - $loadmethod = false; - $savemethod = false; - $ext_element = false; - $button_only = false; - $inputOption = ''; + if ($condition) + { + $element = false; + $table_element = false; + $fk_element = false; + $loadmethod = false; + $savemethod = false; + $ext_element = false; + $button_only = false; + $inputOption = ''; - if (is_object($object)) - { - $element = $object->element; - $table_element = $object->table_element; - $fk_element = $object->id; - } + if (is_object($object)) + { + $element = $object->element; + $table_element = $object->table_element; + $fk_element = $object->id; + } - if (is_object($extObject)) - { - $ext_element = $extObject->element; - } + 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]; + 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 +749,701 @@ 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; + print ''; + $i++; + } + } + print ''; + return $qualifiedlines; + } + else + { + dol_print_error($this->db); + return -1; + } + } - // 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; + /** + * 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; + } - $excludeUsers=null; - $includeUsers=null; + /** + * 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; - // Permettre l'exclusion d'utilisateurs - if (is_array($exclude)) $excludeUsers = implode(",",$exclude); - // Permettre l'inclusion d'utilisateurs - if (is_array($include)) $includeUsers = implode(",",$include); + $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 +1451,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 +1671,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 +1798,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 +1895,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 +2044,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 +2065,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 +3265,357 @@ 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'=> , )) + * @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'].'"':''); - 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); + $more.='
'.$input['label'].' '; + $more.=' $selval) + { + $more.='
'.$input['label'].' '; @@ -3626,71 +3628,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 +4358,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 +4382,435 @@ 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"); + } + } + 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; + } - // 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)?'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 = ""; + // 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") + // 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 +4938,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.=' -