From 328d39bc71a367dd9f8a16d220b0fcaca675c299 Mon Sep 17 00:00:00 2001 From: Scrutinizer Auto-Fixer Date: Sat, 7 Oct 2017 11:09:31 +0000 Subject: [PATCH] Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com --- htdocs/accountancy/admin/accountmodel.php | 1424 +-- htdocs/accountancy/admin/journals_list.php | 844 +- htdocs/adherents/class/adherent.class.php | 3140 +++--- htdocs/admin/ihm.php | 450 +- htdocs/admin/ldap_members.php | 32 +- htdocs/admin/ldap_users.php | 88 +- htdocs/api/class/api_documents.class.php | 124 +- htdocs/comm/propal/card.php | 386 +- .../comm/propal/class/api_proposals.class.php | 792 +- htdocs/comm/propal/class/propal.class.php | 6124 +++++------ htdocs/compta/bank/card.php | 510 +- htdocs/compta/sociales/card.php | 462 +- htdocs/core/class/commonobject.class.php | 6104 +++++------ htdocs/core/class/html.form.class.php | 9666 ++++++++--------- htdocs/core/class/ldap.class.php | 46 +- htdocs/core/class/notify.class.php | 862 +- htdocs/core/lib/files.lib.php | 1330 +-- htdocs/core/lib/project.lib.php | 318 +- htdocs/core/lib/usergroups.lib.php | 790 +- htdocs/core/lib/website.lib.php | 78 +- htdocs/core/login/functions_ldap.php | 38 +- htdocs/core/modules/DolibarrModules.class.php | 3846 +++---- .../modules/dons/html_cerfafr.modules.php | 470 +- ..._50_modNotification_Notification.class.php | 120 +- htdocs/ecm/class/ecmfiles.class.php | 90 +- htdocs/expedition/class/expedition.class.php | 578 +- htdocs/fichinter/class/fichinter.class.php | 330 +- .../class/fournisseur.commande.class.php | 5304 ++++----- htdocs/fourn/class/paiementfourn.class.php | 142 +- htdocs/fourn/commande/list.php | 1274 +-- htdocs/fourn/paiement/card.php | 144 +- htdocs/holiday/class/holiday.class.php | 2922 ++--- htdocs/projet/activity/perday.php | 222 +- htdocs/projet/activity/perweek.php | 206 +- htdocs/projet/card.php | 1632 +-- htdocs/projet/class/task.class.php | 2546 ++--- htdocs/projet/list.php | 598 +- htdocs/theme/eldy/style.css.php | 18 +- htdocs/user/card.php | 3190 +++--- htdocs/user/class/user.class.php | 466 +- htdocs/user/ldap.php | 70 +- htdocs/websites/index.php | 1968 ++-- 42 files changed, 29872 insertions(+), 29872 deletions(-) diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 66f2e156b4c..03565528fc1 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -158,309 +158,309 @@ $sourceList=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) - { - 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); + } } @@ -480,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"; @@ -489,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); @@ -498,557 +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; + } - 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'); + } + } - print ''; - print ""; + print ''; + print ""; - $colspan=count($fieldlist)+3; + $colspan=count($fieldlist)+3; - if (! empty($alabelisused)) // 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 line with search boxes - print ''; - foreach ($fieldlist as $field => $value) - { - $showfield=1; // By defaut + // 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 ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } - if ($showfield) - { - if ($value == 'country') - { - print ''; - } - else - { - print ''; - } - } - } - print ''; - print ''; - print ''; + 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=''; - /* + // 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); - } - } + // 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 ''; - 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 ($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 ''; - $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; + $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 (empty($reshook)) fieldListAccountModel($fieldlist,$obj,$tabname[$id],'edit'); + if (empty($reshook)) fieldListAccountModel($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 ($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; } - } + // 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; + 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.='&'; + $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 "\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 '
'; - 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 ($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().' '.img_delete().' '.img_delete().' 
'; + print ''; print '
'; - print '
'; + print ''; } print '
'; @@ -1152,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 9bbd37449be..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,214 +144,214 @@ $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); + } } @@ -368,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); @@ -378,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); @@ -387,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 line with search boxes - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + // 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=''; - /* + // 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 ''; - 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/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index d5fed99701e..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?"'".$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,1170 +790,1170 @@ 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 ('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; + /** + * 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.='
'; - $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.$this->id; - if ($option == 'subscription') - { - $url = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$this->id; - } + $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.$this->id; + if ($option == 'subscription') + { + $url = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$this->id; + } - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; - if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; - } + if ($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 = '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:'').'"'; - } + $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:'').'"'; + } - $link.=$linkclose.'>'; - $linkend=''; + $link.=$linkclose.'>'; + $linkend=''; - //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.='
'; + //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.='
'; - return $result; - } + return $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); - } + /** + * 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'); - } - } + /** + * 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 - */ + /** + * Initialise tableau info (tableau des attributs LDAP) + * + * @return array Tableau info des attributs + */ function _load_ldap_info() { global $conf,$langs; @@ -2052,63 +2052,63 @@ class Adherent extends CommonObject } - /** - * 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. @@ -2177,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/admin/ihm.php b/htdocs/admin/ihm.php index 70589a516fd..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,7 +89,7 @@ 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); @@ -103,44 +103,44 @@ if ($action == 'update') 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())))); + $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); @@ -151,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'); + } + } } @@ -218,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 ''; @@ -279,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 ''; @@ -346,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"; @@ -383,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 ''; @@ -422,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 '
'; @@ -405,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 ""; @@ -454,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 ""; @@ -477,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 ''; @@ -517,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 ""; @@ -531,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 da04c852b2f..0dccb9967fe 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -66,7 +66,7 @@ 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++; @@ -85,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); + } } diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index 30ec8d8153c..8be03267783 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -63,7 +63,7 @@ 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++; @@ -74,22 +74,22 @@ if ($action == 'setvalue' && $user->admin) 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); + } } @@ -430,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, @@ -439,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, @@ -447,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/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 8c170cc78ad..9ac5b643476 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -87,94 +87,94 @@ class Documents extends DolibarrApi if (preg_match('/\.\./',$original_file) || preg_match('/[<>|]/',$original_file)) { - throw new RestException(401); + throw new RestException(401); + } + if (!$accessallowed) { + 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; + // --- 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, $outputlangs, $hidedetails, $hidedesc, $hideref); - if( $result <= 0 ) { - throw new RestException(500, 'Error generating document'); - } - } - } + 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, $outputlangs, $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'); + 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 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 - */ - /* + /** + * 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; + /** + * 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($modulepart); var_dump($filename); var_dump($filecontent); exit;*/ - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - if (!DolibarrApiAccess::$user->rights->ecm->upload) { - throw new RestException(401); - } + if (!DolibarrApiAccess::$user->rights->ecm->upload) { + throw new RestException(401); + } - $newfilecontent = ''; - if (empty($fileencoding)) $newfilecontent = $filecontent; - if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); + $newfilecontent = ''; + if (empty($fileencoding)) $newfilecontent = $filecontent; + if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); $original_file = dol_sanitizeFileName($filename); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index d127b0b0e09..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,13 +1690,13 @@ 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)); - 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)), - )); - } + 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); @@ -1765,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 '
'; @@ -1941,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 @@ -2105,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 '
'; @@ -2054,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); @@ -2092,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 ''; @@ -2138,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 @@ -2162,7 +2162,7 @@ if ($action == 'create') // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print ''; @@ -2201,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)) @@ -2223,7 +2223,7 @@ if ($action == 'create') } print '
'; - print ''; + print ''; print "\n"; @@ -2237,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') @@ -2245,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 '
' . $langs->trans('Validate') . '
'; - } - else + } + else print '
' . $langs->trans('Validate') . '
'; } // Create event diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index f719dbf7ea8..7dda7031914 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -30,225 +30,225 @@ 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) - { + /** + * 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)) { @@ -257,288 +257,288 @@ class Proposals extends DolibarrApi $request_data = (object) $request_data; - $updateRes = $this->propal->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - 'HT', - 0, - $request_data->info_bits, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->date_start, - $request_data->date_end, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id, - $request_data->multicurrency_subprice, - $request_data->fk_remise_except - ); + $updateRes = $this->propal->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + 'HT', + 0, + $request_data->info_bits, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->date_start, + $request_data->date_end, + $request_data->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id, + $request_data->multicurrency_subprice, + $request_data->fk_remise_except + ); - if ($updateRes > 0) { - return $this->get($id)->line->rowid; + if ($updateRes > 0) { + return $this->get($id)->line->rowid; - } - return false; - } + } + 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) { + /** + * 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 <= 0) { - throw new RestException(404, '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; + $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'); - } + $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 - ); + $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; - } + 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) { + /** + * 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'); - } + $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; - } + $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) { + /** + * 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'); - } + $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; - } + 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); + if($this->propal->update($id, DolibarrApiAccess::$user,1,'','','update')) + return $this->get($id); - return false; - } + return false; + } - /** - * Delete commercial proposal - * - * @param int $id Commercial proposal ID - * - * @return array - */ - function delete($id) - { - if(! DolibarrApiAccess::$user->rights->propal->supprimer) { + /** + * 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); } - if( ! $this->propal->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when delete 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 deleted' - ) - ); + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal deleted' + ) + ); - } + } - /** - * 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) { + /** + * 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'); - } + $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); - } + $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.')' - ) - ); - } + 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]; + /** + * 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; - } + } + return $propal; + } - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - function _cleanObjectDatas($object) { + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + function _cleanObjectDatas($object) { - $object = parent::_cleanObjectDatas($object); + $object = parent::_cleanObjectDatas($object); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->address); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->address); - return $object; - } + return $object; + } } diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 5b9fda29a6d..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,390 +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 - if (empty($type)) $type=0; + // 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); @@ -840,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 @@ -864,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, @@ -989,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)) { @@ -1160,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 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.= ", 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; @@ -1357,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 @@ -1505,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) { @@ -1612,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); @@ -2223,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; } @@ -2249,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"); @@ -3005,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; @@ -3444,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. @@ -3513,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 @@ -3533,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 @@ -3587,7 +3587,7 @@ class PropaleLigne extends CommonObjectLine * @deprecated * @see product_label */ - var $libelle; + var $libelle; /** * Product label * @var string @@ -3597,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; @@ -3619,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,'; @@ -3696,7 +3696,7 @@ class PropaleLigne extends CommonObjectLine $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_end = $this->db->jdate($objp->date_end); // Multicurrency $this->fk_multicurrency = $objp->fk_multicurrency; @@ -3708,7 +3708,7 @@ class PropaleLigne extends CommonObjectLine $this->db->free($result); - return 1; + return 1; } else { @@ -3721,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) @@ -3772,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 @@ -3964,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/compta/bank/card.php b/htdocs/compta/bank/card.php index 352e1db5e6b..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/list.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 ''; @@ -347,12 +347,12 @@ if ($action == 'create') print ''; // Status - print ''.$langs->trans("Status").''; - print ''; - print $form->selectarray("clos", $object->status,(GETPOST("clos",'int')!=''?GETPOST("clos",'int'):$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"]) @@ -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 '
'.$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/sociales/card.php b/htdocs/compta/sociales/card.php index 7dff138f849..1634ec4bf5f 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -63,50 +63,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 +131,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 +166,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 +182,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'); + } } } @@ -293,51 +293,51 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("NewSocialContribution")); - $var=false; + $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 ''; + // Amount + print ''; + print ''; print ''; - print ''; + print ''; // Project if (! empty($conf->projet->enabled)) @@ -354,30 +354,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",'alpha')?GETPOST("actioncode",'alpha'):'','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 +387,7 @@ if ($action == 'create') print ''; print ''; - print '
'; + print ''; } /* *************************************************************************** */ @@ -398,7 +398,7 @@ if ($action == 'create') if ($id > 0) { $object = new ChargeSociales($db); - $result=$object->fetch($id); + $result=$object->fetch($id); if ($result > 0) { @@ -414,7 +414,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 +445,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 +492,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 +517,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 ''; @@ -588,59 +588,59 @@ if ($id > 0) $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 ''; + print ''; + print ''; - $var=true; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($resql); + $var=true; + 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"; + print '\n"; + print ""; + $totalpaye += $objp->amount; + $i++; + } + } + else + { - print ''; - } + print ''; + } - //if ($object->status == ChargeSociales::STATUS_DRAFT) - //{ - print "\n"; - print "\n"; + //if ($object->status == ChargeSociales::STATUS_DRAFT) + //{ + print "\n"; + print "\n"; - $resteapayer = $object->amount - $totalpaye; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + $resteapayer = $object->amount - $totalpaye; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - print ""; - print '\n"; - //} - print "
'.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").''.$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."'.price($objp->amount)."
'.$langs->trans("None").'
'.$langs->trans("None").'
".$langs->trans("AlreadyPaid")." :".price($totalpaye)."
".$langs->trans("AmountExpected")." :".price($object->amount)."
".$langs->trans("AlreadyPaid")." :".price($totalpaye)."
".$langs->trans("AmountExpected")." :".price($object->amount)."
".$langs->trans("RemainderToPay")." :'.price($resteapayer)."
"; - $db->free($resql); + 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/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 5d96945c17a..a09ae3722d4 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -40,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 */ @@ -70,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 @@ -332,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 /** @@ -390,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=''; @@ -495,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)) { @@ -510,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)) { @@ -527,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++; @@ -542,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)) @@ -1595,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'; @@ -1932,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) @@ -1980,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; @@ -1993,273 +1993,273 @@ 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; // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield) $MODULE = ""; @@ -2321,9 +2321,9 @@ abstract class CommonObject $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'; + $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 @@ -2331,22 +2331,22 @@ abstract class CommonObject $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->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_tva = 0; $this->multicurrency_total_ttc = 0; - $num = $this->db->num_rows($resql); - $i = 0; - while ($i < $num) - { + $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' @@ -2404,11 +2404,11 @@ abstract class CommonObject } $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')) @@ -2427,23 +2427,23 @@ 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)) - { + if (empty($nodatabaseupdate)) + { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET'; $sql .= " ".$fieldht."='".price2num($this->total_ht)."',"; $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',"; @@ -2460,60 +2460,60 @@ abstract class CommonObject $resql=$this->db->query($sql); if (! $resql) { - $error++; - $this->error=$this->db->lasterror(); - $this->errors[]=$this->db->lasterror(); + $error++; + $this->error=$this->db->lasterror(); + $this->errors[]=$this->db->lasterror(); } - } + } - if (! $error) - { + if (! $error) + { return 1; - } - else - { + } + else + { return -1; - } + } } else { - dol_print_error($this->db,'Bad request in update_price'); - return -1; + 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(); @@ -2527,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 */ @@ -2839,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 { @@ -2913,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; @@ -3177,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)) { @@ -3251,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; @@ -3277,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; @@ -3311,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; @@ -3361,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) { @@ -3371,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 */ /** @@ -3414,75 +3414,75 @@ abstract class CommonObject $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { - print ''; + print ''; - if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ' '; + if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ' '; - // Description - print ''.$langs->trans('Description').''; + // Description + print ''.$langs->trans('Description').''; - if ($this->element == 'supplier_proposal') - { - print ''.$langs->trans("SupplierProposalRefFourn").''; - } + if ($this->element == 'supplier_proposal') + { + print ''.$langs->trans("SupplierProposalRefFourn").''; + } - // VAT - print ''.$langs->trans('VAT').''; + // VAT + print ''.$langs->trans('VAT').''; - // Price HT - print ''.$langs->trans('PriceUHT').''; + // Price HT + print ''.$langs->trans('PriceUHT').''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; + // Multicurrency + if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; - if ($inputalsopricewithtax) print ''.$langs->trans('PriceUTTC').''; + if ($inputalsopricewithtax) print ''.$langs->trans('PriceUTTC').''; - // Qty - print ''.$langs->trans('Qty').''; + // Qty + print ''.$langs->trans('Qty').''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''.$langs->trans('Unit').''; - } + if($conf->global->PRODUCT_USE_UNITS) + { + print ''.$langs->trans('Unit').''; + } - // Reduction short - print ''.$langs->trans('ReductionShort').''; + // Reduction short + print ''.$langs->trans('ReductionShort').''; - if ($this->situation_cycle_ref) { - print '' . $langs->trans('Progress') . ''; - } + if ($this->situation_cycle_ref) { + print '' . $langs->trans('Progress') . ''; + } - if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) - { - if (!empty($user->rights->margins->creer)) - { - if ($conf->global->MARGIN_TYPE == "1") - print ''.$langs->trans('BuyingPrice').''; - else - print ''.$langs->trans('CostPrice').''; - } + if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id)) + { + if (!empty($user->rights->margins->creer)) + { + if ($conf->global->MARGIN_TYPE == "1") + print ''.$langs->trans('BuyingPrice').''; + else + print ''.$langs->trans('CostPrice').''; + } - if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) - print ''.$langs->trans('MarginRate').''; - if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) - print ''.$langs->trans('MarkRate').''; - } + if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) + print ''.$langs->trans('MarginRate').''; + if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) + print ''.$langs->trans('MarkRate').''; + } - // Total HT - print ''.$langs->trans('TotalHTShort').''; + // Total HT + print ''.$langs->trans('TotalHTShort').''; - // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; + // Multicurrency + if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; - if ($outputalsopricetotalwithtax) print ''.$langs->trans('TotalTTCShort').''; + if ($outputalsopricetotalwithtax) print ''.$langs->trans('TotalTTCShort').''; - print ''; // No width to allow autodim + print ''; // No width to allow autodim - print ''; + print ''; - print ''; + print ''; - print "\n"; + print "\n"; } $var = true; @@ -3496,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); } @@ -3561,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 @@ -3641,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 ''.$langs->trans('Ref').''; - print ''.$langs->trans('Description').''; - print ''.$langs->trans('VATRate').''; - print ''.$langs->trans('PriceUHT').''; + print ''; + print ''.$langs->trans('Ref').''; + print ''.$langs->trans('Description').''; + print ''.$langs->trans('VATRate').''; + print ''.$langs->trans('PriceUHT').''; if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency').''; - print ''.$langs->trans('Qty').''; - if($conf->global->PRODUCT_USE_UNITS) - { - print ''.$langs->trans('Unit').''; - } - print ''.$langs->trans('ReductionShort').''; + print ''.$langs->trans('Qty').''; + if($conf->global->PRODUCT_USE_UNITS) + { + print ''.$langs->trans('Unit').''; + } + print ''.$langs->trans('ReductionShort').''; - $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; @@ -3728,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; + } + } /** @@ -3876,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; + } } @@ -3911,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 @@ -3963,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 @@ -3998,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)) @@ -4028,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. @@ -4043,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 { @@ -4148,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(); @@ -4355,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 = ''; @@ -4694,12 +4694,12 @@ abstract class CommonObject $out .=''; 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 .= ''; @@ -4780,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; } } @@ -5043,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}; + } - } + } } /** @@ -5086,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); } /** @@ -5098,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)."'"; } @@ -5113,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) { @@ -5186,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; } } @@ -5222,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. @@ -5247,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; } } @@ -5281,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; } } @@ -5323,9 +5323,9 @@ abstract class CommonObject */ public function initAsSpecimenCommon() { - $this->id = 0; + $this->id = 0; - // TODO... + // TODO... } /** diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 9cb120fa61d..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.=''; - 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 entity = " . getEntity('c_payment_term'); - $sql.= " AND 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"; - $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 + 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 @@ -3265,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"; - } + else if ($input['type'] == 'other') + { + $more.=''."\n"; + } - else if ($input['type'] == 'onecolumn') - { - $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'].' '; @@ -3628,78 +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.='
'; + if (! empty($input['label'])) $more.=$input['label'].''; + $more.=$input['value']; + $more.='
'; - $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; @@ -4358,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(); @@ -4382,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.'\');'; @@ -4938,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.=' -