46 const TRIGGER_PREFIX =
'';
76 public $errors = array();
81 private $validateFieldsErrors = array();
92 public $element_for_permission;
97 public $table_element;
102 public $table_element_line =
'';
112 public $array_options = array();
117 public $array_languages =
null;
122 public $contacts_ids;
127 public $linked_objects;
132 public $linkedObjectsIds;
137 public $linkedObjects;
142 private $linkedObjectsFullLoaded = array();
152 protected $table_ref_field =
'';
157 public $restrictiononfksoc = 0;
165 public $context = array();
245 public $ref_previous;
286 public $country_code;
329 public $barcode_type;
335 public $barcode_type_code;
341 public $barcode_type_label;
347 public $barcode_type_coder;
353 public $mode_reglement_id;
359 public $cond_reglement_id;
364 public $demand_reason_id;
370 public $transport_mode_id;
377 public $cond_reglement;
384 public $fk_delivery_address;
390 public $shipping_method_id;
409 public $last_main_doc;
439 public $note_private;
463 public $total_localtax1;
469 public $total_localtax2;
486 public $comments = array();
512 public $date_creation;
517 public $date_validation;
522 public $date_modification;
527 public $date_cloture;
538 public $user_creation;
542 public $user_creation_id;
553 public $user_validation;
557 public $user_validation_id;
561 public $user_closing_id;
567 public $user_modification;
571 public $user_modification_id;
574 public $next_prev_filter;
579 public $specimen = 0;
592 protected $labelStatus;
593 protected $labelStatusShort;
599 protected $childtables = array();
606 protected $childtablesoncascade = array();
626 $sql =
"SELECT rowid, ref, ref_ext";
627 $sql .=
" FROM ".$db->prefix().$element;
628 $sql .=
" WHERE entity IN (".getEntity($element).
")";
631 $sql .=
" AND rowid = ".((int) $id);
633 $sql .=
" AND ref = '".$db->escape($ref).
"'";
634 } elseif ($ref_ext) {
635 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
637 $error =
'ErrorWrongParameters';
641 if ($ref || $ref_ext) {
642 $sql .=
" AND entity = ".((int) $conf->entity);
645 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
646 $resql = $db->query($sql);
648 $num = $db->num_rows(
$resql);
666 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
680 $parameters = array(
'objref'=>$objref);
682 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
684 return $hookmanager->resArray[
'objref'];
686 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
699 $parameters = array(
'objref'=>$objref);
701 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
703 return $hookmanager->resArray[
'objref'];
705 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
717 public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
720 $lastname = $this->lastname;
721 $firstname = $this->firstname;
722 if (empty($lastname)) {
723 $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 :
'')))));
727 if (!empty($option) && !empty($this->civility_code)) {
728 if ($langs->transnoentitiesnoconv(
"Civility".$this->civility_code) !=
"Civility".$this->civility_code) {
729 $ret .= $langs->transnoentitiesnoconv(
"Civility".$this->civility_code).
' ';
731 $ret .= $this->civility_code.
' ';
749 if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
755 if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
760 if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
764 if (isset($this->email)) {
767 if (isset($this->personal_email)) {
780 $return =
'<div class="box-flex-item box-flex-grow-zero">';
781 $return .=
'<div class="info-box info-box-sm">';
782 $return .=
'<span class="info-box-icon bg-infobox-action">';
784 $return .=
'</span>';
785 $return .=
'<div class="info-box-content">';
786 $return .=
'<span class="info-box-ref">'.(method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref).
'</span>';
787 if (property_exists($this,
'label')) {
788 $return .=
'<br><span class="info-box-label opacitymedium">'.$this->label.
'</span>';
790 if (method_exists($this,
'getLibStatut')) {
791 $return .=
'<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).
'</div>';
809 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
811 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
812 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
813 $tmparray =
getCountry($this->country_id,
'all');
814 $this->country_code = $tmparray[
'code'];
815 $this->country = $tmparray[
'label'];
818 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
819 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
820 $tmparray =
getState($this->state_id,
'all', 0, 1);
821 $this->state_code = $tmparray[
'code'];
822 $this->state = $tmparray[
'label'];
823 $this->region_code = $tmparray[
'region_code'];
824 $this->region = $tmparray[
'region'];
840 global $conf, $langs,
$form, $extralanguages;
842 $countriesusingstate = array(
'AU',
'US',
'IN',
'GB',
'ES',
'UK',
'TR');
846 $elementforaltlanguage = $this->element;
847 if ($this->element ==
'societe') {
848 $thirdpartyid = $this->id;
850 if ($this->element ==
'contact') {
851 $contactid = $this->id;
852 $thirdpartyid = empty($this->fk_soc) ? 0 : $this->fk_soc;
854 if ($this->element ==
'user') {
855 $contactid = $this->contact_id;
856 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
862 $coords = $this->
getFullAddress(1,
', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
864 if (!empty($conf->use_javascript_ajax)) {
867 if ($this->element ==
'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
868 $namecoords .= $object->name.
'<br>';
870 $namecoords .= $this->
getFullName($langs, 1).
'<br>'.$coords;
872 $out .=
'<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).
'\',\
''.dol_escape_js($langs->trans(
"HelpCopyToClipboard")).
'\');
">';
873 $out .= img_picto($langs->trans("Address
"), 'map-marker-alt');
876 $address = dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
883 // List of extra languages
884 $arrayoflangcode = array();
885 if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
886 $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
889 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
890 if (!is_object($extralanguages)) {
891 include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
892 $extralanguages = new ExtraLanguages($this->db);
894 $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
896 if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
897 $out .= "<!-- alternatelanguage
for '".$elementforaltlanguage."' set to fields
'".join(',
', $extralanguages->attributes[$elementforaltlanguage])."' -->\n
";
898 $this->fetchValuesForExtraLanguages();
899 if (!is_object($form)) {
900 $form = new Form($this->db);
903 // If there is extra languages
904 foreach ($arrayoflangcode as $extralangcode) {
905 $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright
"');
906 // This also call dol_format_address()
907 $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
908 $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
910 $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
915 // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
916 if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)
917 && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
918 if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
919 $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
921 $out .= ($outdone ? ' - ' : '').$this->state;
927 $out = '<div class="address
inline-block
">'.$out.'</div>';
930 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)) {
931 $out .= ($outdone ? '<br>' : '');
933 if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
934 $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
937 if (!empty($this->phone_pro)) {
938 $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
941 if (!empty($this->phone_mobile)) {
942 $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
945 if (!empty($this->phone_perso)) {
946 $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso
"));
949 if (!empty($this->office_phone)) {
950 $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
953 if (!empty($this->user_mobile)) {
954 $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
957 if (!empty($this->fax)) {
958 $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
961 if (!empty($this->office_fax)) {
962 $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
967 $out .= '<div style="clear: both;
"></div>';
970 if (!empty($this->email)) {
971 $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
974 if (!empty($this->url)) {
975 //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
976 $out .= dol_print_url($this->url, '_blank', 0, 1);
980 if (isModEnabled('socialnetworks')) {
981 $outsocialnetwork = '';
983 if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
984 $socialnetworksdict = getArrayOfSocialNetworks();
985 foreach ($this->socialnetworks as $key => $value) {
987 $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
991 } else { // Old code to remove
992 if (!empty($this->skype)) {
993 $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
996 if (!empty($this->jabberid)) {
997 $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
1000 if (!empty($this->twitter)) {
1001 $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
1004 if (!empty($this->facebook)) {
1005 $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
1008 if (!empty($this->linkedin)) {
1009 $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
1014 if ($outsocialnetwork) {
1015 $out .= '<div style="clear: both;
">'.$outsocialnetwork.'</div>';
1020 return '<!-- BEGIN part to show address block -->'."\n
".$out.'<!-- END Part to show address block -->'."\n
";
1034 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1036 global $user, $dolibarr_main_url_root;
1038 if (empty($this->last_main_doc)) {
1039 return ''; // No way to known which document name to use
1042 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1043 $ecmfile = new EcmFiles($this->db);
1044 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1046 $this->error = $ecmfile->error;
1047 $this->errors = $ecmfile->errors;
1051 if (empty($ecmfile->id)) {
1052 // Add entry into index
1053 if ($initsharekey) {
1054 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1056 // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
1058 $ecmfile->filepath = $rel_dir;
1059 $ecmfile->filename = $filename;
1060 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1061 $ecmfile->fullpath_orig = '';
1062 $ecmfile->gen_or_uploaded = 'generated';
1063 $ecmfile->description = ''; // indexed content
1064 $ecmfile->keywords = ''; // keyword content
1065 $ecmfile->share = getRandomPassword(true);
1066 $result = $ecmfile->create($user);
1069 $this->error = $ecmfile->error;
1070 $this->errors = $ecmfile->errors;
1076 } elseif (empty($ecmfile->share)) {
1077 // Add entry into index
1078 if ($initsharekey) {
1079 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1080 $ecmfile->share = getRandomPassword(true);
1081 $ecmfile->update($user);
1086 // Define $urlwithroot
1087 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1088 // This is to use external domain name found into config file
1089 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1091 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1092 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1097 //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1098 //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1099 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1100 if (!empty($ecmfile->share)) {
1101 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1103 if ($forcedownload) {
1104 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1107 if ($relativelink) {
1108 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1110 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1113 // Here $ecmfile->share is defined
1114 return $linktoreturn;
1118 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1128 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1131 global $user, $langs;
1134 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger
");
1137 if ($fk_socpeople <= 0) {
1138 $langs->load("errors
");
1139 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "1
");
1140 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1143 if (!$type_contact) {
1144 $langs->load("errors
");
1145 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "2
");
1146 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1150 $id_type_contact = 0;
1151 if (is_numeric($type_contact)) {
1152 $id_type_contact = $type_contact;
1154 // We look for id type_contact
1155 $sql = "SELECT tc.rowid
";
1156 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1157 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1158 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1159 $sql .= " AND tc.code=
'".$this->db->escape($type_contact)."' AND tc.active=1
";
1161 $resql = $this->db->query($sql);
1163 $obj = $this->db->fetch_object($resql);
1165 $id_type_contact = $obj->rowid;
1170 if ($id_type_contact == 0) {
1171 dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code
type of contact
'".$type_contact."' does not exists or is not active
for element
".$this->element.", we can ignore it
");
1175 $datecreate = dol_now();
1177 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1178 $TListeContacts = $this->liste_contact(-1, $source);
1179 $already_added = false;
1180 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1181 foreach ($TListeContacts as $array_contact) {
1182 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1183 $already_added = true;
1189 if (!$already_added) {
1192 // Insert into database
1193 $sql = "INSERT INTO
".$this->db->prefix()."element_contact
";
1194 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact)
";
1195 $sql .= " VALUES (
".$this->id.",
".((int) $fk_socpeople)." ,
";
1196 $sql .= "'".$this->db->idate($datecreate)."'";
1197 $sql .= ", 4,
".((int) $id_type_contact);
1200 $resql = $this->db->query($sql);
1203 $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1205 $this->db->rollback();
1210 $this->db->commit();
1213 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1214 $this->error = $this->db->errno();
1215 $this->db->rollback();
1218 $this->error = $this->db->lasterror();
1219 $this->db->rollback();
1228 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1236 public function copy_linked_contact($objFrom, $source = 'internal')
1239 $contacts = $objFrom->liste_contact(-1, $source);
1240 foreach ($contacts as $contact) {
1241 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1248 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1258 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1261 // Insert into database
1262 $sql = "UPDATE
".$this->db->prefix()."element_contact
set";
1263 $sql .= " statut =
".$statut;
1264 if ($type_contact_id) {
1265 $sql .= ", fk_c_type_contact =
".((int) $type_contact_id);
1267 if ($fk_socpeople) {
1268 $sql .= ", fk_socpeople =
".((int) $fk_socpeople);
1270 $sql .= " where
rowid =
".((int) $rowid);
1271 $resql = $this->db->query($sql);
1275 $this->error = $this->db->lasterror();
1280 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1288 public function delete_contact($rowid, $notrigger = 0)
1296 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1297 $sql .= " WHERE
rowid =
".((int) $rowid);
1300 if ($this->db->query($sql)) {
1302 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1304 $this->db->rollback();
1309 $this->db->commit();
1312 $this->error = $this->db->lasterror();
1313 $this->db->rollback();
1318 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1326 public function delete_linked_contact($source = '', $code = '')
1331 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1333 if (!empty($typeContact)) {
1334 foreach ($typeContact as $key => $value) {
1335 array_push($temp, $key);
1337 $listId = implode(",
", $temp);
1340 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1341 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1342 if (empty($listId)) {
1346 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1347 $sql .= " WHERE element_id =
".((int) $this->id);
1348 $sql .= " AND fk_c_type_contact IN (
".$this->db->sanitize($listId).")
";
1351 if ($this->db->query($sql)) {
1354 $this->error = $this->db->lasterror();
1359 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1371 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1378 $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
1379 if ($source == 'internal') {
1380 $sql .= ",
'-1' as socid, t.statut as statuscontact, t.login, t.photo
";
1382 if ($source == 'external' || $source == 'thirdparty') {
1383 $sql .= ", t.fk_soc as socid, t.statut as statuscontact
";
1385 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email
";
1386 $sql .= ", tc.source, tc.element, tc.code, tc.libelle
";
1387 $sql .= " FROM
".$this->db->prefix()."c_type_contact tc
";
1388 $sql .= ",
".$this->db->prefix()."element_contact ec
";
1389 if ($source == 'internal') { // internal contact (user)
1390 $sql .= " LEFT JOIN
".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid
";
1392 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1393 $sql .= " LEFT JOIN
".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid
";
1395 $sql .= " WHERE ec.element_id =
".((int) $this->id);
1396 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1397 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1399 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1401 if ($source == 'internal') {
1402 $sql .= " AND tc.source =
'internal'";
1404 $sql .= " AND t.statut =
".((int) $status);
1407 if ($source == 'external' || $source == 'thirdparty') {
1408 $sql .= " AND tc.source =
'external'";
1410 $sql .= " AND t.statut =
".((int) $status); // t is llx_socpeople
1413 $sql .= " AND tc.active = 1
";
1414 if ($statusoflink >= 0) {
1415 $sql .= " AND ec.statut =
".((int) $statusoflink);
1417 $sql .= " ORDER BY t.lastname ASC
";
1420 $resql = $this->db->query($sql);
1422 $num = $this->db->num_rows($resql);
1425 $obj = $this->db->fetch_object($resql);
1428 $transkey = "TypeContact_
".$obj->element."_
".$obj->source."_
".$obj->code;
1429 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1431 'source' => $obj->source,
1432 'socid' => $obj->socid,
1434 'nom' => $obj->lastname, // For backward compatibility
1435 'civility' => $obj->civility,
1436 'lastname' => $obj->lastname,
1437 'firstname' => $obj->firstname,
1438 'email'=>$obj->email,
1439 'login'=> (empty($obj->login) ? '' : $obj->login),
1440 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1441 'statuscontact' => $obj->statuscontact,
1442 'rowid' => $obj->rowid,
1443 'code' => $obj->code,
1444 'libelle' => $libelle_type,
1445 'status' => $obj->statuslink,
1446 'fk_c_type_contact' => $obj->fk_c_type_contact
1449 $tab[$i] = $obj->id;
1457 $this->error = $this->db->lasterror();
1458 dol_print_error($this->db);
1470 public function swapContactStatus($rowid)
1472 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,
";
1473 $sql .= " tc.code, tc.libelle
";
1474 $sql .= " FROM (
".$this->db->prefix()."element_contact as ec,
".$this->db->prefix()."c_type_contact as tc)
";
1475 $sql .= " WHERE ec.rowid =
".((int) $rowid);
1476 $sql .= " AND ec.fk_c_type_contact=tc.rowid
";
1477 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1480 $resql = $this->db->query($sql);
1482 $obj = $this->db->fetch_object($resql);
1483 $newstatut = ($obj->statut == 4) ? 5 : 4;
1484 $result = $this->update_contact($rowid, $newstatut);
1485 $this->db->free($resql);
1488 $this->error = $this->db->error();
1489 dol_print_error($this->db);
1494 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1505 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1510 if (empty($order)) {
1511 $order = 'position';
1513 if ($order == 'position') {
1518 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position
";
1519 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1520 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1521 if ($activeonly == 1) {
1522 $sql .= " AND tc.active=1
"; // only the active types
1524 if (!empty($source) && $source != 'all') {
1525 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1527 if (!empty($code)) {
1528 $sql .= " AND tc.code=
'".$this->db->escape($code)."'";
1530 $sql .= $this->db->order($order, 'ASC');
1532 //print "sql=
".$sql;
1533 $resql = $this->db->query($sql);
1535 $num = $this->db->num_rows($resql);
1538 $obj = $this->db->fetch_object($resql);
1540 $transkey = "TypeContact_
".$this->element."_
".$source."_
".$obj->code;
1541 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1542 if (empty($option)) {
1543 $tab[$obj->rowid] = $libelle_type;
1545 $tab[$obj->code] = $libelle_type;
1551 $this->error = $this->db->lasterror();
1552 //dol_print_error($this->db);
1568 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1570 global $langs, $conf;
1572 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1576 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element
";
1577 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1579 $sqlWhere = array();
1580 if (!empty($element)) {
1581 $sqlWhere[] = " tc.element=
'".$this->db->escape($element)."'";
1583 if (!empty($excludeelement)) {
1584 $sqlWhere[] = " tc.element <>
'".$this->db->escape($excludeelement)."'";
1587 if ($activeonly == 1) {
1588 $sqlWhere[] = " tc.active=1
"; // only the active types
1591 if (!empty($source) && $source != 'all') {
1592 $sqlWhere[] = " tc.source=
'".$this->db->escape($source)."'";
1595 if (!empty($code)) {
1596 $sqlWhere[] = " tc.code=
'".$this->db->escape($code)."'";
1599 if (count($sqlWhere) > 0) {
1600 $sql .= " WHERE
".implode(' AND ', $sqlWhere);
1603 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1605 dol_syslog(__METHOD__, LOG_DEBUG);
1606 $resql = $this->db->query($sql);
1608 $num = $this->db->num_rows($resql);
1610 $langs->loadLangs(array("propal
", "orders
", "bills
", "suppliers
", "contracts
", "supplier_proposal
"));
1612 while ($obj = $this->db->fetch_object($resql)) {
1613 $modulename = $obj->element;
1614 if (strpos($obj->element, 'project') !== false) {
1615 $modulename = 'projet';
1616 } elseif ($obj->element == 'contrat') {
1617 $element = 'contract';
1618 } elseif ($obj->element == 'action') {
1619 $modulename = 'agenda';
1620 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1621 $modulename = 'fournisseur';
1622 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1623 $modulename = 'fournisseur';
1625 if (!empty($conf->{$modulename}->enabled)) {
1626 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1627 $tmpelement = $obj->element;
1628 $transkey = "TypeContact_
".$tmpelement."_
".$source."_
".$obj->code;
1629 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1630 if (empty($option)) {
1631 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1633 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1640 $this->error = $this->db->lasterror();
1656 public function getIdContact($source, $code, $status = 0)
1662 //cas particulier pour les expeditions
1663 if ($this->element == 'shipping' && $this->origin_id != 0) {
1664 $id = $this->origin_id;
1665 $element = 'commande';
1666 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1667 $id = $this->origin_id;
1668 $element = 'order_supplier';
1671 $element = $this->element;
1674 $sql = "SELECT ec.fk_socpeople
";
1675 $sql .= " FROM
".$this->db->prefix()."element_contact as ec,
";
1676 if ($source == 'internal') {
1677 $sql .= " ".$this->db->prefix()."user as c,
";
1679 if ($source == 'external') {
1680 $sql .= " ".$this->db->prefix()."socpeople as c,
";
1682 $sql .= " ".$this->db->prefix()."c_type_contact as tc
";
1683 $sql .= " WHERE ec.element_id =
".((int) $id);
1684 $sql .= " AND ec.fk_socpeople = c.rowid
";
1685 if ($source == 'internal') {
1686 $sql .= " AND c.entity IN (
".getEntity('user').")
";
1688 if ($source == 'external') {
1689 $sql .= " AND c.entity IN (
".getEntity('societe').")
";
1691 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1692 $sql .= " AND tc.element =
'".$this->db->escape($element)."'";
1693 $sql .= " AND tc.source =
'".$this->db->escape($source)."'";
1695 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1697 $sql .= " AND tc.active = 1
";
1699 $sql .= " AND ec.statut =
".((int) $status);
1703 $resql = $this->db->query($sql);
1705 while ($obj = $this->db->fetch_object($resql)) {
1706 $result[$i] = $obj->fk_socpeople;
1710 $this->error = $this->db->error();
1717 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1724 public function fetch_contact($contactid = null)
1727 if (empty($contactid)) {
1728 $contactid = $this->contact_id;
1731 if (empty($contactid)) {
1735 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1736 $contact = new Contact($this->db);
1737 $result = $contact->fetch($contactid);
1738 $this->contact = $contact;
1742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1749 public function fetch_thirdparty($force_thirdparty_id = 0)
1754 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1758 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1760 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1761 if ($force_thirdparty_id) {
1762 $idtofetch = $force_thirdparty_id;
1766 $thirdparty = new Societe($this->db);
1767 $result = $thirdparty->fetch($idtofetch);
1769 $this->errors=array_merge($this->errors, $thirdparty->errors);
1771 $this->thirdparty = $thirdparty;
1773 // Use first price level if level not defined for third party
1774 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1775 $this->thirdparty->price_level = 1;
1792 public function fetchOneLike($ref)
1794 if (!$this->table_ref_field) {
1798 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element." WHERE
".$this->table_ref_field." LIKE
'".$this->db->escape($ref)."' LIMIT 1
";
1800 $query = $this->db->query($sql);
1802 if (!$this->db->num_rows($query)) {
1806 $result = $this->db->fetch_object($query);
1808 return $this->fetch($result->rowid);
1811 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1819 public function fetch_barcode()
1824 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1826 $idtype = $this->barcode_type;
1827 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
1828 if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1829 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1830 } elseif ($this->element == 'societe') {
1831 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1833 dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1838 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
1839 $sql = "SELECT
rowid,
code, libelle as label, coder
";
1840 $sql .= " FROM
".$this->db->prefix()."c_barcode_type
";
1841 $sql .= " WHERE
rowid =
".((int) $idtype);
1842 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1843 $resql = $this->db->query($sql);
1845 $obj = $this->db->fetch_object($resql);
1846 $this->barcode_type = $obj->rowid;
1847 $this->barcode_type_code = $obj->code;
1848 $this->barcode_type_label = $obj->label;
1849 $this->barcode_type_coder = $obj->coder;
1852 dol_print_error($this->db);
1860 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1866 public function fetch_project()
1869 return $this->fetch_projet();
1872 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1878 public function fetch_projet()
1881 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1883 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1884 $this->fk_project = $this->fk_projet; // For backward compatibility
1886 if (empty($this->fk_project)) {
1890 $project = new Project($this->db);
1891 $result = $project->fetch($this->fk_project);
1893 $this->projet = $project; // deprecated
1894 $this->project = $project;
1898 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1904 public function fetch_product()
1907 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1909 if (empty($this->fk_product)) {
1913 $product = new Product($this->db);
1914 $result = $product->fetch($this->fk_product);
1916 $this->product = $product;
1920 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1927 public function fetch_user($userid)
1930 $user = new User($this->db);
1931 $result = $user->fetch($userid);
1932 $this->user = $user;
1936 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1942 public function fetch_origin()
1945 if ($this->origin == 'shipping') {
1946 $this->origin = 'expedition';
1948 if ($this->origin == 'delivery') {
1949 $this->origin = 'livraison';
1951 if ($this->origin == 'order_supplier') {
1952 $this->origin = 'commandeFournisseur';
1955 $origin = $this->origin;
1957 $classname = ucfirst($origin);
1958 $this->$origin = new $classname($this->db);
1959 $this->$origin->fetch($this->origin_id);
1971 public function fetchObjectFrom($table, $field, $key, $element = null)
1977 $sql = "SELECT
rowid FROM
".$this->db->prefix().$table;
1978 $sql .= " WHERE
".$field." =
'".$this->db->escape($key)."'";
1979 if (!empty($element)) {
1980 $sql .= " AND entity IN (
".getEntity($element).")
";
1982 $sql .= " AND entity =
".((int) $conf->entity);
1985 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1986 $resql = $this->db->query($sql);
1988 $row = $this->db->fetch_row($resql);
1989 // Test for avoid error -1
1991 $result = $this->fetch($row[0]);
2006 public function getValueFrom($table, $id, $field)
2009 if (!empty($id) && !empty($field) && !empty($table)) {
2010 $sql = "SELECT
".$field." FROM
".$this->db->prefix().$table;
2011 $sql .= " WHERE
rowid =
".((int) $id);
2013 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2014 $resql = $this->db->query($sql);
2016 $row = $this->db->fetch_row($resql);
2039 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2041 global $user, $langs, $conf;
2043 if (empty($table)) {
2044 $table = $this->table_element;
2049 if (empty($format)) {
2052 if (empty($id_field)) {
2053 $id_field = 'rowid';
2061 if ($table == 'product' && $field == 'note_private') {
2064 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2065 $fk_user_field = 'fk_user_mod';
2068 $sql = "UPDATE
".$this->db->prefix().$table." SET
";
2070 if ($format == 'text') {
2071 $sql .= $field." =
'".$this->db->escape($value)."'";
2072 } elseif ($format == 'int') {
2073 $sql .= $field." =
".((int) $value);
2074 } elseif ($format == 'date') {
2075 $sql .= $field." =
".($value ? "'".$this->db->idate($value)."'" : "null");
2078 if ($fk_user_field) {
2079 if (!empty($fuser) && is_object($fuser)) {
2080 $sql .= ",
".$fk_user_field." =
".((int) $fuser->id);
2081 } elseif (empty($fuser) || $fuser != 'none') {
2082 $sql .= ",
".$fk_user_field." =
".((int) $user->id);
2086 $sql .= " WHERE
".$id_field." =
".((int) $id);
2088 dol_syslog(__METHOD__."", LOG_DEBUG);
2089 $resql = $this->db->query($sql);
2092 // call trigger with updated object values
2093 if (method_exists($this, 'fetch')) {
2094 $result = $this->fetch($id);
2096 $result = $this->fetchCommon($id);
2099 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2107 if (property_exists($this, $field)) {
2108 $this->$field = $value;
2110 $this->db->commit();
2113 $this->db->rollback();
2117 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2118 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2120 $this->error = $this->db->lasterror();
2122 $this->db->rollback();
2127 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2136 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2139 global $conf, $user;
2141 if (!$this->table_element) {
2142 dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with
property table_element not defined
");
2145 if ($fieldid == 'none') {
2149 // For backward compatibility
2150 if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2154 // Security on socid
2156 if ($user->socid > 0) {
2157 $socid = $user->socid;
2160 // this->ismultientitymanaged contains
2161 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2162 $aliastablesociete = 's';
2163 if ($this->element == 'societe') {
2164 $aliastablesociete = 'te'; // te as table_element
2166 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2167 $sql = "SELECT MAX(te.
".$fieldid.")
";
2168 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2169 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2170 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2172 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2173 $tmparray = explode('@', $this->ismultientitymanaged);
2174 $sql .= ",
".$this->db->prefix().$tmparray[1]." as
".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2175 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2176 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2177 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2178 $sql .= " LEFT JOIN
".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid
"; // If we need to link to societe to limit select to socid
2180 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2181 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2183 $sql .= " WHERE te.
".$fieldid." <
'".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2184 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2185 $sql .= " AND sc.fk_user =
".((int) $user->id);
2187 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2188 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2190 if (!empty($filter)) {
2191 if (!preg_match('/^\s*AND/i', $filter)) {
2192 $sql .= " AND
"; // For backward compatibility
2196 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2197 $tmparray = explode('@', $this->ismultientitymanaged);
2198 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2199 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2200 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2202 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2203 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2204 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2205 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2207 $sql .= " AND ug.fk_user = te.rowid
";
2208 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2211 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2214 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2215 $tmparray = explode('@', $this->ismultientitymanaged);
2216 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2218 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2219 $sql .= ' AND te.fk_soc = '.((int) $socid);
2221 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2222 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2224 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2225 $sql .= ' AND te.rowid = '.((int) $socid);
2227 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2229 $result = $this->db->query($sql);
2231 $this->error = $this->db->lasterror();
2234 $row = $this->db->fetch_row($result);
2235 $this->ref_previous = $row[0];
2237 $sql = "SELECT MIN(te.
".$fieldid.")
";
2238 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2239 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2240 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2242 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2243 $tmparray = explode('@', $this->ismultientitymanaged);
2244 $sql .= ",
".$this->db->prefix().$tmparray[1]." as
".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2245 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2246 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2247 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2248 $sql .= " LEFT JOIN
".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid
"; // If we need to link to societe to limit select to socid
2250 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2251 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2253 $sql .= " WHERE te.
".$fieldid." >
'".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2254 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2255 $sql .= " AND sc.fk_user =
".((int) $user->id);
2257 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2258 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2260 if (!empty($filter)) {
2261 if (!preg_match('/^\s*AND/i', $filter)) {
2262 $sql .= " AND
"; // For backward compatibility
2266 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2267 $tmparray = explode('@', $this->ismultientitymanaged);
2268 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2269 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2270 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2272 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2273 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2274 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2275 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2277 $sql .= " AND ug.fk_user = te.rowid
";
2278 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2281 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2284 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2285 $tmparray = explode('@', $this->ismultientitymanaged);
2286 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2288 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2289 $sql .= ' AND te.fk_soc = '.((int) $socid);
2291 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2292 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2294 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2295 $sql .= ' AND te.rowid = '.((int) $socid);
2297 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2298 // 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
2300 $result = $this->db->query($sql);
2302 $this->error = $this->db->lasterror();
2305 $row = $this->db->fetch_row($result);
2306 $this->ref_next = $row[0];
2319 public function getListContactId($source = 'external')
2321 $contactAlreadySelected = array();
2322 $tab = $this->liste_contact(-1, $source);
2326 if ($source == 'thirdparty') {
2327 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2329 $contactAlreadySelected[$i] = $tab[$i]['id'];
2333 return $contactAlreadySelected;
2344 public function setProject($projectid, $notrigger = 0)
2349 if (!$this->table_element) {
2350 dol_syslog(get_class($this)."::
setProject was called on objet with property table_element not defined
", LOG_ERR);
2354 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2355 if (!empty($this->fields['fk_project'])) { // Common case
2357 $sql .= " SET fk_project =
".((int) $projectid);
2359 $sql .= " SET fk_project = NULL
";
2361 $sql .= ' WHERE rowid = '.((int) $this->id);
2362 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2364 $sql .= " SET fk_project =
".((int) $projectid);
2366 $sql .= " SET fk_project = NULL
";
2368 $sql .= ' WHERE id = '.((int) $this->id);
2369 } else // Special case for old architecture objects
2372 $sql .= ' SET fk_projet = '.((int) $projectid);
2374 $sql .= ' SET fk_projet = NULL';
2376 $sql .= " WHERE
rowid =
".((int) $this->id);
2381 dol_syslog(get_class($this)."::
setProject", LOG_DEBUG);
2382 if ($this->db->query($sql)) {
2383 $this->fk_project = ((int) $projectid);
2385 dol_print_error($this->db);
2390 if (!$error && !$notrigger) {
2392 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2395 } //Do also here what you must do to rollback action if trigger fail
2396 // End call triggers
2399 // Commit or rollback
2401 $this->db->rollback();
2404 $this->db->commit();
2415 public function setPaymentMethods($id)
2419 $error = 0; $notrigger = 0;
2421 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2423 if ($this->statut >= 0 || $this->element == 'societe') {
2424 // TODO uniformize field name
2425 $fieldname = 'fk_mode_reglement';
2426 if ($this->element == 'societe') {
2427 $fieldname = 'mode_reglement';
2429 if (get_class($this) == 'Fournisseur') {
2430 $fieldname = 'mode_reglement_supplier';
2432 if (get_class($this) == 'Tva') {
2433 $fieldname = 'fk_typepayment';
2435 if (get_class($this) == 'Salary') {
2436 $fieldname = 'fk_typepayment';
2439 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2440 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2441 $sql .= ' WHERE rowid='.((int) $this->id);
2443 if ($this->db->query($sql)) {
2444 $this->mode_reglement_id = $id;
2446 if (get_class($this) == 'Fournisseur') {
2447 $this->mode_reglement_supplier_id = $id;
2450 if (!$error && !$notrigger) {
2452 if (get_class($this) == 'Commande') {
2453 $result = $this->call_trigger('ORDER_MODIFY', $user);
2455 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2460 // End call triggers
2464 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2465 $this->error = $this->db->error();
2469 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2470 $this->error = 'Status of the object is incompatible '.$this->statut;
2481 public function setMulticurrencyCode($code)
2483 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2484 if ($this->statut >= 0 || $this->element == 'societe') {
2485 $fieldname = 'multicurrency_code';
2487 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2488 $sql .= " SET
".$fieldname." =
'".$this->db->escape($code)."'";
2489 $sql .= ' WHERE rowid='.((int) $this->id);
2491 if ($this->db->query($sql)) {
2492 $this->multicurrency_code = $code;
2494 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2496 $this->setMulticurrencyRate($rate, 2);
2501 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2502 $this->error = $this->db->error();
2506 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2507 $this->error = 'Status of the object is incompatible '.$this->statut;
2519 public function setMulticurrencyRate($rate, $mode = 1)
2521 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2522 if ($this->statut >= 0 || $this->element == 'societe') {
2523 $fieldname = 'multicurrency_tx';
2525 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2526 $sql .= " SET
".$fieldname." =
".((float) $rate);
2527 $sql .= ' WHERE rowid='.((int) $this->id);
2529 if ($this->db->query($sql)) {
2530 $this->multicurrency_tx = $rate;
2532 // Update line price
2533 if (!empty($this->lines)) {
2534 foreach ($this->lines as &$line) {
2535 // Amounts in company currency will be recalculated
2537 $line->subprice = 0;
2540 // Amounts in foreign currency will be recalculated
2542 $line->multicurrency_subprice = 0;
2545 switch ($this->element) {
2551 $line->remise_percent,
2553 $line->localtax1_tx,
2554 $line->localtax2_tx,
2555 ($line->description ? $line->description : $line->desc),
2558 $line->special_code,
2559 $line->fk_parent_line,
2560 $line->skip_update_total,
2561 $line->fk_fournprice,
2564 $line->product_type,
2567 $line->array_options,
2569 $line->multicurrency_subprice
2575 ($line->description ? $line->description : $line->desc),
2578 $line->remise_percent,
2580 $line->localtax1_tx,
2581 $line->localtax2_tx,
2586 $line->product_type,
2587 $line->fk_parent_line,
2588 $line->skip_update_total,
2589 $line->fk_fournprice,
2592 $line->special_code,
2593 $line->array_options,
2595 $line->multicurrency_subprice
2601 ($line->description ? $line->description : $line->desc),
2604 $line->remise_percent,
2608 $line->localtax1_tx,
2609 $line->localtax2_tx,
2612 $line->product_type,
2613 $line->fk_parent_line,
2614 $line->skip_update_total,
2615 $line->fk_fournprice,
2618 $line->special_code,
2619 $line->array_options,
2620 $line->situation_percent,
2622 $line->multicurrency_subprice
2625 case 'supplier_proposal':
2630 $line->remise_percent,
2632 $line->localtax1_tx,
2633 $line->localtax2_tx,
2634 ($line->description ? $line->description : $line->desc),
2637 $line->special_code,
2638 $line->fk_parent_line,
2639 $line->skip_update_total,
2640 $line->fk_fournprice,
2643 $line->product_type,
2644 $line->array_options,
2646 $line->multicurrency_subprice
2649 case 'order_supplier':
2652 ($line->description ? $line->description : $line->desc),
2655 $line->remise_percent,
2657 $line->localtax1_tx,
2658 $line->localtax2_tx,
2661 $line->product_type,
2665 $line->array_options,
2667 $line->multicurrency_subprice,
2671 case 'invoice_supplier':
2674 ($line->description ? $line->description : $line->desc),
2677 $line->localtax1_tx,
2678 $line->localtax2_tx,
2683 $line->product_type,
2684 $line->remise_percent,
2688 $line->array_options,
2690 $line->multicurrency_subprice,
2695 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2703 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2704 $this->error = $this->db->error();
2708 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2709 $this->error = 'Status of the object is incompatible '.$this->statut;
2721 public function setPaymentTerms($id, $deposit_percent = null)
2723 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2724 if ($this->statut >= 0 || $this->element == 'societe') {
2725 // TODO uniformize field name
2726 $fieldname = 'fk_cond_reglement';
2727 if ($this->element == 'societe') {
2728 $fieldname = 'cond_reglement';
2730 if (get_class($this) == 'Fournisseur') {
2731 $fieldname = 'cond_reglement_supplier';
2734 if (empty($deposit_percent) || $deposit_percent < 0) {
2735 $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2738 if ($deposit_percent > 100) {
2739 $deposit_percent = 100;
2742 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2743 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2744 if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
2745 $sql .= " , deposit_percent =
" . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2747 $sql .= ' WHERE rowid='.((int) $this->id);
2749 if ($this->db->query($sql)) {
2750 $this->cond_reglement_id = $id;
2752 if (get_class($this) == 'Fournisseur') {
2753 $this->cond_reglement_supplier_id = $id;
2755 $this->cond_reglement = $id; // for compatibility
2756 $this->deposit_percent = $deposit_percent;
2759 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2760 $this->error = $this->db->error();
2764 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2765 $this->error = 'Status of the object is incompatible '.$this->statut;
2776 public function setTransportMode($id)
2778 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2779 if ($this->statut >= 0 || $this->element == 'societe') {
2780 $fieldname = 'fk_transport_mode';
2781 if ($this->element == 'societe') {
2782 $fieldname = 'transport_mode';
2784 if (get_class($this) == 'Fournisseur') {
2785 $fieldname = 'transport_mode_supplier';
2788 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2789 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2790 $sql .= ' WHERE rowid='.((int) $this->id);
2792 if ($this->db->query($sql)) {
2793 $this->transport_mode_id = $id;
2795 if (get_class($this) == 'Fournisseur') {
2796 $this->transport_mode_supplier_id = $id;
2800 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2801 $this->error = $this->db->error();
2805 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2806 $this->error = 'Status of the object is incompatible '.$this->statut;
2817 public function setRetainedWarrantyPaymentTerms($id)
2819 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2820 if ($this->statut >= 0 || $this->element == 'societe') {
2821 $fieldname = 'retained_warranty_fk_cond_reglement';
2823 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2824 $sql .= " SET
".$fieldname." =
".((int) $id);
2825 $sql .= ' WHERE rowid='.((int) $this->id);
2827 if ($this->db->query($sql)) {
2828 $this->retained_warranty_fk_cond_reglement = $id;
2831 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2832 $this->error = $this->db->error();
2836 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2837 $this->error = 'Status of the object is incompatible '.$this->statut;
2849 public function setDeliveryAddress($id)
2851 $fieldname = 'fk_delivery_address';
2852 if ($this->element == 'delivery' || $this->element == 'shipping') {
2853 $fieldname = 'fk_address';
2856 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET
".$fieldname." =
".((int) $id);
2857 $sql .= " WHERE
rowid =
".((int) $this->id)." AND fk_statut = 0
";
2859 if ($this->db->query($sql)) {
2860 $this->fk_delivery_address = $id;
2863 $this->error = $this->db->error();
2864 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2879 public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2883 if (empty($userused)) {
2889 if (!$this->table_element) {
2890 dol_syslog(get_class($this)."::
setShippingMethod was called on objet with property table_element not defined
", LOG_ERR);
2896 if ($shipping_method_id < 0) {
2897 $shipping_method_id = 'NULL';
2899 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2901 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2902 $sql .= " SET fk_shipping_method =
".((int) $shipping_method_id);
2903 $sql .= " WHERE
rowid=
".((int) $this->id);
2904 $resql = $this->db->query($sql);
2906 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2907 $this->error = $this->db->lasterror();
2912 $this->context = array('shippingmethodupdate'=>1);
2913 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2921 $this->db->rollback();
2924 $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2925 $this->db->commit();
2937 public function setWarehouse($warehouse_id)
2939 if (!$this->table_element) {
2940 dol_syslog(get_class($this)."::
setWarehouse was called on objet with property table_element not defined
", LOG_ERR);
2943 if ($warehouse_id < 0) {
2944 $warehouse_id = 'NULL';
2946 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2948 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2949 $sql .= " SET fk_warehouse =
".((int) $warehouse_id);
2950 $sql .= " WHERE
rowid=
".((int) $this->id);
2952 if ($this->db->query($sql)) {
2953 $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2956 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2957 $this->error = $this->db->error();
2970 public function setDocModel($user, $modelpdf)
2972 if (!$this->table_element) {
2973 dol_syslog(get_class($this)."::
setDocModel was called on objet with property table_element not defined
", LOG_ERR);
2977 $newmodelpdf = dol_trunc($modelpdf, 255);
2979 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2980 $sql .= " SET model_pdf =
'".$this->db->escape($newmodelpdf)."'";
2981 $sql .= " WHERE
rowid =
".((int) $this->id);
2983 dol_syslog(get_class($this)."::
setDocModel", LOG_DEBUG);
2984 $resql = $this->db->query($sql);
2986 $this->model_pdf = $modelpdf;
2987 $this->modelpdf = $modelpdf; // For bakward compatibility
2990 dol_print_error($this->db);
3004 public function setBankAccount($fk_account, $notrigger = false, $userused = null)
3008 if (empty($userused)) {
3014 if (!$this->table_element) {
3015 dol_syslog(get_class($this)."::
setBankAccount was called on objet with property table_element not defined
", LOG_ERR);
3020 if ($fk_account < 0) {
3021 $fk_account = 'NULL';
3023 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3025 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3026 $sql .= " SET fk_account =
".((int) $fk_account);
3027 $sql .= " WHERE
rowid=
".((int) $this->id);
3029 $resql = $this->db->query($sql);
3031 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3032 $this->error = $this->db->lasterror();
3037 $this->context = array('bankaccountupdate'=>1);
3038 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3046 $this->db->rollback();
3049 $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3050 $this->db->commit();
3056 // TODO: Move line related operations to CommonObjectLine?
3058 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3068 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3071 if (!$this->table_element_line) {
3072 dol_syslog(get_class($this)."::
line_order was called on objet with property table_element_line not defined
", LOG_ERR);
3075 if (!$this->fk_element) {
3076 dol_syslog(get_class($this)."::
line_order was called on objet with property fk_element not defined
", LOG_ERR);
3080 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3081 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3082 $fieldposition = 'position';
3085 // Count number of lines to reorder (according to choice $renum)
3087 $sql = "SELECT count(
rowid) FROM
".$this->db->prefix().$this->table_element_line;
3088 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3090 $sql .= " AND
" . $fieldposition . " = 0
";
3093 $sql .= " AND
" . $fieldposition . " <> 0
";
3096 dol_syslog(get_class($this)."::
line_order", LOG_DEBUG);
3097 $resql = $this->db->query($sql);
3099 $row = $this->db->fetch_row($resql);
3102 dol_print_error($this->db);
3105 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3108 // We first search all lines that are parent lines (for multilevel details lines)
3109 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3110 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3111 if ($fk_parent_line) {
3112 $sql .= ' AND fk_parent_line IS NULL';
3114 $sql .= " ORDER BY
" . $fieldposition . " ASC,
rowid " . $rowidorder;
3116 dol_syslog(get_class($this)."::
line_order search all parent lines
", LOG_DEBUG);
3117 $resql = $this->db->query($sql);
3120 $num = $this->db->num_rows($resql);
3122 $row = $this->db->fetch_row($resql);
3123 $rows[] = $row[0]; // Add parent line into array rows
3124 $childrens = $this->getChildrenOfLine($row[0]);
3125 if (!empty($childrens)) {
3126 foreach ($childrens as $child) {
3127 array_push($rows, $child);
3133 // Now we set a new number for each lines (parent and children with children included into parent tree)
3134 if (!empty($rows)) {
3135 foreach ($rows as $key => $row) {
3136 $this->updateRangOfLine($row, ($key + 1));
3140 dol_print_error($this->db);
3153 public function getChildrenOfLine($id, $includealltree = 0)
3155 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3156 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3157 $fieldposition = 'position';
3162 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3163 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3164 $sql .= ' AND fk_parent_line = '.((int) $id);
3165 $sql .= " ORDER BY
" . $fieldposition . " ASC
";
3167 dol_syslog(get_class($this)."::
getChildrenOfLine search children lines
for line
".$id, LOG_DEBUG);
3168 $resql = $this->db->query($sql);
3170 if ($this->db->num_rows($resql) > 0) {
3171 while ($row = $this->db->fetch_row($resql)) {
3173 if (!empty($includealltree)) {
3174 $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3182 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3190 public function line_up($rowid, $fk_parent_line = true)
3193 $this->line_order(false, 'ASC', $fk_parent_line);
3196 $rang = $this->getRangOfLine($rowid);
3198 // Update position of line
3199 $this->updateLineUp($rowid, $rang);
3202 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3210 public function line_down($rowid, $fk_parent_line = true)
3213 $this->line_order(false, 'ASC', $fk_parent_line);
3216 $rang = $this->getRangOfLine($rowid);
3218 // Get max value for rang
3219 $max = $this->line_max();
3221 // Update position of line
3222 $this->updateLineDown($rowid, $rang, $max);
3232 public function updateRangOfLine($rowid, $rang)
3234 global $hookmanager;
3235 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3236 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3237 $fieldposition = 'position';
3240 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3241 $sql .= ' WHERE rowid = '.((int) $rowid);
3244 if (!$this->db->query($sql)) {
3245 dol_print_error($this->db);
3248 $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3250 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3255 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3262 public function line_ajaxorder($rows)
3265 $num = count($rows);
3266 for ($i = 0; $i < $num; $i++) {
3267 $this->updateRangOfLine($rows[$i], ($i + 1));
3278 public function updateLineUp($rowid, $rang)
3281 $fieldposition = 'rang';
3282 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3283 $fieldposition = 'position';
3286 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3287 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3288 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang - 1));
3289 if ($this->db->query($sql)) {
3290 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang - 1));
3291 $sql .= ' WHERE rowid = '.((int) $rowid);
3292 if (!$this->db->query($sql)) {
3293 dol_print_error($this->db);
3296 dol_print_error($this->db);
3309 public function updateLineDown($rowid, $rang, $max)
3312 $fieldposition = 'rang';
3313 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3314 $fieldposition = 'position';
3317 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3318 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3319 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang + 1));
3320 if ($this->db->query($sql)) {
3321 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang + 1));
3322 $sql .= ' WHERE rowid = '.((int) $rowid);
3323 if (!$this->db->query($sql)) {
3324 dol_print_error($this->db);
3327 dol_print_error($this->db);
3338 public function getRangOfLine($rowid)
3340 $fieldposition = 'rang';
3341 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3342 $fieldposition = 'position';
3345 $sql = "SELECT
" . $fieldposition . " FROM
".$this->db->prefix().$this->table_element_line;
3346 $sql .= " WHERE
rowid =
".((int) $rowid);
3349 $resql = $this->db->query($sql);
3351 $row = $this->db->fetch_row($resql);
3362 public function getIdOfLine($rang)
3364 $fieldposition = 'rang';
3365 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3366 $fieldposition = 'position';
3369 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3370 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3371 $sql .= " AND
" . $fieldposition . " =
".((int) $rang);
3372 $resql = $this->db->query($sql);
3374 $row = $this->db->fetch_row($resql);
3379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3386 public function line_max($fk_parent_line = 0)
3389 $positionfield = 'rang';
3390 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3391 $positionfield = 'position';
3394 // Search the last rang with fk_parent_line
3395 if ($fk_parent_line) {
3396 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3397 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3398 $sql .= " AND fk_parent_line =
".((int) $fk_parent_line);
3400 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3401 $resql = $this->db->query($sql);
3403 $row = $this->db->fetch_row($resql);
3404 if (!empty($row[0])) {
3407 return $this->getRangOfLine($fk_parent_line);
3411 // If not, search the last rang of element
3412 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3413 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3415 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3416 $resql = $this->db->query($sql);
3418 $row = $this->db->fetch_row($resql);
3424 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3431 public function update_ref_ext($ref_ext)
3434 if (!$this->table_element) {
3435 dol_syslog(get_class($this)."::
update_ref_ext was called on objet with property table_element not defined
", LOG_ERR);
3439 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3440 $sql .= " SET ref_ext =
'".$this->db->escape($ref_ext)."'";
3441 $sql .= " WHERE
".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." =
".((int) $this->id);
3444 if ($this->db->query($sql)) {
3445 $this->ref_ext = $ref_ext;
3448 $this->error = $this->db->error();
3453 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3461 public function update_note($note, $suffix = '')
3466 if (!$this->table_element) {
3467 $this->error = 'update_note was called on objet with property table_element not defined';
3468 dol_syslog(get_class($this)."::
update_note was called on objet with property table_element not defined
", LOG_ERR);
3471 if (!in_array($suffix, array('', '_public', '_private'))) {
3472 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3473 dol_syslog(get_class($this)."::
update_note Parameter suffix must be empty,
'_private' or
'_public'", LOG_ERR);
3477 $newsuffix = $suffix;
3480 if ($this->table_element == 'product' && $newsuffix == '_private') {
3483 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3484 $fieldusermod = "fk_user_mod
";
3485 } elseif ($this->table_element == 'ecm_files') {
3486 $fieldusermod = "fk_user_m
";
3488 $fieldusermod = "fk_user_modif
";
3490 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3491 $sql .= " SET note
".$newsuffix." =
".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL
");
3492 $sql .= ",
".$fieldusermod." =
".((int) $user->id);
3493 $sql .= " WHERE
rowid =
".((int) $this->id);
3495 dol_syslog(get_class($this)."::
update_note", LOG_DEBUG);
3496 if ($this->db->query($sql)) {
3497 if ($suffix == '_public') {
3498 $this->note_public = $note;
3499 } elseif ($suffix == '_private') {
3500 $this->note_private = $note;
3502 $this->note = $note; // deprecated
3503 $this->note_private = $note;
3507 $this->error = $this->db->lasterror();
3512 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3521 public function update_note_public($note)
3524 return $this->update_note($note, '_public');
3527 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3538 public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3541 global $conf, $hookmanager, $action;
3543 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3544 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3546 return 1; // replacement code
3547 } elseif ($reshook < 0) {
3548 return -1; // failure
3549 } // reshook = 0 => execute normal code
3551 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3553 if ($this->element == 'propal') {
3554 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL
";
3555 } elseif ($this->element == 'commande' || $this->element == 'order') {
3556 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER
";
3557 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3558 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE
";
3559 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3560 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE
";
3561 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3562 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER
";
3563 } elseif ($this->element == 'supplier_proposal') {
3564 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL
";
3567 if (!empty($MODULE)) {
3568 if (!empty($conf->global->$MODULE)) {
3569 $modsactivated = explode(',', $conf->global->$MODULE);
3570 foreach ($modsactivated as $mod) {
3571 if (isModEnabled($mod)) {
3572 return 1; // update was disabled by specific setup
3578 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3580 $forcedroundingmode = $roundingadjust;
3581 if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3582 $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3583 } elseif ($forcedroundingmode == 'auto') {
3584 $forcedroundingmode = '0';
3589 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3591 // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3592 $fieldtva = 'total_tva';
3593 $fieldlocaltax1 = 'total_localtax1';
3594 $fieldlocaltax2 = 'total_localtax2';
3595 $fieldup = 'subprice';
3596 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3600 if ($this->element == 'invoice_supplier_rec') {
3603 if ($this->element == 'expensereport') {
3604 $fieldup = 'value_unit';
3607 $sql = "SELECT
rowid, qty,
".$fieldup." as up, remise_percent, total_ht,
".$fieldtva." as total_tva, total_ttc,
".$fieldlocaltax1." as total_localtax1,
".$fieldlocaltax2." as total_localtax2,
";
3608 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3609 if ($this->table_element_line == 'facturedet') {
3610 $sql .= ', situation_percent';
3612 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3613 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
3614 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3616 $product_field = 'product_type';
3617 if ($this->table_element_line == 'contratdet') {
3618 $product_field = ''; // contratdet table has no product_type field
3620 if ($product_field) {
3621 $sql .= " AND
".$product_field." <> 9
";
3624 $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
3626 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3628 $resql = $this->db->query($sql);
3630 $this->total_ht = 0;
3631 $this->total_tva = 0;
3632 $this->total_localtax1 = 0;
3633 $this->total_localtax2 = 0;
3634 $this->total_ttc = 0;
3635 $total_ht_by_vats = array();
3636 $total_tva_by_vats = array();
3637 $total_ttc_by_vats = array();
3638 $this->multicurrency_total_ht = 0;
3639 $this->multicurrency_total_tva = 0;
3640 $this->multicurrency_total_ttc = 0;
3642 $num = $this->db->num_rows($resql);
3645 $obj = $this->db->fetch_object($resql);
3647 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3648 $parameters = array('fk_element' => $obj->rowid);
3649 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3651 if (empty($reshook) && $forcedroundingmode == '0') { // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
3652 // This part of code is to fix data. We should not call it too often.
3653 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3654 $tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
3656 $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3657 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3658 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3659 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3661 if ($diff_on_current_total) {
3662 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3663 $sqlfix = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldtva." =
".price2num((float) $tmpcal[1]).", total_ttc =
".price2num((float) $tmpcal[2])." WHERE
rowid =
".((int) $obj->rowid);
3664 dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=
".$obj->total_ht." vat=
".$obj->total_tva." tax1=
".$obj->total_localtax1." tax2=
".$obj->total_localtax2." ttc=
".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix =
".$sqlfix, LOG_WARNING);
3665 $resqlfix = $this->db->query($sqlfix);
3667 dol_print_error($this->db, 'Failed to update line');
3669 $obj->total_tva = $tmpcal[1];
3670 $obj->total_ttc = $tmpcal[2];
3671 } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
3672 // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3673 // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3674 $sqlfix = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldtva." =
".price2num((float) $tmpcal[1]).", total_ttc =
".price2num((float) $tmpcal[2])." WHERE
rowid =
".((int) $obj->rowid);
3675 dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=
".$tmpcal[1].", database=
".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix =
".$sqlfix);
3676 $resqlfix = $this->db->query($sqlfix);
3678 dol_print_error($this->db, 'Failed to update line');
3680 $obj->total_tva = $tmpcal[1];
3681 $obj->total_ttc = $tmpcal[2];
3685 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3686 $this->total_tva += $obj->total_tva;
3687 $this->total_localtax1 += $obj->total_localtax1;
3688 $this->total_localtax2 += $obj->total_localtax2;
3689 $this->total_ttc += $obj->total_ttc;
3690 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3691 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3692 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3694 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3695 $total_ht_by_vats[$obj->vatrate] = 0;
3697 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3698 $total_tva_by_vats[$obj->vatrate] = 0;
3700 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3701 $total_ttc_by_vats[$obj->vatrate] = 0;
3703 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3704 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3705 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3707 if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3708 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3709 $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3710 //print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF
":"")."<br>\n
";
3712 if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) {
3713 // If error is more than 10 times the accurancy of rounding. This should not happen.
3714 $errmsg = 'A rounding difference was detected into TOTAL but is too high to be corrected. Some data in your line may be corrupted. Try to edit each line manually.';
3715 dol_syslog($errmsg, LOG_WARNING);
3716 dol_print_error('', $errmsg);
3719 $sqlfix = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldtva." =
".price2num($obj->total_tva - $diff).", total_ttc =
".price2num($obj->total_ttc - $diff)." WHERE
rowid =
".((int) $obj->rowid);
3720 dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix =
".$sqlfix);
3722 $resqlfix = $this->db->query($sqlfix);
3725 dol_print_error($this->db, 'Failed to update line');
3728 $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3729 $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3730 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3731 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3738 // Add revenue stamp to total
3739 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3740 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3742 // Situations totals
3743 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3744 $prev_sits = $this->get_prev_sits();
3746 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3747 $this->total_ht -= $sit->total_ht;
3748 $this->total_tva -= $sit->total_tva;
3749 $this->total_localtax1 -= $sit->total_localtax1;
3750 $this->total_localtax2 -= $sit->total_localtax2;
3751 $this->total_ttc -= $sit->total_ttc;
3752 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3753 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3754 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3759 $this->total_ht = (float) price2num($this->total_ht);
3760 $this->total_tva = (float) price2num($this->total_tva);
3761 $this->total_localtax1 = (float) price2num($this->total_localtax1);
3762 $this->total_localtax2 = (float) price2num($this->total_localtax2);
3763 $this->total_ttc = (float) price2num($this->total_ttc);
3765 $this->db->free($resql);
3767 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
3768 $fieldht = 'total_ht';
3770 $fieldlocaltax1 = 'localtax1';
3771 $fieldlocaltax2 = 'localtax2';
3772 $fieldttc = 'total_ttc';
3773 // Specific code for backward compatibility with old field names
3774 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
3775 $fieldtva = 'total_tva';
3778 if (empty($nodatabaseupdate)) {
3779 $sql = "UPDATE
".$this->db->prefix().$this->table_element.' SET';
3780 $sql .= " ".$fieldht." =
".((float) price2num($this->total_ht, 'MT', 1)).",
";
3781 $sql .= " ".$fieldtva." =
".((float) price2num($this->total_tva, 'MT', 1)).",
";
3782 $sql .= " ".$fieldlocaltax1." =
".((float) price2num($this->total_localtax1, 'MT', 1)).",
";
3783 $sql .= " ".$fieldlocaltax2." =
".((float) price2num($this->total_localtax2, 'MT', 1)).",
";
3784 $sql .= " ".$fieldttc." =
".((float) price2num($this->total_ttc, 'MT', 1));
3785 $sql .= ", multicurrency_total_ht =
".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3786 $sql .= ", multicurrency_total_tva =
".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3787 $sql .= ", multicurrency_total_ttc =
".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3788 $sql .= " WHERE
rowid =
".((int) $this->id);
3790 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3791 $resql = $this->db->query($sql);
3795 $this->error = $this->db->lasterror();
3796 $this->errors[] = $this->db->lasterror();
3806 dol_print_error($this->db, 'Bad request in update_price');
3811 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3822 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3825 global $user, $hookmanager, $action;
3826 $origin = (!empty($origin) ? $origin : $this->origin);
3827 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3828 $f_user = isset($f_user) ? $f_user : $user;
3831 if ($origin == 'order') {
3832 $origin = 'commande';
3834 if ($origin == 'invoice') {
3835 $origin = 'facture';
3837 if ($origin == 'invoice_template') {
3838 $origin = 'facturerec';
3840 if ($origin == 'supplierorder') {
3841 $origin = 'order_supplier';
3844 // Elements of the core modules which have `$module` property but may to which we don't want to prefix module part to the element name for finding the linked object in llx_element_element.
3845 // It's because an entry for this element may be exist in llx_element_element before this modification (version <=14.2) and ave named only with their element name in fk_source or fk_target.
3846 $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3847 // Add module part to target type if object has $module property and isn't in core modules.
3848 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3850 $parameters = array('targettype'=>$targettype);
3851 // Hook for explicitly set the targettype if it must be differtent than $this->element
3852 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3854 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3860 $sql = "INSERT INTO
" . $this->db->prefix() . "element_element (
";
3861 $sql .= "fk_source
";
3862 $sql .= ", sourcetype
";
3863 $sql .= ", fk_target
";
3864 $sql .= ", targettype
";
3865 $sql .= ") VALUES (
";
3866 $sql .= ((int) $origin_id);
3867 $sql .= ",
'" . $this->db->escape($origin) . "'";
3868 $sql .= ",
" . ((int) $this->id);
3869 $sql .= ",
'" . $this->db->escape($targettype) . "'";
3873 if ($this->db->query($sql)) {
3876 $this->context['link_origin'] = $origin;
3877 $this->context['link_origin_id'] = $origin_id;
3878 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3882 // End call triggers
3885 $this->error = $this->db->lasterror();
3890 $this->db->commit();
3893 $this->db->rollback();
3920 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3922 global $conf, $hookmanager, $action;
3924 // Important for pdf generation time reduction
3925 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3926 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3930 $this->linkedObjectsIds = array();
3931 $this->linkedObjects = array();
3933 $justsource = false;
3934 $justtarget = false;
3935 $withtargettype = false;
3936 $withsourcetype = false;
3938 $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3939 // Hook for explicitly set the targettype if it must be differtent than $this->element
3940 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3942 if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3943 if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3944 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3945 if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3948 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3949 $justsource = true; // the source (id and type) is a search criteria
3950 if (!empty($targettype)) {
3951 $withtargettype = true;
3954 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3955 $justtarget = true; // the target (id and type) is a search criteria
3956 if (!empty($sourcetype)) {
3957 $withsourcetype = true;
3961 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3962 $targetid = (!empty($targetid) ? $targetid : $this->id);
3963 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3964 $targettype = (!empty($targettype) ? $targettype : $this->element);
3966 /*if (empty($sourceid) && empty($targetid))
3968 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3972 // Links between objects are stored in table element_element
3973 $sql = "SELECT
rowid, fk_source, sourcetype, fk_target, targettype
";
3974 $sql .= " FROM
".$this->db->prefix()."element_element
";
3976 if ($justsource || $justtarget) {
3978 $sql .= "fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3979 if ($withtargettype) {
3980 $sql .= " AND targettype =
'".$this->db->escape($targettype)."'";
3982 } elseif ($justtarget) {
3983 $sql .= "fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."'";
3984 if ($withsourcetype) {
3985 $sql .= " AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3989 $sql .= "(fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."')
";
3990 $sql .= " ".$clause." (fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."')
";
3991 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3992 $this->linkedObjectsFullLoaded[$this->id] = true;
3995 $sql .= " ORDER BY
".$orderby;
3997 dol_syslog(get_class($this)."::fetchObjectLink
", LOG_DEBUG);
3998 $resql = $this->db->query($sql);
4000 $num = $this->db->num_rows($resql);
4003 $obj = $this->db->fetch_object($resql);
4004 if ($justsource || $justtarget) {
4006 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4007 } elseif ($justtarget) {
4008 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4011 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4012 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4014 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4015 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4021 if (!empty($this->linkedObjectsIds)) {
4022 $tmparray = $this->linkedObjectsIds;
4023 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4024 // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4025 $module = $element = $subelement = $objecttype;
4027 if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4028 && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4029 $module = $element = $regs[1];
4030 $subelement = $regs[2];
4033 $classpath = $element.'/class';
4034 // To work with non standard classpath or module name
4035 if ($objecttype == 'facture') {
4036 $classpath = 'compta/facture/class';
4037 } elseif ($objecttype == 'facturerec') {
4038 $classpath = 'compta/facture/class';
4039 $module = 'facture';
4040 } elseif ($objecttype == 'propal') {
4041 $classpath = 'comm/propal/class';
4042 } elseif ($objecttype == 'supplier_proposal') {
4043 $classpath = 'supplier_proposal/class';
4044 } elseif ($objecttype == 'shipping') {
4045 $classpath = 'expedition/class';
4046 $subelement = 'expedition';
4047 $module = 'expedition_bon';
4048 } elseif ($objecttype == 'delivery') {
4049 $classpath = 'delivery/class';
4050 $subelement = 'delivery';
4051 $module = 'delivery_note';
4052 } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4053 $classpath = 'fourn/class';
4054 $module = 'fournisseur';
4055 } elseif ($objecttype == 'fichinter') {
4056 $classpath = 'fichinter/class';
4057 $subelement = 'fichinter';
4058 $module = 'ficheinter';
4059 } elseif ($objecttype == 'subscription') {
4060 $classpath = 'adherents/class';
4061 $module = 'adherent';
4062 } elseif ($objecttype == 'contact') {
4063 $module = 'societe';
4066 $classfile = strtolower($subelement);
4067 $classname = ucfirst($subelement);
4069 if ($objecttype == 'order') {
4070 $classfile = 'commande';
4071 $classname = 'Commande';
4072 } elseif ($objecttype == 'invoice_supplier') {
4073 $classfile = 'fournisseur.facture';
4074 $classname = 'FactureFournisseur';
4075 } elseif ($objecttype == 'order_supplier') {
4076 $classfile = 'fournisseur.commande';
4077 $classname = 'CommandeFournisseur';
4078 } elseif ($objecttype == 'supplier_proposal') {
4079 $classfile = 'supplier_proposal';
4080 $classname = 'SupplierProposal';
4081 } elseif ($objecttype == 'facturerec') {
4082 $classfile = 'facture-rec';
4083 $classname = 'FactureRec';
4084 } elseif ($objecttype == 'subscription') {
4085 $classfile = 'subscription';
4086 $classname = 'Subscription';
4087 } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4088 $classpath = 'projet/class';
4089 $classfile = 'project';
4090 $classname = 'Project';
4091 } elseif ($objecttype == 'conferenceorboothattendee') {
4092 $classpath = 'eventorganization/class';
4093 $classfile = 'conferenceorboothattendee';
4094 $classname = 'ConferenceOrBoothAttendee';
4095 $module = 'eventorganization';
4096 } elseif ($objecttype == 'conferenceorbooth') {
4097 $classpath = 'eventorganization/class';
4098 $classfile = 'conferenceorbooth';
4099 $classname = 'ConferenceOrBooth';
4100 $module = 'eventorganization';
4101 } elseif ($objecttype == 'mo') {
4102 $classpath = 'mrp/class';
4108 // Here $module, $classfile and $classname are set, we can use them.
4109 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4110 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4111 dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4112 //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4113 if (class_exists($classname)) {
4114 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4115 $object = new $classname($this->db);
4116 $ret = $object->fetch($objectid);
4118 $this->linkedObjects[$objecttype][$i] = $object;
4124 unset($this->linkedObjectsIds[$objecttype]);
4130 dol_print_error($this->db);
4141 public function clearObjectLinkedCache()
4143 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4144 unset($this->linkedObjectsFullLoaded[$this->id]);
4162 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4165 $updatesource = false;
4166 $updatetarget = false;
4167 $f_user = isset($f_user) ? $f_user : $user;
4169 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4170 $updatesource = true;
4171 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4172 $updatetarget = true;
4178 $sql = "UPDATE
" . $this->db->prefix() . "element_element SET
";
4179 if ($updatesource) {
4180 $sql .= "fk_source =
" . ((int) $sourceid);
4181 $sql .= ", sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4182 $sql .= " WHERE fk_target =
" . ((int) $this->id);
4183 $sql .= " AND targettype =
'" . $this->db->escape($this->element) . "'";
4184 } elseif ($updatetarget) {
4185 $sql .= "fk_target =
" . ((int) $targetid);
4186 $sql .= ", targettype =
'" . $this->db->escape($targettype) . "'";
4187 $sql .= " WHERE fk_source =
" . ((int) $this->id);
4188 $sql .= " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4192 if ($this->db->query($sql)) {
4195 $this->context['link_source_id'] = $sourceid;
4196 $this->context['link_source_type'] = $sourcetype;
4197 $this->context['link_target_id'] = $targetid;
4198 $this->context['link_target_type'] = $targettype;
4199 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4203 // End call triggers
4206 $this->error = $this->db->lasterror();
4211 $this->db->commit();
4214 $this->db->rollback();
4232 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4235 $deletesource = false;
4236 $deletetarget = false;
4237 $f_user = isset($f_user) ? $f_user : $user;
4239 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4240 $deletesource = true;
4241 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4242 $deletetarget = true;
4245 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4246 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4247 $targetid = (!empty($targetid) ? $targetid : $this->id);
4248 $targettype = (!empty($targettype) ? $targettype : $this->element);
4254 $this->context['link_id'] = $rowid;
4255 $this->context['link_source_id'] = $sourceid;
4256 $this->context['link_source_type'] = $sourcetype;
4257 $this->context['link_target_id'] = $targetid;
4258 $this->context['link_target_type'] = $targettype;
4259 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4263 // End call triggers
4267 $sql = "DELETE FROM
" . $this->db->prefix() . "element_element
";
4270 $sql .= " rowid =
" . ((int) $rowid);
4272 if ($deletesource) {
4273 $sql .= " fk_source =
" . ((int) $sourceid) . " AND sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4274 $sql .= " AND fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "'";
4275 } elseif ($deletetarget) {
4276 $sql .= " fk_target =
" . ((int) $targetid) . " AND targettype =
'" . $this->db->escape($targettype) . "'";
4277 $sql .= " AND fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4279 $sql .= " (fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "')
";
4281 $sql .= " (fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "')
";
4286 if (!$this->db->query($sql)) {
4287 $this->error = $this->db->lasterror();
4288 $this->errors[] = $this->error;
4294 $this->db->commit();
4297 $this->db->rollback();
4311 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4313 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4319 $sql = "SELECT
".$field_select." FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4320 $resql = $db->query($sql);
4323 if (!empty($resql)) {
4324 while ($res = $db->fetch_object($resql)) {
4325 $TRes[] = $res->{$field_select};
4340 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4342 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4348 $sql = "DELETE FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4349 $resql = $db->query($sql);
4351 if (empty($resql)) {
4368 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4370 global $user, $langs, $conf;
4372 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4374 $elementId = (!empty($elementId) ? $elementId : $this->id);
4375 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4379 if ($elementTable == 'facture_rec') {
4380 $fieldstatus = "suspended
";
4382 if ($elementTable == 'mailing') {
4383 $fieldstatus = "statut
";
4385 if ($elementTable == 'cronjob') {
4386 $fieldstatus = "status
";
4388 if ($elementTable == 'user') {
4389 $fieldstatus = "statut
";
4391 if ($elementTable == 'expensereport') {
4392 $fieldstatus = "fk_statut
";
4394 if ($elementTable == 'commande_fournisseur_dispatch') {
4395 $fieldstatus = "status
";
4397 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4398 $fieldstatus = 'status';
4401 $sql = "UPDATE
".$this->db->prefix().$elementTable;
4402 $sql .= " SET
".$fieldstatus." =
".((int) $status);
4403 // If status = 1 = validated, update also fk_user_valid
4404 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4405 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4406 $sql .= ", fk_user_valid =
".((int) $user->id);
4408 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4409 $sql .= ", date_valid =
'".$this->db->idate(dol_now())."'";
4411 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4412 $sql .= ", date_validation =
'".$this->db->idate(dol_now())."'";
4414 $sql .= " WHERE
rowid =
".((int) $elementId);
4415 $sql .= " AND
".$fieldstatus." <>
".((int) $status); // We avoid update if status already correct
4417 dol_syslog(get_class($this)."::
setStatut", LOG_DEBUG);
4418 $resql = $this->db->query($sql);
4422 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4424 if ($nb_rows_affected > 0) {
4425 if (empty($trigkey)) {
4426 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4427 if ($this->element == 'supplier_proposal' && $status == 2) {
4428 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4430 if ($this->element == 'supplier_proposal' && $status == 3) {
4431 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4433 if ($this->element == 'supplier_proposal' && $status == 4) {
4434 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4436 if ($this->element == 'fichinter' && $status == 3) {
4437 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4439 if ($this->element == 'fichinter' && $status == 2) {
4440 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4442 if ($this->element == 'fichinter' && $status == 1) {
4443 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4449 $result = $this->call_trigger($trigkey, $user);
4453 // End call triggers
4456 // The status was probably already good. We do nothing more, no triggers.
4460 $this->db->commit();
4462 if (empty($savElementId)) {
4463 // If the element we update is $this (so $elementId was provided as null)
4464 if ($fieldstatus == 'tosell') {
4465 $this->status = $status;
4466 } elseif ($fieldstatus == 'tobuy') {
4467 $this->status_buy = $status;
4469 $this->statut = $status;
4470 $this->status = $status;
4476 $this->db->rollback();
4477 dol_syslog(get_class($this)."::
setStatut ".$this->error, LOG_ERR);
4481 $this->error = $this->db->lasterror();
4482 $this->db->rollback();
4495 public function getCanvas($id = 0, $ref = '')
4499 if (empty($id) && empty($ref)) {
4502 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4503 return 0; // To increase speed. Not enabled by default.
4509 $sql = "SELECT
rowid, canvas
";
4510 $sql .= " FROM
".$this->db->prefix().$this->table_element;
4511 $sql .= " WHERE entity IN (
".getEntity($this->element).")
";
4513 $sql .= " AND
rowid =
".((int) $id);
4516 $sql .= " AND
ref =
'".$this->db->escape($ref)."'";
4519 $resql = $this->db->query($sql);
4521 $obj = $this->db->fetch_object($resql);
4523 $this->canvas = $obj->canvas;
4529 dol_print_error($this->db);
4541 public function getSpecialCode($lineid)
4543 $sql = "SELECT special_code FROM
".$this->db->prefix().$this->table_element_line;
4544 $sql .= " WHERE
rowid =
".((int) $lineid);
4545 $resql = $this->db->query($sql);
4547 $row = $this->db->fetch_row($resql);
4560 public function isObjectUsed($id = 0, $entity = 0)
4569 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4570 dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4574 $arraytoscan = $this->childtables;
4575 // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4576 $tmparray = array_keys($this->childtables);
4577 if (is_numeric($tmparray[0])) {
4578 $arraytoscan = array_flip($this->childtables);
4581 // Test if child exists
4583 foreach ($arraytoscan as $table => $element) {
4584 //print $id.'-'.$table.'-'.$elementname.'<br>';
4585 // Check if element can be deleted
4586 $sql = "SELECT COUNT(*) as nb
";
4587 $sql.= " FROM
".$this->db->prefix().$table." as c
";
4588 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4589 $sql.= ",
".$this->db->prefix().$element['parent']." as p
";
4591 $sql.= " WHERE c.
".$this->fk_element." =
".((int) $id);
4592 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4593 $sql.= " AND c.
".$element['parentkey']." = p.rowid
";
4595 if (!empty($entity)) {
4596 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4597 $sql.= " AND p.entity =
".((int) $entity);
4599 $sql.= " AND c.entity =
".((int) $entity);
4602 $resql = $this->db->query($sql);
4604 $obj = $this->db->fetch_object($resql);
4606 $langs->load("errors
");
4607 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4608 $haschild += $obj->nb;
4609 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4610 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4611 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4612 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4613 } else { // new usage: $element['name']=Translation key
4614 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4616 break; // We found at least one, we stop here
4619 $this->errors[] = $this->db->lasterror();
4623 if ($haschild > 0) {
4624 $this->errors[] = "ErrorRecordHasChildren
";
4637 public function hasProductsOrServices($predefined = -1)
4641 foreach ($this->lines as $key => $val) {
4643 if ($predefined == -1) {
4646 if ($predefined == 1 && $val->fk_product > 0) {
4649 if ($predefined == 0 && $val->fk_product <= 0) {
4652 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4655 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4662 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4671 public function getTotalDiscount()
4673 if (!empty($this->table_element_line) ) {
4674 $total_discount = 0.00;
4676 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht
";
4677 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
4678 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
4680 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4681 $resql = $this->db->query($sql);
4683 $num = $this->db->num_rows($resql);
4686 $obj = $this->db->fetch_object($resql);
4688 $pu_ht = $obj->pu_ht;
4690 $total_ht = $obj->total_ht;
4692 $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4693 $total_discount += $total_discount_line;
4699 //print $total_discount; exit;
4700 return price2num($total_discount);
4713 public function getTotalWeightVolume()
4717 // defined for shipment only
4719 // defined for shipment only
4722 foreach ($this->lines as $line) {
4723 if (isset($line->qty_asked)) {
4724 if (empty($totalOrdered)) {
4725 $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4727 $totalOrdered += $line->qty_asked; // defined for shipment only
4729 if (isset($line->qty_shipped)) {
4730 if (empty($totalToShip)) {
4731 $totalToShip = 0; // Avoid warning because $totalToShip is ''
4733 $totalToShip += $line->qty_shipped; // defined for shipment only
4734 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4735 if (empty($totalToShip)) {
4738 $totalToShip += $line->qty; // defined for reception only
4741 // Define qty, weight, volume, weight_units, volume_units
4742 if ($this->element == 'shipping') {
4744 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4746 $qty = $line->qty ? $line->qty : 0;
4749 $weight = !empty($line->weight) ? $line->weight : 0;
4750 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4751 $volume = !empty($line->volume) ? $line->volume : 0;
4752 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4754 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4755 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4756 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4757 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4761 if (!empty($weight_units)) {
4762 $weightUnit = $weight_units;
4764 if (!empty($volume_units)) {
4765 $volumeUnit = $volume_units;
4768 if (empty($totalWeight)) {
4769 $totalWeight = 0; // Avoid warning because $totalWeight is ''
4771 if (empty($totalVolume)) {
4772 $totalVolume = 0; // Avoid warning because $totalVolume is ''
4775 //var_dump($line->volume_units);
4776 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4777 $trueWeightUnit = pow(10, $weightUnit);
4778 $totalWeight += $weight * $qty * $trueWeightUnit;
4780 if ($weight_units == 99) {
4781 // conversion 1 Pound = 0.45359237 KG
4782 $trueWeightUnit = 0.45359237;
4783 $totalWeight += $weight * $qty * $trueWeightUnit;
4784 } elseif ($weight_units == 98) {
4785 // conversion 1 Ounce = 0.0283495 KG
4786 $trueWeightUnit = 0.0283495;
4787 $totalWeight += $weight * $qty * $trueWeightUnit;
4789 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4792 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4793 //print $line->volume."x
".$line->volume_units."x
".($line->volume_units < 50)."x
".$volumeUnit;
4794 $trueVolumeUnit = pow(10, $volumeUnit);
4795 //print $line->volume;
4796 $totalVolume += $volume * $qty * $trueVolumeUnit;
4798 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4802 return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4811 public function setExtraParameters()
4815 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4817 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
4818 $sql .= " SET extraparams =
".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4819 $sql .= " WHERE
rowid =
".((int) $this->id);
4822 $resql = $this->db->query($sql);
4824 $this->error = $this->db->lasterror();
4825 $this->db->rollback();
4828 $this->db->commit();
4834 // --------------------
4835 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4836 // --------------------
4838 /* This is to show add lines */
4849 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4851 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4855 if (!is_object($extrafields)) {
4856 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4857 $extrafields = new ExtraFields($this->db);
4859 $extrafields->fetch_name_optionals_label($this->table_element_line);
4861 // Output template part (modules that overwrite templates must declare this into descriptor)
4862 // Use global variables + $dateSelector + $seller and $buyer
4863 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4864 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4865 foreach ($dirtpls as $module => $reldir) {
4866 if (!empty($module)) {
4867 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4869 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4872 if (empty($conf->file->strict_mode)) {
4873 $res = @include $tpl;
4875 $res = include $tpl; // for debug
4885 /* This is to show array of line of details */
4902 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4904 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4905 // TODO We should not use global var for this
4906 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4908 // Define usemargins
4910 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4914 $num = count($this->lines);
4917 if (!is_object($extrafields)) {
4918 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4919 $extrafields = new ExtraFields($this->db);
4921 $extrafields->fetch_name_optionals_label($this->table_element_line);
4923 $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4924 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4925 if (empty($reshook)) {
4926 // Output template part (modules that overwrite templates must declare this into descriptor)
4927 // Use global variables + $dateSelector + $seller and $buyer
4928 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4929 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4930 foreach ($dirtpls as $module => $reldir) {
4932 if (!empty($module)) {
4933 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4935 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4937 if (file_exists($tpl)) {
4938 if (empty($conf->file->strict_mode)) {
4939 $res = @include $tpl;
4941 $res = include $tpl; // for debug
4953 foreach ($this->lines as $line) {
4955 $line->fetch_optionals();
4957 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
4958 if (is_object($hookmanager)) { // Old code is commented on preceding line.
4959 if (empty($line->fk_parent_line)) {
4960 $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4961 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4963 $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element, 'fk_parent_line'=>$line->fk_parent_line);
4964 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4967 if (empty($reshook)) {
4968 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4993 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4995 global $conf, $langs, $user, $object, $hookmanager;
4997 global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4999 $object_rights = $this->getRights();
5001 $element = $this->element;
5006 // Line in view mode
5007 if ($action != 'editline' || $selected != $line->id) {
5009 if (!empty($line->fk_product) && $line->fk_product > 0) {
5010 $product_static = new Product($this->db);
5011 $product_static->fetch($line->fk_product);
5013 $product_static->ref = $line->ref; //can change ref in hook
5014 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5016 $text = $product_static->getNomUrl(1);
5018 // Define output language and label
5019 if (getDolGlobalInt('MAIN_MULTILANGS')) {
5020 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5021 dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5025 $prod = new Product($this->db);
5026 $prod->fetch($line->fk_product);
5028 $outputlangs = $langs;
5030 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5031 $newlang = GETPOST('lang_id', 'aZ09');
5033 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5034 $newlang = $this->thirdparty->default_lang; // To use language of customer
5036 if (!empty($newlang)) {
5037 $outputlangs = new Translate("", $conf);
5038 $outputlangs->setDefaultLang($newlang);
5041 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label
"])) ? $prod->multilangs[$outputlangs->defaultlang]["label
"] : $line->product_label;
5043 $label = $line->product_label;
5046 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5047 $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5050 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5052 // Output template part (modules that overwrite templates must declare this into descriptor)
5053 // Use global variables + $dateSelector + $seller and $buyer
5054 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5055 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5056 foreach ($dirtpls as $module => $reldir) {
5058 if (!empty($module)) {
5059 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5061 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5063 if (file_exists($tpl)) {
5064 if (empty($conf->file->strict_mode)) {
5065 $res = @include $tpl;
5067 $res = include $tpl; // for debug
5076 // Line in update mode
5077 if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5078 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5080 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5082 // Output template part (modules that overwrite templates must declare this into descriptor)
5083 // Use global variables + $dateSelector + $seller and $buyer
5084 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5085 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5086 foreach ($dirtpls as $module => $reldir) {
5087 if (!empty($module)) {
5088 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5090 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5093 if (empty($conf->file->strict_mode)) {
5094 $res = @include $tpl;
5096 $res = include $tpl; // for debug
5106 /* This is to show array of line of details of source object */
5119 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5121 global $langs, $hookmanager, $conf, $form, $action;
5123 print '<tr class="liste_titre
">';
5124 print '<td class="linecolref
">'.$langs->trans('Ref').'</td>';
5125 print '<td class="linecoldescription
">'.$langs->trans('Description').'</td>';
5126 print '<td class="linecolvat right
">'.$langs->trans('VATRate').'</td>';
5127 print '<td class="linecoluht right
">'.$langs->trans('PriceUHT').'</td>';
5128 if (isModEnabled("multicurrency
")) {
5129 print '<td class="linecoluht_currency right
">'.$langs->trans('PriceUHTCurrency').'</td>';
5131 print '<td class="linecolqty right
">'.$langs->trans('Qty').'</td>';
5132 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5133 print '<td class="linecoluseunit left
">'.$langs->trans('Unit').'</td>';
5135 print '<td class="linecoldiscount right
">'.$langs->trans('ReductionShort').'</td>';
5136 print '<td class="linecolht right
">'.$langs->trans('TotalHT').'</td>';
5137 print '<td class="center
">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5141 if (!empty($this->lines)) {
5142 foreach ($this->lines as $line) {
5144 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5145 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5146 $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5147 if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5148 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5150 if (empty($reshook)) {
5151 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5172 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5174 global $langs, $conf;
5177 if (!empty($line->date_start)) {
5178 $date_start = $line->date_start;
5180 $date_start = $line->date_debut_prevue;
5181 if ($line->date_debut_reel) {
5182 $date_start = $line->date_debut_reel;
5185 if (!empty($line->date_end)) {
5186 $date_end = $line->date_end;
5188 $date_end = $line->date_fin_prevue;
5189 if ($line->date_fin_reel) {
5190 $date_end = $line->date_fin_reel;
5194 $this->tpl['id'] = $line->id;
5196 $this->tpl['label'] = '';
5197 if (!empty($line->fk_parent_line)) {
5198 $this->tpl['label'] .= img_picto('', 'rightarrow');
5201 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5202 $discount = new DiscountAbsolute($this->db);
5203 $discount->fk_soc = $this->socid;
5204 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5205 } elseif (!empty($line->fk_product)) {
5206 $productstatic = new Product($this->db);
5207 $productstatic->id = $line->fk_product;
5208 $productstatic->ref = $line->ref;
5209 $productstatic->type = $line->fk_product_type;
5210 if (empty($productstatic->ref)) {
5211 $line->fetch_product();
5212 $productstatic = $line->product;
5215 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5216 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5218 if ($line->product_type == 1 && ($date_start || $date_end)) {
5219 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5222 $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5223 if (!empty($line->desc)) {
5224 $this->tpl['label'] .= $line->desc;
5226 $this->tpl['label'] .= ($line->label ? ' '.$line->label : '');
5230 if ($line->product_type == 1 && ($date_start || $date_end)) {
5231 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5235 if (!empty($line->desc)) {
5236 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5237 $discount = new DiscountAbsolute($this->db);
5238 $discount->fetch($line->fk_remise_except);
5239 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote
", $discount->getNomUrl(0));
5240 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5241 $discount = new DiscountAbsolute($this->db);
5242 $discount->fetch($line->fk_remise_except);
5243 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit
", $discount->getNomUrl(0));
5244 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5245 $discount = new DiscountAbsolute($this->db);
5246 $discount->fetch($line->fk_remise_except);
5247 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived
", $discount->getNomUrl(0));
5248 } elseif ($line->desc == '(EXCESS PAID)') {
5249 $discount = new DiscountAbsolute($this->db);
5250 $discount->fetch($line->fk_remise_except);
5251 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid
", $discount->getNomUrl(0));
5253 $this->tpl['description'] = dol_trunc($line->desc, 60);
5256 $this->tpl['description'] = ' ';
5260 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5261 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5262 if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5263 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5266 $this->tpl['price'] = price($line->subprice);
5267 $this->tpl['total_ht'] = price($line->total_ht);
5268 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5269 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' ';
5270 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5271 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5273 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' ';
5275 // Is the line strike or not
5276 $this->tpl['strike'] = 0;
5277 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5278 $this->tpl['strike'] = 1;
5281 // Output template part (modules that overwrite templates must declare this into descriptor)
5282 // Use global variables + $dateSelector + $seller and $buyer
5283 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5284 foreach ($dirtpls as $module => $reldir) {
5285 if (!empty($module)) {
5286 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5288 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5291 if (empty($conf->file->strict_mode)) {
5292 $res = @include $tpl;
5294 $res = include $tpl; // for debug
5303 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5314 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5319 $sql = "INSERT INTO
".$this->db->prefix()."element_resources (
";
5320 $sql .= "resource_id
";
5321 $sql .= ", resource_type
";
5322 $sql .= ", element_id
";
5323 $sql .= ", element_type
";
5325 $sql .= ", mandatory
";
5326 $sql .= ") VALUES (
";
5327 $sql .= $resource_id;
5328 $sql .= ",
'".$this->db->escape($resource_type)."'";
5329 $sql .= ",
'".$this->db->escape($this->id)."'";
5330 $sql .= ",
'".$this->db->escape($this->element)."'";
5331 $sql .= ",
'".$this->db->escape($busy)."'";
5332 $sql .= ",
'".$this->db->escape($mandatory)."'";
5336 if ($this->db->query($sql)) {
5337 $this->db->commit();
5340 $this->error = $this->db->lasterror();
5341 $this->db->rollback();
5346 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5355 public function delete_resource($rowid, $element, $notrigger = 0)
5362 $sql = "DELETE FROM
".$this->db->prefix()."element_resources
";
5363 $sql .= " WHERE
rowid =
".((int) $rowid);
5367 $resql = $this->db->query($sql);
5369 $this->error = $this->db->lasterror();
5370 $this->db->rollback();
5374 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5376 $this->db->rollback();
5380 $this->db->commit();
5391 public function __clone()
5393 // Force a copy of this->lines, otherwise it will point to same object.
5394 if (isset($this->lines) && is_array($this->lines)) {
5395 $nboflines = count($this->lines);
5396 for ($i = 0; $i < $nboflines; $i++) {
5397 $this->lines[$i] = clone $this->lines[$i];
5415 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5417 global $conf, $langs, $user, $hookmanager, $action;
5419 $srctemplatepath = '';
5421 $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5422 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5424 if (empty($reshook)) {
5425 dol_syslog("commonGenerateDocument modele=
".$modele." outputlangs->defaultlang=
".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5427 if (empty($modele)) {
5428 $this->error = 'BadValueForParameterModele';
5432 // Increase limit for PDF build
5433 $err = error_reporting();
5435 @set_time_limit(120);
5436 error_reporting($err);
5438 // If selected model is a filename template (then $modele="modelname
" or "modelname:filename
")
5439 $tmp = explode(':', $modele, 2);
5440 if (!empty($tmp[1])) {
5442 $srctemplatepath = $tmp[1];
5445 // Search template files
5449 $dirmodels = array('/');
5450 if (is_array($conf->modules_parts['models'])) {
5451 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5453 foreach ($dirmodels as $reldir) {
5454 foreach (array('doc', 'pdf') as $prefix) {
5455 if (in_array(get_class($this), array('Adherent'))) {
5456 // Member module use prefix_modele.class.php
5457 $file = $prefix."_
".$modele.".class.php
";
5459 // Other module use prefix_modele.modules.php
5460 $file = $prefix."_
".$modele.".modules.php
";
5463 // On verifie l'emplacement du modele
5464 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5465 if (file_exists($file)) {
5467 $classname = $prefix.'_'.$modele;
5476 // If generator was found
5478 global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5482 $obj = new $classname($this->db);
5484 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5485 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5486 $varfortemplatedir = $obj->scandir;
5487 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5488 $dirtoscan = $conf->global->$varfortemplatedir;
5490 $listoffiles = array();
5492 // Now we add first model found in directories scanned
5493 $listofdir = explode(',', $dirtoscan);
5494 foreach ($listofdir as $key => $tmpdir) {
5495 $tmpdir = trim($tmpdir);
5496 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5498 unset($listofdir[$key]);
5501 if (is_dir($tmpdir)) {
5502 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5503 if (count($tmpfiles)) {
5504 $listoffiles = array_merge($listoffiles, $tmpfiles);
5509 if (count($listoffiles)) {
5510 foreach ($listoffiles as $record) {
5511 $srctemplatepath = $record['fullname'];
5517 if (empty($srctemplatepath)) {
5518 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5523 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5524 if (!dol_is_file($srctemplatepath)) {
5525 dol_syslog("Failed to locate
template file
".$srctemplatepath, LOG_WARNING);
5526 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5531 // We save charset_output to restore it because write_file can change it if needed for
5532 // output format that does not support UTF8.
5533 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5535 if (in_array(get_class($this), array('Adherent'))) {
5536 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5538 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5540 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5542 if ($resultwritefile > 0) {
5543 $outputlangs->charset_output = $sav_charset_output;
5545 // We delete old preview
5546 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5547 dol_delete_preview($this);
5549 // Index file in database
5550 if (!empty($obj->result['fullpath'])) {
5551 $destfull = $obj->result['fullpath'];
5553 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5554 $update_main_doc_field = 0;
5555 if (!empty($obj->update_main_doc_field)) {
5556 $update_main_doc_field = 1;
5559 $this->indexFile($destfull, $update_main_doc_field);
5561 dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath
"] was not set.', LOG_WARNING);
5564 // Success in building document. We build meta file.
5565 dol_meta_create($this);
5569 $outputlangs->charset_output = $sav_charset_output;
5570 $this->error = $obj->error;
5571 $this->errors = $obj->errors;
5572 dol_syslog("Error generating document
for ".__CLASS__.". Error:
".$obj->error, LOG_ERR);
5577 $this->error = $langs->trans("Error
").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5578 $this->errors[] = $this->error;
5579 dol_syslog($this->error, LOG_ERR);
5581 $this->error = $langs->trans("Error
")." ".$langs->trans("ErrorFileDoesNotExists
", $filefound);
5582 $this->errors[] = $this->error;
5583 dol_syslog($this->error, LOG_ERR);
5601 public function indexFile($destfull, $update_main_doc_field)
5603 global $conf, $user;
5605 $upload_dir = dirname($destfull);
5606 $destfile = basename($destfull);
5607 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5609 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5610 $filename = basename($destfile);
5611 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5612 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5614 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5615 $ecmfile = new EcmFiles($this->db);
5616 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5618 // Set the public "share
" key
5619 $setsharekey = false;
5620 if ($this->element == 'propal' || $this->element == 'proposal') {
5621 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5622 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5624 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5625 $setsharekey = true;
5628 if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5629 $setsharekey = true;
5631 if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5632 $setsharekey = true;
5634 if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5635 $setsharekey = true;
5637 if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5638 $setsharekey = true;
5640 if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5641 $setsharekey = true;
5643 if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5644 $setsharekey = true;
5646 if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5647 $setsharekey = true;
5651 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5652 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5653 $ecmfile->share = getRandomPassword(true);
5658 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5659 $ecmfile->fullpath_orig = '';
5660 $ecmfile->gen_or_uploaded = 'generated';
5661 $ecmfile->description = ''; // indexed content
5662 $ecmfile->keywords = ''; // keyword content
5663 $result = $ecmfile->update($user);
5665 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5669 $ecmfile->entity = $conf->entity;
5670 $ecmfile->filepath = $rel_dir;
5671 $ecmfile->filename = $filename;
5672 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5673 $ecmfile->fullpath_orig = '';
5674 $ecmfile->gen_or_uploaded = 'generated';
5675 $ecmfile->description = ''; // indexed content
5676 $ecmfile->keywords = ''; // keyword content
5677 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5678 $ecmfile->src_object_id = $this->id;
5680 $result = $ecmfile->create($user);
5682 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5687 /*$this->result['fullname']=$destfull;
5688 $this->result['filepath']=$ecmfile->filepath;
5689 $this->result['filename']=$ecmfile->filename;*/
5690 //var_dump($obj->update_main_doc_field);exit;
5692 if ($update_main_doc_field && !empty($this->table_element)) {
5693 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET last_main_doc =
'".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5694 $sql .= " WHERE
rowid =
".((int) $this->id);
5696 $resql = $this->db->query($sql);
5698 dol_print_error($this->db);
5701 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5716 public function addThumbs($file)
5718 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5720 $tmparraysize = getDefaultImageSizes();
5721 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5722 $maxheightsmall = $tmparraysize['maxheightsmall'];
5723 $maxwidthmini = $tmparraysize['maxwidthmini'];
5724 $maxheightmini = $tmparraysize['maxheightmini'];
5725 //$quality = $tmparraysize['quality'];
5726 $quality = 50; // For thumbs, we force quality to 50
5728 $file_osencoded = dol_osencode($file);
5729 if (file_exists($file_osencoded)) {
5730 // Create small thumbs for company (Ratio is near 16/9)
5731 // Used on logon for example
5732 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5734 // Create mini thumbs for company (Ratio is near 16/9)
5735 // Used on menu or for setup page for example
5736 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5741 /* Functions common to commonobject and commonobjectline */
5743 /* For default values */
5757 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5759 global $conf, $_POST;
5761 // If param here has been posted, we use this value first.
5762 if (GETPOSTISSET($fieldname)) {
5763 return GETPOST($fieldname, 'alphanohtml', 3);
5766 if (isset($alternatevalue)) {
5767 return $alternatevalue;
5770 $newelement = $this->element;
5771 if ($newelement == 'facture') {
5772 $newelement = 'invoice';
5774 if ($newelement == 'commande') {
5775 $newelement = 'order';
5777 if (empty($newelement)) {
5778 dol_syslog("Ask a
default value
using common method getDefaultCreateValueForField on an
object with no property ->element defined. Return empty
string.
", LOG_WARNING);
5782 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5783 //var_dump($keyforfieldname);
5784 if (isset($conf->global->$keyforfieldname)) {
5785 return $conf->global->$keyforfieldname;
5788 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5795 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5806 public function call_trigger($triggerName, $user)
5809 global $langs, $conf;
5810 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5811 dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_
" as required.');
5814 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5815 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5816 $langs = new Translate('', $conf);
5819 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5820 $interface = new Interfaces($this->db);
5821 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5824 if (!empty($this->errors)) {
5825 $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.
5827 $this->errors = $interface->errors;
5834 /* Functions for data in other language */
5844 public function fetchValuesForExtraLanguages()
5846 // To avoid SQL errors. Probably not the better solution though
5847 if (!$this->element) {
5850 if (!($this->id > 0)) {
5853 if (is_array($this->array_languages)) {
5857 $this->array_languages = array();
5859 $element = $this->element;
5860 if ($element == 'categorie') {
5861 $element = 'categories'; // For compatibility
5864 // Request to get translation values for object
5865 $sql = "SELECT
rowid, property, lang , value
";
5866 $sql .= " FROM
".$this->db->prefix()."object_lang
";
5867 $sql .= " WHERE type_object =
'".$this->db->escape($element)."'";
5868 $sql .= " AND fk_object =
".((int) $this->id);
5870 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
5871 $resql = $this->db->query($sql);
5873 $numrows = $this->db->num_rows($resql);
5876 while ($i < $numrows) {
5877 $obj = $this->db->fetch_object($resql);
5878 $key = $obj->property;
5879 $value = $obj->value;
5880 $codelang = $obj->lang;
5881 $type = $this->fields[$key]['type'];
5883 // we can add this attribute to object
5884 if (preg_match('/date/', $type)) {
5885 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5887 $this->array_languages[$key][$codelang] = $value;
5894 $this->db->free($resql);
5902 dol_print_error($this->db);
5913 public function setValuesForExtraLanguages($onlykey = '')
5915 global $_POST, $langs;
5918 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5919 $tmparray = explode('-', $postfieldkey);
5920 if ($tmparray[0] != 'field') {
5924 $element = $tmparray[1];
5925 $key = $tmparray[2];
5926 $codelang = $tmparray[3];
5927 //var_dump("postfieldkey=
".$postfieldkey." element=
".$element." key=
".$key." codelang=
".$codelang);
5929 if (!empty($onlykey) && $key != $onlykey) {
5932 if ($element != $this->element) {
5936 $key_type = $this->fields[$key]['type'];
5939 if (isset($this->fields[$key]['enabled'])) {
5940 $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5943 if (isset($this->fields[$key]['perms']))
5945 $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5947 if (empty($enabled)) {
5950 //if (empty($perms)) continue;
5952 if (in_array($key_type, array('date'))) {
5954 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5955 $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month
", 'int'), GETPOST($postfieldkey."day
", 'int'), GETPOST($postfieldkey."year
", 'int'));
5956 } elseif (in_array($key_type, array('datetime'))) {
5958 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5959 $value_key = dol_mktime(GETPOST($postfieldkey."hour
", 'int'), GETPOST($postfieldkey."min
", 'int'), 0, GETPOST($postfieldkey."month
", 'int'), GETPOST($postfieldkey."day
", 'int'), GETPOST($postfieldkey."year
", 'int'));
5960 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5961 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5962 if (!empty($value_arr)) {
5963 $value_key = implode(',', $value_arr);
5967 } elseif (in_array($key_type, array('price', 'double'))) {
5968 $value_arr = GETPOST($postfieldkey, 'alpha');
5969 $value_key = price2num($value_arr);
5971 $value_key = GETPOST($postfieldkey);
5972 if (in_array($key_type, array('link')) && $value_key == '-1') {
5977 $this->array_languages[$key][$codelang] = $value_key;
5979 /*if ($nofillrequired) {
5980 $langs->load('errors');
5981 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5990 /* Functions for extrafields */
5998 public function fetchNoCompute($id)
6002 $savDisableCompute = $conf->disable_compute;
6003 $conf->disable_compute = 1;
6005 $ret = $this->fetch($id);
6007 $conf->disable_compute = $savDisableCompute;
6012 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6022 public function fetch_optionals($rowid = null, $optionsArray = null)
6025 global $conf, $extrafields;
6027 if (empty($rowid)) {
6030 if (empty($rowid) && isset($this->rowid)) {
6031 $rowid = $this->rowid; // deprecated
6034 // To avoid SQL errors. Probably not the better solution though
6035 if (!$this->table_element) {
6039 $this->array_options = array();
6041 if (!is_array($optionsArray)) {
6042 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6043 if (!isset($extrafields) || !is_object($extrafields)) {
6044 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6045 $extrafields = new ExtraFields($this->db);
6048 // Load array of extrafields for elementype = $this->table_element
6049 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6050 $extrafields->fetch_name_optionals_label($this->table_element);
6052 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6054 global $extrafields;
6055 dol_syslog("Warning:
fetch_optionals was called with param optionsArray defined when you should pass
null now
", LOG_WARNING);
6058 $table_element = $this->table_element;
6059 if ($table_element == 'categorie') {
6060 $table_element = 'categories'; // For compatibility
6063 // Request to get complementary values
6064 if (is_array($optionsArray) && count($optionsArray) > 0) {
6065 $sql = "SELECT
rowid";
6066 foreach ($optionsArray as $name => $label) {
6067 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6071 $sql .= " FROM
".$this->db->prefix().$table_element."_extrafields
";
6072 $sql .= " WHERE fk_object =
".((int) $rowid);
6074 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
6075 $resql = $this->db->query($sql);
6077 $numrows = $this->db->num_rows($resql);
6079 $tab = $this->db->fetch_array($resql);
6081 foreach ($tab as $key => $value) {
6082 // 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)
6083 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6084 // we can add this attribute to object
6085 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6086 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6087 $this->array_options["options_
".$key] = $this->db->jdate($value);
6089 $this->array_options["options_
".$key] = $value;
6092 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_
".$key]);
6097 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6098 // in the element's extrafields table)
6099 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6100 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6101 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6102 //var_dump($conf->disable_compute);
6103 if (empty($conf->disable_compute)) {
6104 global $objectoffield; // We set a global variable to $objectoffield so
6105 $objectoffield = $this; // we can use it inside computed formula
6106 $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6112 $this->db->free($resql);
6120 $this->errors[]=$this->db->lasterror;
6133 public function deleteExtraFields()
6137 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6143 $table_element = $this->table_element;
6144 if ($table_element == 'categorie') {
6145 $table_element = 'categories'; // For compatibility
6150 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6152 $resql = $this->db->query($sql_del);
6154 $this->error = $this->db->lasterror();
6155 $this->db->rollback();
6158 $this->db->commit();
6173 public function insertExtraFields($trigger = '', $userused = null)
6175 global $conf, $langs, $user;
6177 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6181 if (empty($userused)) {
6187 if (!empty($this->array_options)) {
6189 $langs->load('admin');
6190 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6191 $extrafields = new ExtraFields($this->db);
6192 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6194 // Eliminate copied source object extra fields that do not exist in target object
6195 $new_array_options = array();
6196 foreach ($this->array_options as $key => $value) {
6197 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6198 $new_array_options[$key] = $value;
6199 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6200 $new_array_options['options_'.$key] = $value;
6204 foreach ($new_array_options as $key => $value) {
6205 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6206 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6207 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6208 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6209 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6210 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6211 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6213 // If we clone, we have to clean unique extrafields to prevent duplicates.
6214 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6215 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6216 $new_array_options[$key] = null;
6219 // Similar code than into insertExtraFields
6220 if ($attributeRequired) {
6221 $mandatorypb = false;
6222 if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6223 $mandatorypb = true;
6225 if ($this->array_options[$key] === '') {
6226 $mandatorypb = true;
6228 if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6229 $mandatorypb = true;
6232 $langs->load("errors
");
6233 dol_syslog("Mandatory field
'".$key."' is empty during create and
set to required into definition of extrafields
");
6234 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6239 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6240 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6242 if (!empty($attrfieldcomputed)) {
6243 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6244 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6245 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6246 $new_array_options[$key] = $value;
6248 $new_array_options[$key] = null;
6252 switch ($attributeType) {
6254 if (!is_numeric($value) && $value != '') {
6255 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6257 } elseif ($value == '') {
6258 $new_array_options[$key] = null;
6263 $value = price2num($value);
6264 if (!is_numeric($value) && $value != '') {
6265 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." for ".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6266 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6268 } elseif ($value == '') {
6271 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6272 $new_array_options[$key] = $value;
6274 /*case 'select': // Not required, we chosed value='0' for undefined values
6277 $this->array_options[$key] = null;
6282 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6283 // If there is an encryption choice, we use it to crypt data before insert
6284 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6285 $algo = reset($tmparrays);
6287 //global $action; // $action may be 'create', 'update', 'update_extras'...
6288 //var_dump($action);
6289 //var_dump($this->oldcopy);exit;
6290 if (is_object($this->oldcopy)) { // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
6291 //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6292 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) { // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
6293 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6296 $newvalue = dol_hash($this->array_options[$key], $algo);
6297 $new_array_options[$key] = $newvalue;
6300 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6303 } else // Common usage
6305 $new_array_options[$key] = $this->array_options[$key];
6310 // If data is a string instead of a timestamp, we convert it
6311 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6312 $this->array_options[$key] = strtotime($this->array_options[$key]);
6314 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6317 $param_list = array_keys($attributeParam['options']);
6320 $InfoFieldList = explode(":
", $param_list[0]);
6321 dol_include_once($InfoFieldList[1]);
6322 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6323 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6324 $new_array_options[$key] = '';
6326 $object = new $InfoFieldList[0]($this->db);
6327 if (is_numeric($value)) {
6328 $res = $object->fetch($value); // Common case
6330 $res = $object->fetch('', $value); // For compatibility
6334 $new_array_options[$key] = $object->id;
6336 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6341 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6349 $table_element = $this->table_element;
6350 if ($table_element == 'categorie') {
6351 $table_element = 'categories'; // For compatibility
6354 dol_syslog(get_class($this)."::
insertExtraFields delete then insert
", LOG_DEBUG);
6356 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6357 $this->db->query($sql_del);
6359 $sql = "INSERT INTO
".$this->db->prefix().$table_element."_extrafields (fk_object
";
6360 foreach ($new_array_options as $key => $value) {
6361 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6362 // Add field of attribut
6363 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6364 $sql .= ",
".$attributeKey;
6367 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6368 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6369 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6370 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6371 $sql .= ",
".$tmpkey;
6375 $sql .= ") VALUES (
".$this->id;
6377 foreach ($new_array_options as $key => $value) {
6378 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6379 // Add field of attribute
6380 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6381 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6382 $sql .= ",
'".$this->db->escape($new_array_options[$key])."'";
6388 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6389 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6390 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6391 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6392 if (in_array($tmpval, array('int', 'double', 'price'))) {
6403 $resql = $this->db->query($sql);
6405 $this->error = $this->db->lasterror();
6409 if (!$error && $trigger) {
6411 $this->context = array('extrafieldaddupdate'=>1);
6412 $result = $this->call_trigger($trigger, $userused);
6420 $this->db->rollback();
6423 $this->db->commit();
6441 public function insertExtraLanguages($trigger = '', $userused = null)
6443 global $conf, $langs, $user;
6445 if (empty($userused)) {
6451 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6452 return 0; // For avoid conflicts if trigger used
6455 if (is_array($this->array_languages)) {
6456 $new_array_languages = $this->array_languages;
6458 foreach ($new_array_languages as $key => $value) {
6459 $attributeKey = $key;
6460 $attributeType = $this->fields[$attributeKey]['type'];
6461 $attributeLabel = $this->fields[$attributeKey]['label'];
6463 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6464 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6466 switch ($attributeType) {
6468 if (!is_numeric($value) && $value != '') {
6469 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6471 } elseif ($value == '') {
6472 $new_array_languages[$key] = null;
6476 $value = price2num($value);
6477 if (!is_numeric($value) && $value != '') {
6478 dol_syslog($langs->trans("ExtraLanguageHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6479 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6481 } elseif ($value == '') {
6482 $new_array_languages[$key] = null;
6484 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6485 $new_array_languages[$key] = $value;
6487 /*case 'select': // Not required, we chosed value='0' for undefined values
6490 $this->array_options[$key] = null;
6498 $table_element = $this->table_element;
6499 if ($table_element == 'categorie') {
6500 $table_element = 'categories'; // For compatibility
6505 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6506 foreach ($langcodearray as $langcode => $value) {
6507 $sql_del = "DELETE FROM
".$this->db->prefix()."object_lang
";
6508 $sql_del .= " WHERE fk_object =
".((int) $this->id)." AND property =
'".$this->db->escape($key)."' AND type_object =
'".$this->db->escape($table_element)."'";
6509 $sql_del .= " AND lang =
'".$this->db->escape($langcode)."'";
6510 $this->db->query($sql_del);
6512 if ($value !== '') {
6513 $sql = "INSERT INTO
".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value
";
6514 $sql .= ") VALUES (
".$this->id.",
'".$this->db->escape($key)."',
'".$this->db->escape($table_element)."',
'".$this->db->escape($langcode)."',
'".$this->db->escape($value)."'";
6517 $resql = $this->db->query($sql);
6519 $this->error = $this->db->lasterror();
6527 if (!$error && $trigger) {
6529 $this->context = array('extralanguagesaddupdate'=>1);
6530 $result = $this->call_trigger($trigger, $userused);
6538 $this->db->rollback();
6541 $this->db->commit();
6559 public function updateExtraField($key, $trigger = null, $userused = null)
6561 global $conf, $langs, $user;
6563 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6567 if (empty($userused)) {
6573 if (!empty($this->array_options) && isset($this->array_options["options_
".$key])) {
6575 $langs->load('admin');
6576 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6577 $extrafields = new ExtraFields($this->db);
6578 $extrafields->fetch_name_optionals_label($this->table_element);
6580 $value = $this->array_options["options_
".$key];
6582 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6583 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6584 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6585 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6586 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6588 // Similar code than into insertExtraFields
6589 if ($attributeRequired) {
6590 $mandatorypb = false;
6591 if ($attributeType == 'link' && $this->array_options["options_
".$key] == '-1') {
6592 $mandatorypb = true;
6594 if ($this->array_options["options_
".$key] === '') {
6595 $mandatorypb = true;
6598 $langs->load("errors
");
6599 dol_syslog("Mandatory field
'options_".$key."' is empty during update and
set to required into definition of extrafields
");
6600 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6605 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6606 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6608 if (!empty($attrfieldcomputed)) {
6609 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6610 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6611 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6612 $this->array_options["options_
".$key] = $value;
6614 $this->array_options["options_
".$key] = null;
6618 switch ($attributeType) {
6620 if (!is_numeric($value) && $value != '') {
6621 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6623 } elseif ($value === '') {
6624 $this->array_options["options_
".$key] = null;
6628 $value = price2num($value);
6629 if (!is_numeric($value) && $value != '') {
6630 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6631 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6633 } elseif ($value === '') {
6636 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6637 $this->array_options["options_
".$key] = $value;
6639 /*case 'select': // Not required, we chosed value='0' for undefined values
6642 $this->array_options[$key] = null;
6646 $this->array_options["options_
".$key] = price2num($this->array_options["options_
".$key]);
6650 if (empty($this->array_options["options_
".$key])) {
6651 $this->array_options["options_
".$key] = null;
6653 $this->array_options["options_
".$key] = $this->db->idate($this->array_options["options_
".$key]);
6657 if (empty($this->array_options["options_
".$key])) {
6658 $this->array_options["options_
".$key] = null;
6662 if ($this->array_options["options_
".$key] === '') {
6663 $this->array_options["options_
".$key] = null;
6668 $param_list = array_keys($attributeParam['options']);
6671 $InfoFieldList = explode(":
", $param_list[0]);
6672 dol_include_once($InfoFieldList[1]);
6673 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6675 if ($value == '-1') // -1 is key for no defined in combo list of objects
6677 $new_array_options[$key] = '';
6679 $object = new $InfoFieldList[0]($this->db);
6680 if (is_numeric($value)) $res = $object->fetch($value); // Common case
6681 else $res = $object->fetch('', $value); // For compatibility
6683 if ($res > 0) $new_array_options[$key] = $object->id;
6685 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6686 $this->db->rollback();
6691 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6699 $linealreadyfound = 0;
6701 // Check if there is already a line for this object (in most cases, it is, but sometimes it is not, for example when extra field has been created after), so we must keep this overload)
6702 $sql = "SELECT COUNT(
rowid) as nb FROM
".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6703 $resql = $this->db->query($sql);
6705 $tmpobj = $this->db->fetch_object($resql);
6707 $linealreadyfound = $tmpobj->nb;
6711 if ($linealreadyfound) {
6712 if ($this->array_options["options_
".$key] === null) {
6713 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
null";
6715 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
'".$this->db->escape($this->array_options["options_".$key])."'";
6717 $sql .= " WHERE fk_object =
".((int) $this->id);
6719 $result = $this->insertExtraFields('', $user);
6725 $resql = $this->db->query($sql);
6728 $this->error = $this->db->lasterror();
6730 if (!$error && $trigger) {
6732 $this->context = array('extrafieldupdate'=>1);
6733 $result = $this->call_trigger($trigger, $userused);
6741 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6742 $this->db->rollback();
6745 $this->db->commit();
6763 public function updateExtraLanguages($key, $trigger = null, $userused = null)
6765 global $conf, $langs, $user;
6767 if (empty($userused)) {
6773 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6774 return 0; // For avoid conflicts if trigger used
6795 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6797 global $conf, $langs, $form;
6799 if (!is_object($form)) {
6800 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6801 $form = new Form($this->db);
6804 if (!empty($this->fields)) {
6805 $val = $this->fields[$key];
6808 // Validation tests and output
6809 $fieldValidationErrorMsg = '';
6810 $validationClass = '';
6811 $fieldValidationErrorMsg = $this->getFieldError($key);
6812 if (!empty($fieldValidationErrorMsg)) {
6813 $validationClass = ' --error'; // the -- is use as class state in css : .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
6815 $validationClass = ' --success'; // the -- is use as class state in css : .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
6822 $param['options'] = array();
6824 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6825 // Because we work on extrafields
6826 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6827 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6829 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6830 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6832 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6833 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6835 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6836 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6838 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6839 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6841 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6842 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6844 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
6845 $param['options'] = array($reg[1] => 'N');
6847 } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6848 $param['options'] = array();
6851 } elseif (preg_match('/varchar/', $val['type'])) {
6852 $param['options'] = array();
6855 $param['options'] = array();
6856 $type = $this->fields[$key]['type'];
6859 // Special case that force options and type ($type can be integer, varchar, ...)
6860 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6861 $param['options'] = $this->fields[$key]['arrayofkeyval'];
6865 $label = $this->fields[$key]['label'];
6866 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6867 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6868 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6869 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6870 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6871 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6873 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6874 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6875 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6877 $objectid = $this->id;
6880 if (!preg_match('/^search_/', $keyprefix)) {
6881 return '<span class="opacitymedium
">'.$langs->trans("AutomaticallyCalculated
").'</span>';
6887 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6888 if (empty($morecss) && !empty($val['css'])) {
6889 $morecss = $val['css'];
6890 } elseif (empty($morecss)) {
6891 if ($type == 'date') {
6892 $morecss = 'minwidth100imp';
6893 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6894 $morecss = 'minwidth200imp';
6895 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6896 $morecss = 'maxwidth75';
6897 } elseif ($type == 'url') {
6898 $morecss = 'minwidth400';
6899 } elseif ($type == 'boolean') {
6902 if (round($size) < 12) {
6903 $morecss = 'minwidth100';
6904 } elseif (round($size) <= 48) {
6905 $morecss = 'minwidth200';
6907 $morecss = 'minwidth400';
6912 // Add validation state class
6913 if (!empty($validationClass)) {
6914 $morecss.= $validationClass;
6917 if (in_array($type, array('date'))) {
6918 $tmp = explode(',', $size);
6922 // Do not show current date when field not required (see selectDate() method)
6923 if (!$required && $value == '') {
6927 // TODO Must also support $moreparam
6928 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6929 } elseif (in_array($type, array('datetime'))) {
6930 $tmp = explode(',', $size);
6934 // Do not show current date when field not required (see selectDate() method)
6935 if (!$required && $value == '') $value = '-1';
6937 // TODO Must also support $moreparam
6938 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6939 } elseif (in_array($type, array('duration'))) {
6940 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6941 } elseif (in_array($type, array('int', 'integer'))) {
6942 $tmp = explode(',', $size);
6944 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($newsize > 0 ? ' maxlength="'.$newsize.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6945 } elseif (in_array($type, array('real'))) {
6946 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6947 } elseif (preg_match('/varchar/', $type)) {
6948 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6949 } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
6950 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6951 } elseif (preg_match('/^text/', $type)) {
6952 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6953 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6954 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6955 $out = $doleditor->Create(1);
6957 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6959 } elseif (preg_match('/^html/', $type)) {
6960 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6961 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6962 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6963 $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6965 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6967 } elseif ($type == 'boolean') {
6969 if (!empty($value)) {
6970 $checked = ' checked value="1
" ';
6972 $checked = ' value="1
" ';
6974 $out = '<input type="checkbox
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6975 } elseif ($type == 'price') {
6976 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6977 $value = price($value);
6979 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6980 } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6981 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6982 $value = price($value);
6984 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6985 } elseif ($type == 'select') {
6987 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6988 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6989 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6992 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6993 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6994 $out .= '<option value="0
"> </option>';
6996 foreach ($param['options'] as $keyb => $valb) {
6997 if ((string) $keyb == '') {
7000 if (strpos($valb, "|
") !== false) {
7001 list($valb, $parent) = explode('|', $valb);
7003 $out .= '<option value="'.$keyb.'"';
7004 $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
7005 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7006 $out .= '>'.$valb.'</option>';
7008 $out .= '</select>';
7009 } elseif ($type == 'sellist') {
7011 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
7012 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7013 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7016 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7017 if (is_array($param['options'])) {
7018 $param_list = array_keys($param['options']);
7019 $InfoFieldList = explode(":
", $param_list[0]);
7023 // 1 : label field name
7024 // 2 : key fields name (if differ of rowid)
7025 // 3 : key field parent (for dependent lists)
7026 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7027 // 5 : id category type
7028 // 6 : ids categories list separated by comma for category root
7029 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7031 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7032 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7033 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7035 $keyList = $InfoFieldList[2].' as rowid';
7038 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7039 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7040 $keyList .= ', '.$parentField;
7043 $filter_categorie = false;
7044 if (count($InfoFieldList) > 5) {
7045 if ($InfoFieldList[0] == 'categorie') {
7046 $filter_categorie = true;
7050 if ($filter_categorie === false) {
7051 $fields_label = explode('|', $InfoFieldList[1]);
7052 if (is_array($fields_label)) {
7054 $keyList .= implode(', ', $fields_label);
7058 $sql = "SELECT
" . $keyList;
7059 $sql .= " FROM
" . $this->db->prefix() . $InfoFieldList[0];
7060 if (!empty($InfoFieldList[4])) {
7061 // can use SELECT request
7062 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7063 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7066 // current object id can be use into filter
7067 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7068 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7070 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7073 //We have to join on extrafield table
7074 if (strpos($InfoFieldList[4], 'extra') !== false) {
7075 $sql .= " as main,
" . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra
";
7076 $sqlwhere .= " WHERE extra.fk_object=main.
" . $InfoFieldList[2] . " AND
" . $InfoFieldList[4];
7078 $sqlwhere .= " WHERE
" . $InfoFieldList[4];
7081 $sqlwhere .= ' WHERE 1=1';
7083 // Some tables may have field, some other not. For the moment we disable it.
7084 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7085 $sqlwhere .= " AND entity =
" . ((int) $conf->entity);
7090 $sql .= ' ORDER BY ' . implode(', ', $fields_label);
7092 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7093 $resql = $this->db->query($sql);
7095 $out .= '<option value="0
"> </option>';
7096 $num = $this->db->num_rows($resql);
7100 $obj = $this->db->fetch_object($resql);
7102 // Several field into label (eq table:code|libelle:rowid)
7104 $fields_label = explode('|', $InfoFieldList[1]);
7105 if (count($fields_label) > 1) {
7107 foreach ($fields_label as $field_toshow) {
7108 $labeltoshow .= $obj->$field_toshow . ' ';
7111 $labeltoshow = $obj->{$InfoFieldList[1]};
7113 $labeltoshow = dol_trunc($labeltoshow, 45);
7115 if ($value == $obj->rowid) {
7116 foreach ($fields_label as $field_toshow) {
7117 $translabel = $langs->trans($obj->$field_toshow);
7118 if ($translabel != $obj->$field_toshow) {
7119 $labeltoshow = dol_trunc($translabel) . ' ';
7121 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7124 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7127 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7128 if ($translabel != $obj->{$InfoFieldList[1]}) {
7129 $labeltoshow = dol_trunc($translabel, 18);
7131 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7134 if (empty($labeltoshow)) {
7135 $labeltoshow = '(not defined)';
7137 if ($value == $obj->rowid) {
7138 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7141 if (!empty($InfoFieldList[3]) && $parentField) {
7142 $parent = $parentName . ':' . $obj->{$parentField};
7146 $out .= '<option value="' . $obj->rowid . '"';
7147 $out .= ($value == $obj->rowid ? ' selected' : '');
7148 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7149 $out .= '>' . $labeltoshow . '</option>';
7154 $this->db->free($resql);
7156 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7159 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7160 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7161 $out .= '<option value="0
"> </option>';
7162 foreach ($data as $data_key => $data_value) {
7163 $out .= '<option value="' . $data_key . '"';
7164 $out .= ($value == $data_key ? ' selected' : '');
7165 $out .= '>' . $data_value . '</option>';
7169 $out .= '</select>';
7170 } elseif ($type == 'checkbox') {
7171 $value_arr = explode(',', $value);
7172 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7173 } elseif ($type == 'radio') {
7175 foreach ($param['options'] as $keyopt => $valopt) {
7176 $out .= '<input class="flat
'.$morecss.'" type="radio
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7177 $out .= ' value="'.$keyopt.'"';
7178 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'"';
7179 $out .= ($value == $keyopt ? 'checked' : '');
7180 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'">'.$valopt.'</label><br>';
7182 } elseif ($type == 'chkbxlst') {
7183 if (is_array($value)) {
7184 $value_arr = $value;
7186 $value_arr = explode(',', $value);
7189 if (is_array($param['options'])) {
7190 $param_list = array_keys($param['options']);
7191 $InfoFieldList = explode(":
", $param_list[0]);
7195 // 1 : label field name
7196 // 2 : key fields name (if differ of rowid)
7197 // 3 : key field parent (for dependent lists)
7198 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7199 // 5 : id category type
7200 // 6 : ids categories list separated by comma for category root
7201 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7203 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7204 list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7205 $keyList .= ', '.$parentField;
7207 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7208 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7209 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7211 $keyList = $InfoFieldList[2].' as rowid';
7215 $filter_categorie = false;
7216 if (count($InfoFieldList) > 5) {
7217 if ($InfoFieldList[0] == 'categorie') {
7218 $filter_categorie = true;