46 const TRIGGER_PREFIX =
'';
76 public $errors = array();
81 public $validateFieldsErrors = array();
91 public $element_for_permission;
96 public $table_element;
101 public $table_element_line =
'';
111 public $array_options = array();
116 public $array_languages =
null;
121 public $contacts_ids;
126 public $linked_objects;
131 public $linkedObjectsIds;
136 public $linkedObjects;
141 public $linkedObjectsFullLoaded = array();
151 protected $table_ref_field =
'';
156 public $restrictiononfksoc = 0;
164 public $context = array();
244 public $ref_previous;
285 public $country_code;
328 public $barcode_type;
334 public $barcode_type_code;
340 public $barcode_type_label;
346 public $barcode_type_coder;
352 public $mode_reglement_id;
358 public $cond_reglement_id;
363 public $demand_reason_id;
369 public $transport_mode_id;
376 public $cond_reglement;
383 public $fk_delivery_address;
389 public $shipping_method_id;
408 public $last_main_doc;
438 public $note_private;
462 public $total_localtax1;
468 public $total_localtax2;
485 public $comments = array();
511 public $date_creation;
516 public $date_validation;
521 public $date_modification;
526 public $date_cloture;
537 public $user_creation;
541 public $user_creation_id;
552 public $user_validation;
556 public $user_validation_id;
560 public $user_closing_id;
566 public $user_modification;
570 public $user_modification_id;
573 public $next_prev_filter;
578 public $specimen = 0;
594 protected $childtables = array();
601 protected $childtablesoncascade = array();
621 $sql =
"SELECT rowid, ref, ref_ext";
622 $sql .=
" FROM ".$db->prefix().$element;
623 $sql .=
" WHERE entity IN (".getEntity($element).
")";
626 $sql .=
" AND rowid = ".((int) $id);
628 $sql .=
" AND ref = '".$db->escape($ref).
"'";
629 } elseif ($ref_ext) {
630 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
632 $error =
'ErrorWrongParameters';
636 if ($ref || $ref_ext) {
637 $sql .=
" AND entity = ".((int) $conf->entity);
640 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
641 $resql = $db->query($sql);
643 $num = $db->num_rows(
$resql);
661 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
675 $parameters = array(
'objref'=>$objref);
677 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
679 return $hookmanager->resArray[
'objref'];
681 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
694 $parameters = array(
'objref'=>$objref);
696 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
698 return $hookmanager->resArray[
'objref'];
700 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
712 public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
715 $lastname = $this->lastname;
716 $firstname = $this->firstname;
717 if (empty($lastname)) {
718 $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 :
'')))));
722 if (!empty($option) && !empty($this->civility_code)) {
723 if ($langs->transnoentitiesnoconv(
"Civility".$this->civility_code) !=
"Civility".$this->civility_code) {
724 $ret .= $langs->transnoentitiesnoconv(
"Civility".$this->civility_code).
' ';
726 $ret .= $this->civility_code.
' ';
743 if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
749 if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
754 if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
768 $return =
'<div class="box-flex-item box-flex-grow-zero">';
769 $return .=
'<div class="info-box info-box-sm">';
770 $return .=
'<span class="info-box-icon bg-infobox-action">';
773 $return .=
'</span>';
774 $return .=
'<div class="info-box-content">';
775 $return .=
'<span class="info-box-ref">'.(method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref).
'</span>';
776 if (property_exists($this,
'label')) {
777 $return .=
'<br><span class="info-box-label opacitymedium">'.$this->label.
'</span>';
779 if (method_exists($this,
'getLibStatut')) {
780 $return .=
'<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).
'</div>';
798 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
800 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
801 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
802 $tmparray =
getCountry($this->country_id,
'all');
803 $this->country_code = $tmparray[
'code'];
804 $this->country = $tmparray[
'label'];
807 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
808 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
809 $tmparray =
getState($this->state_id,
'all', 0, 1);
810 $this->state_code = $tmparray[
'code'];
811 $this->state = $tmparray[
'label'];
812 $this->region_code = $tmparray[
'region_code'];
813 $this->region = $tmparray[
'region'];
829 global $conf, $langs,
$form, $extralanguages;
831 $countriesusingstate = array(
'AU',
'US',
'IN',
'GB',
'ES',
'UK',
'TR');
835 $elementforaltlanguage = $this->element;
836 if ($this->element ==
'societe') {
837 $thirdpartyid = $this->id;
839 if ($this->element ==
'contact') {
840 $contactid = $this->id;
841 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
843 if ($this->element ==
'user') {
844 $contactid = $this->contact_id;
845 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
851 $coords = $this->
getFullAddress(1,
', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
853 if (!empty($conf->use_javascript_ajax)) {
856 if ($this->element ==
'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
857 $namecoords .= $object->name.
'<br>';
859 $namecoords .= $this->
getFullName($langs, 1).
'<br>'.$coords;
861 $out .=
'<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).
'\',\
''.dol_escape_js($langs->trans(
"HelpCopyToClipboard")).
'\');
">';
862 $out .= img_picto($langs->trans("Address
"), 'map-marker-alt');
865 $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
869 // List of extra languages
870 $arrayoflangcode = array();
871 if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
872 $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
875 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
876 if (!is_object($extralanguages)) {
877 include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
878 $extralanguages = new ExtraLanguages($this->db);
880 $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
882 if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
883 $out .= "<!-- alternatelanguage
for '".$elementforaltlanguage."' set to fields
'".join(',
', $extralanguages->attributes[$elementforaltlanguage])."' -->\n
";
884 $this->fetchValuesForExtraLanguages();
885 if (!is_object($form)) {
886 $form = new Form($this->db);
889 // If there is extra languages
890 foreach ($arrayoflangcode as $extralangcode) {
891 $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright
"');
892 $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
893 $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
895 $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
900 if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
901 && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
902 if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
903 $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
905 $out .= ($outdone ? ' - ' : '').$this->state;
910 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)) {
911 $out .= ($outdone ? '<br>' : '');
913 if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
914 $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
917 if (!empty($this->phone_pro)) {
918 $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
921 if (!empty($this->phone_mobile)) {
922 $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
925 if (!empty($this->phone_perso)) {
926 $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso
"));
929 if (!empty($this->office_phone)) {
930 $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
933 if (!empty($this->user_mobile)) {
934 $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
937 if (!empty($this->fax)) {
938 $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
941 if (!empty($this->office_fax)) {
942 $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
947 $out .= '<div style="clear: both;
"></div>';
950 if (!empty($this->email)) {
951 $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
954 if (!empty($this->url)) {
955 //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
956 $out .= dol_print_url($this->url, '_blank', 0, 1);
960 if (!empty($conf->socialnetworks->enabled)) {
961 $outsocialnetwork = '';
963 if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
964 $socialnetworksdict = getArrayOfSocialNetworks();
965 foreach ($this->socialnetworks as $key => $value) {
967 $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
971 } else { // Old code to remove
972 if (!empty($this->skype)) {
973 $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
976 if (!empty($this->jabberid)) {
977 $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
980 if (!empty($this->twitter)) {
981 $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
984 if (!empty($this->facebook)) {
985 $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
988 if (!empty($this->linkedin)) {
989 $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
994 if ($outsocialnetwork) {
995 $out .= '<div style="clear: both;
">'.$outsocialnetwork.'</div>';
1000 return '<!-- BEGIN part to show address block -->'."\n
".$out.'<!-- END Part to show address block -->'."\n
";
1014 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1016 global $user, $dolibarr_main_url_root;
1018 if (empty($this->last_main_doc)) {
1019 return ''; // No way to known which document name to use
1022 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1023 $ecmfile = new EcmFiles($this->db);
1024 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1026 $this->error = $ecmfile->error;
1027 $this->errors = $ecmfile->errors;
1031 if (empty($ecmfile->id)) {
1032 // Add entry into index
1033 if ($initsharekey) {
1034 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1036 // 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
1038 $ecmfile->filepath = $rel_dir;
1039 $ecmfile->filename = $filename;
1040 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1041 $ecmfile->fullpath_orig = '';
1042 $ecmfile->gen_or_uploaded = 'generated';
1043 $ecmfile->description = ''; // indexed content
1044 $ecmfile->keywords = ''; // keyword content
1045 $ecmfile->share = getRandomPassword(true);
1046 $result = $ecmfile->create($user);
1049 $this->error = $ecmfile->error;
1050 $this->errors = $ecmfile->errors;
1056 } elseif (empty($ecmfile->share)) {
1057 // Add entry into index
1058 if ($initsharekey) {
1059 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1060 $ecmfile->share = getRandomPassword(true);
1061 $ecmfile->update($user);
1066 // Define $urlwithroot
1067 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1068 // This is to use external domain name found into config file
1069 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1071 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1072 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1077 //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1078 //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1079 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1080 if (!empty($ecmfile->share)) {
1081 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1083 if ($forcedownload) {
1084 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1087 if ($relativelink) {
1088 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1090 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1093 // Here $ecmfile->share is defined
1094 return $linktoreturn;
1098 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1108 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1111 global $user, $langs;
1114 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger
");
1117 if ($fk_socpeople <= 0) {
1118 $langs->load("errors
");
1119 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "1
");
1120 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1123 if (!$type_contact) {
1124 $langs->load("errors
");
1125 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "2
");
1126 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1130 $id_type_contact = 0;
1131 if (is_numeric($type_contact)) {
1132 $id_type_contact = $type_contact;
1134 // We look for id type_contact
1135 $sql = "SELECT tc.rowid
";
1136 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1137 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1138 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1139 $sql .= " AND tc.code=
'".$this->db->escape($type_contact)."' AND tc.active=1
";
1141 $resql = $this->db->query($sql);
1143 $obj = $this->db->fetch_object($resql);
1145 $id_type_contact = $obj->rowid;
1150 if ($id_type_contact == 0) {
1151 $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1152 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
");
1156 $datecreate = dol_now();
1158 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1159 $TListeContacts = $this->liste_contact(-1, $source);
1160 $already_added = false;
1161 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1162 foreach ($TListeContacts as $array_contact) {
1163 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1164 $already_added = true;
1170 if (!$already_added) {
1173 // Insert into database
1174 $sql = "INSERT INTO
".$this->db->prefix()."element_contact
";
1175 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact)
";
1176 $sql .= " VALUES (
".$this->id.",
".((int) $fk_socpeople)." ,
";
1177 $sql .= "'".$this->db->idate($datecreate)."'";
1178 $sql .= ", 4,
".((int) $id_type_contact);
1181 $resql = $this->db->query($sql);
1184 $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1186 $this->db->rollback();
1191 $this->db->commit();
1194 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1195 $this->error = $this->db->errno();
1196 $this->db->rollback();
1199 $this->error = $this->db->lasterror();
1200 $this->db->rollback();
1209 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217 public function copy_linked_contact($objFrom, $source = 'internal')
1220 $contacts = $objFrom->liste_contact(-1, $source);
1221 foreach ($contacts as $contact) {
1222 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1229 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1239 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1242 // Insert into database
1243 $sql = "UPDATE
".$this->db->prefix()."element_contact
set";
1244 $sql .= " statut =
".$statut;
1245 if ($type_contact_id) {
1246 $sql .= ", fk_c_type_contact =
".((int) $type_contact_id);
1248 if ($fk_socpeople) {
1249 $sql .= ", fk_socpeople =
".((int) $fk_socpeople);
1251 $sql .= " where
rowid =
".((int) $rowid);
1252 $resql = $this->db->query($sql);
1256 $this->error = $this->db->lasterror();
1261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1269 public function delete_contact($rowid, $notrigger = 0)
1277 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1278 $sql .= " WHERE
rowid =
".((int) $rowid);
1281 if ($this->db->query($sql)) {
1283 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1285 $this->db->rollback();
1290 $this->db->commit();
1293 $this->error = $this->db->lasterror();
1294 $this->db->rollback();
1299 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1307 public function delete_linked_contact($source = '', $code = '')
1312 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1314 if (!empty($typeContact)) {
1315 foreach ($typeContact as $key => $value) {
1316 array_push($temp, $key);
1318 $listId = implode(",
", $temp);
1321 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1322 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1323 if (empty($listId)) {
1327 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1328 $sql .= " WHERE element_id =
".((int) $this->id);
1329 $sql .= " AND fk_c_type_contact IN (
".$this->db->sanitize($listId).")
";
1332 if ($this->db->query($sql)) {
1335 $this->error = $this->db->lasterror();
1340 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1350 public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
1357 $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
1358 if ($source == 'internal') {
1359 $sql .= ",
'-1' as socid, t.statut as statuscontact, t.login, t.photo
";
1361 if ($source == 'external' || $source == 'thirdparty') {
1362 $sql .= ", t.fk_soc as socid, t.statut as statuscontact
";
1364 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email
";
1365 $sql .= ", tc.source, tc.element, tc.code, tc.libelle
";
1366 $sql .= " FROM
".$this->db->prefix()."c_type_contact tc
";
1367 $sql .= ",
".$this->db->prefix()."element_contact ec
";
1368 if ($source == 'internal') {
1369 $sql .= " LEFT JOIN
".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid
";
1371 if ($source == 'external' || $source == 'thirdparty') {
1372 $sql .= " LEFT JOIN
".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid
";
1374 $sql .= " WHERE ec.element_id =
".((int) $this->id);
1375 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1376 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1378 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1380 if ($source == 'internal') {
1381 $sql .= " AND tc.source =
'internal'";
1383 if ($source == 'external' || $source == 'thirdparty') {
1384 $sql .= " AND tc.source =
'external'";
1386 $sql .= " AND tc.active=1
";
1388 $sql .= " AND ec.statut =
".((int) $status);
1390 $sql .= " ORDER BY t.lastname ASC
";
1393 $resql = $this->db->query($sql);
1395 $num = $this->db->num_rows($resql);
1398 $obj = $this->db->fetch_object($resql);
1401 $transkey = "TypeContact_
".$obj->element."_
".$obj->source."_
".$obj->code;
1402 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1404 'source' => $obj->source,
1405 'socid' => $obj->socid,
1407 'nom' => $obj->lastname, // For backward compatibility
1408 'civility' => $obj->civility,
1409 'lastname' => $obj->lastname,
1410 'firstname' => $obj->firstname,
1411 'email'=>$obj->email,
1412 'login'=> (empty($obj->login) ? '' : $obj->login),
1413 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1414 'statuscontact' => $obj->statuscontact,
1415 'rowid' => $obj->rowid,
1416 'code' => $obj->code,
1417 'libelle' => $libelle_type,
1418 'status' => $obj->statuslink,
1419 'fk_c_type_contact' => $obj->fk_c_type_contact
1422 $tab[$i] = $obj->id;
1430 $this->error = $this->db->lasterror();
1431 dol_print_error($this->db);
1443 public function swapContactStatus($rowid)
1445 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,
";
1446 $sql .= " tc.code, tc.libelle
";
1447 $sql .= " FROM (
".$this->db->prefix()."element_contact as ec,
".$this->db->prefix()."c_type_contact as tc)
";
1448 $sql .= " WHERE ec.rowid =
".((int) $rowid);
1449 $sql .= " AND ec.fk_c_type_contact=tc.rowid
";
1450 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1453 $resql = $this->db->query($sql);
1455 $obj = $this->db->fetch_object($resql);
1456 $newstatut = ($obj->statut == 4) ? 5 : 4;
1457 $result = $this->update_contact($rowid, $newstatut);
1458 $this->db->free($resql);
1461 $this->error = $this->db->error();
1462 dol_print_error($this->db);
1467 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1478 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1483 if (empty($order)) {
1484 $order = 'position';
1486 if ($order == 'position') {
1491 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position
";
1492 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1493 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1494 if ($activeonly == 1) {
1495 $sql .= " AND tc.active=1
"; // only the active types
1497 if (!empty($source) && $source != 'all') {
1498 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1500 if (!empty($code)) {
1501 $sql .= " AND tc.code=
'".$this->db->escape($code)."'";
1503 $sql .= $this->db->order($order, 'ASC');
1505 //print "sql=
".$sql;
1506 $resql = $this->db->query($sql);
1508 $num = $this->db->num_rows($resql);
1511 $obj = $this->db->fetch_object($resql);
1513 $transkey = "TypeContact_
".$this->element."_
".$source."_
".$obj->code;
1514 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1515 if (empty($option)) {
1516 $tab[$obj->rowid] = $libelle_type;
1518 $tab[$obj->code] = $libelle_type;
1524 $this->error = $this->db->lasterror();
1525 //dol_print_error($this->db);
1530 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1542 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1545 global $langs, $conf;
1547 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1551 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element
";
1552 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1554 $sqlWhere = array();
1555 if (!empty($element)) {
1556 $sqlWhere[] = " tc.element=
'".$this->db->escape($element)."'";
1558 if (!empty($excludeelement)) {
1559 $sqlWhere[] = " tc.element <>
'".$this->db->escape($excludeelement)."'";
1562 if ($activeonly == 1) {
1563 $sqlWhere[] = " tc.active=1
"; // only the active types
1566 if (!empty($source) && $source != 'all') {
1567 $sqlWhere[] = " tc.source=
'".$this->db->escape($source)."'";
1570 if (!empty($code)) {
1571 $sqlWhere[] = " tc.code=
'".$this->db->escape($code)."'";
1574 if (count($sqlWhere) > 0) {
1575 $sql .= " WHERE
".implode(' AND ', $sqlWhere);
1578 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1580 dol_syslog(__METHOD__, LOG_DEBUG);
1581 $resql = $this->db->query($sql);
1583 $num = $this->db->num_rows($resql);
1585 $langs->loadLangs(array("propal
", "orders
", "bills
", "suppliers
", "contracts
", "supplier_proposal
"));
1587 while ($obj = $this->db->fetch_object($resql)) {
1588 $modulename = $obj->element;
1589 if (strpos($obj->element, 'project') !== false) {
1590 $modulename = 'projet';
1591 } elseif ($obj->element == 'contrat') {
1592 $element = 'contract';
1593 } elseif ($obj->element == 'action') {
1594 $modulename = 'agenda';
1595 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1596 $modulename = 'fournisseur';
1597 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1598 $modulename = 'fournisseur';
1600 if (!empty($conf->{$modulename}->enabled)) {
1601 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1602 $tmpelement = $obj->element;
1603 $transkey = "TypeContact_
".$tmpelement."_
".$source."_
".$obj->code;
1604 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1605 if (empty($option)) {
1606 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1608 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1615 $this->error = $this->db->lasterror();
1631 public function getIdContact($source, $code, $status = 0)
1637 //cas particulier pour les expeditions
1638 if ($this->element == 'shipping' && $this->origin_id != 0) {
1639 $id = $this->origin_id;
1640 $element = 'commande';
1641 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1642 $id = $this->origin_id;
1643 $element = 'order_supplier';
1646 $element = $this->element;
1649 $sql = "SELECT ec.fk_socpeople
";
1650 $sql .= " FROM
".$this->db->prefix()."element_contact as ec,
";
1651 if ($source == 'internal') {
1652 $sql .= " ".$this->db->prefix()."user as c,
";
1654 if ($source == 'external') {
1655 $sql .= " ".$this->db->prefix()."socpeople as c,
";
1657 $sql .= " ".$this->db->prefix()."c_type_contact as tc
";
1658 $sql .= " WHERE ec.element_id =
".((int) $id);
1659 $sql .= " AND ec.fk_socpeople = c.rowid
";
1660 if ($source == 'internal') {
1661 $sql .= " AND c.entity IN (
".getEntity('user').")
";
1663 if ($source == 'external') {
1664 $sql .= " AND c.entity IN (
".getEntity('societe').")
";
1666 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1667 $sql .= " AND tc.element =
'".$this->db->escape($element)."'";
1668 $sql .= " AND tc.source =
'".$this->db->escape($source)."'";
1670 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1672 $sql .= " AND tc.active = 1
";
1674 $sql .= " AND ec.statut =
".((int) $status);
1678 $resql = $this->db->query($sql);
1680 while ($obj = $this->db->fetch_object($resql)) {
1681 $result[$i] = $obj->fk_socpeople;
1685 $this->error = $this->db->error();
1692 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1699 public function fetch_contact($contactid = null)
1702 if (empty($contactid)) {
1703 $contactid = $this->contact_id;
1706 if (empty($contactid)) {
1710 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1711 $contact = new Contact($this->db);
1712 $result = $contact->fetch($contactid);
1713 $this->contact = $contact;
1717 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1724 public function fetch_thirdparty($force_thirdparty_id = 0)
1729 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1733 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1735 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1736 if ($force_thirdparty_id) {
1737 $idtofetch = $force_thirdparty_id;
1741 $thirdparty = new Societe($this->db);
1742 $result = $thirdparty->fetch($idtofetch);
1744 $this->errors=array_merge($this->errors, $thirdparty->errors);
1746 $this->thirdparty = $thirdparty;
1748 // Use first price level if level not defined for third party
1749 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1750 $this->thirdparty->price_level = 1;
1767 public function fetchOneLike($ref)
1769 if (!$this->table_ref_field) {
1773 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element." WHERE
".$this->table_ref_field." LIKE
'".$this->db->escape($ref)."' LIMIT 1
";
1775 $query = $this->db->query($sql);
1777 if (!$this->db->num_rows($query)) {
1781 $result = $this->db->fetch_object($query);
1783 return $this->fetch($result->rowid);
1786 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1794 public function fetch_barcode()
1799 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1801 $idtype = $this->barcode_type;
1802 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
1803 if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1804 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1805 } elseif ($this->element == 'societe') {
1806 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1808 dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1813 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
1814 $sql = "SELECT
rowid,
code, libelle as label, coder
";
1815 $sql .= " FROM
".$this->db->prefix()."c_barcode_type
";
1816 $sql .= " WHERE
rowid =
".((int) $idtype);
1817 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1818 $resql = $this->db->query($sql);
1820 $obj = $this->db->fetch_object($resql);
1821 $this->barcode_type = $obj->rowid;
1822 $this->barcode_type_code = $obj->code;
1823 $this->barcode_type_label = $obj->label;
1824 $this->barcode_type_coder = $obj->coder;
1827 dol_print_error($this->db);
1835 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1841 public function fetch_project()
1844 return $this->fetch_projet();
1847 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1853 public function fetch_projet()
1856 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1858 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1859 $this->fk_project = $this->fk_projet; // For backward compatibility
1861 if (empty($this->fk_project)) {
1865 $project = new Project($this->db);
1866 $result = $project->fetch($this->fk_project);
1868 $this->projet = $project; // deprecated
1869 $this->project = $project;
1873 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1879 public function fetch_product()
1882 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1884 if (empty($this->fk_product)) {
1888 $product = new Product($this->db);
1889 $result = $product->fetch($this->fk_product);
1891 $this->product = $product;
1895 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1902 public function fetch_user($userid)
1905 $user = new User($this->db);
1906 $result = $user->fetch($userid);
1907 $this->user = $user;
1911 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1917 public function fetch_origin()
1920 if ($this->origin == 'shipping') {
1921 $this->origin = 'expedition';
1923 if ($this->origin == 'delivery') {
1924 $this->origin = 'livraison';
1926 if ($this->origin == 'order_supplier') {
1927 $this->origin = 'commandeFournisseur';
1930 $origin = $this->origin;
1932 $classname = ucfirst($origin);
1933 $this->$origin = new $classname($this->db);
1934 $this->$origin->fetch($this->origin_id);
1946 public function fetchObjectFrom($table, $field, $key, $element = null)
1952 $sql = "SELECT
rowid FROM
".$this->db->prefix().$table;
1953 $sql .= " WHERE
".$field." =
'".$this->db->escape($key)."'";
1954 if (!empty($element)) {
1955 $sql .= " AND entity IN (
".getEntity($element).")
";
1957 $sql .= " AND entity =
".((int) $conf->entity);
1960 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1961 $resql = $this->db->query($sql);
1963 $row = $this->db->fetch_row($resql);
1964 // Test for avoid error -1
1966 $result = $this->fetch($row[0]);
1981 public function getValueFrom($table, $id, $field)
1984 if (!empty($id) && !empty($field) && !empty($table)) {
1985 $sql = "SELECT
".$field." FROM
".$this->db->prefix().$table;
1986 $sql .= " WHERE
rowid =
".((int) $id);
1988 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
1989 $resql = $this->db->query($sql);
1991 $row = $this->db->fetch_row($resql);
2014 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2016 global $user, $langs, $conf;
2018 if (empty($table)) {
2019 $table = $this->table_element;
2024 if (empty($format)) {
2027 if (empty($id_field)) {
2028 $id_field = 'rowid';
2036 if ($table == 'product' && $field == 'note_private') {
2039 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2040 $fk_user_field = 'fk_user_mod';
2043 $sql = "UPDATE
".$this->db->prefix().$table." SET
";
2045 if ($format == 'text') {
2046 $sql .= $field." =
'".$this->db->escape($value)."'";
2047 } elseif ($format == 'int') {
2048 $sql .= $field." =
".((int) $value);
2049 } elseif ($format == 'date') {
2050 $sql .= $field." =
".($value ? "'".$this->db->idate($value)."'" : "null");
2053 if ($fk_user_field) {
2054 if (!empty($fuser) && is_object($fuser)) {
2055 $sql .= ",
".$fk_user_field." =
".((int) $fuser->id);
2056 } elseif (empty($fuser) || $fuser != 'none') {
2057 $sql .= ",
".$fk_user_field." =
".((int) $user->id);
2061 $sql .= " WHERE
".$id_field." =
".((int) $id);
2063 dol_syslog(__METHOD__."", LOG_DEBUG);
2064 $resql = $this->db->query($sql);
2067 // call trigger with updated object values
2068 if (empty($this->fields) && method_exists($this, 'fetch')) {
2069 $result = $this->fetch($id);
2071 $result = $this->fetchCommon($id);
2074 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2082 if (property_exists($this, $field)) {
2083 $this->$field = $value;
2085 $this->db->commit();
2088 $this->db->rollback();
2092 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2093 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2095 $this->error = $this->db->lasterror();
2097 $this->db->rollback();
2102 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2111 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2114 global $conf, $user;
2116 if (!$this->table_element) {
2117 dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with
property table_element not defined
");
2120 if ($fieldid == 'none') {
2124 // For backward compatibility
2125 if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2129 // Security on socid
2131 if ($user->socid > 0) {
2132 $socid = $user->socid;
2135 // this->ismultientitymanaged contains
2136 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2137 $aliastablesociete = 's';
2138 if ($this->element == 'societe') {
2139 $aliastablesociete = 'te'; // te as table_element
2141 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2142 $sql = "SELECT MAX(te.
".$fieldid.")
";
2143 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2144 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2145 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2147 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2148 $tmparray = explode('@', $this->ismultientitymanaged);
2149 $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
2150 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2151 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2152 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2153 $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
2155 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2156 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2158 $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)
2159 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2160 $sql .= " AND sc.fk_user =
".((int) $user->id);
2162 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2163 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2165 if (!empty($filter)) {
2166 if (!preg_match('/^\s*AND/i', $filter)) {
2167 $sql .= " AND
"; // For backward compatibility
2171 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2172 $tmparray = explode('@', $this->ismultientitymanaged);
2173 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2174 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2175 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2177 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2178 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2179 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2180 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2182 $sql .= " AND ug.fk_user = te.rowid
";
2183 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2186 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2189 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2190 $tmparray = explode('@', $this->ismultientitymanaged);
2191 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2193 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2194 $sql .= ' AND te.fk_soc = '.((int) $socid);
2196 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2197 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2199 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2200 $sql .= ' AND te.rowid = '.((int) $socid);
2202 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2204 $result = $this->db->query($sql);
2206 $this->error = $this->db->lasterror();
2209 $row = $this->db->fetch_row($result);
2210 $this->ref_previous = $row[0];
2212 $sql = "SELECT MIN(te.
".$fieldid.")
";
2213 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2214 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2215 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2217 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2218 $tmparray = explode('@', $this->ismultientitymanaged);
2219 $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
2220 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2221 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2222 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2223 $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
2225 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2226 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2228 $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)
2229 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2230 $sql .= " AND sc.fk_user =
".((int) $user->id);
2232 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2233 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2235 if (!empty($filter)) {
2236 if (!preg_match('/^\s*AND/i', $filter)) {
2237 $sql .= " AND
"; // For backward compatibility
2241 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2242 $tmparray = explode('@', $this->ismultientitymanaged);
2243 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2244 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2245 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2247 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2248 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2249 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2250 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2252 $sql .= " AND ug.fk_user = te.rowid
";
2253 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2256 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2259 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2260 $tmparray = explode('@', $this->ismultientitymanaged);
2261 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2263 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2264 $sql .= ' AND te.fk_soc = '.((int) $socid);
2266 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2267 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2269 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2270 $sql .= ' AND te.rowid = '.((int) $socid);
2272 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2273 // 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
2275 $result = $this->db->query($sql);
2277 $this->error = $this->db->lasterror();
2280 $row = $this->db->fetch_row($result);
2281 $this->ref_next = $row[0];
2294 public function getListContactId($source = 'external')
2296 $contactAlreadySelected = array();
2297 $tab = $this->liste_contact(-1, $source);
2301 if ($source == 'thirdparty') {
2302 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2304 $contactAlreadySelected[$i] = $tab[$i]['id'];
2308 return $contactAlreadySelected;
2319 public function setProject($projectid, $notrigger = 0)
2324 if (!$this->table_element) {
2325 dol_syslog(get_class($this)."::
setProject was called on objet with property table_element not defined
", LOG_ERR);
2329 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2330 if (!empty($this->fields['fk_project'])) { // Common case
2332 $sql .= " SET fk_project =
".((int) $projectid);
2334 $sql .= " SET fk_project = NULL
";
2336 $sql .= ' WHERE rowid = '.((int) $this->id);
2337 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2339 $sql .= " SET fk_project =
".((int) $projectid);
2341 $sql .= " SET fk_project = NULL
";
2343 $sql .= ' WHERE id = '.((int) $this->id);
2344 } else // Special case for old architecture objects
2347 $sql .= ' SET fk_projet = '.((int) $projectid);
2349 $sql .= ' SET fk_projet = NULL';
2351 $sql .= " WHERE
rowid =
".((int) $this->id);
2356 dol_syslog(get_class($this)."::
setProject", LOG_DEBUG);
2357 if ($this->db->query($sql)) {
2358 $this->fk_project = ((int) $projectid);
2360 dol_print_error($this->db);
2365 if (!$error && !$notrigger) {
2367 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2370 } //Do also here what you must do to rollback action if trigger fail
2371 // End call triggers
2374 // Commit or rollback
2376 $this->db->rollback();
2379 $this->db->commit();
2390 public function setPaymentMethods($id)
2394 $error = 0; $notrigger = 0;
2396 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2398 if ($this->statut >= 0 || $this->element == 'societe') {
2399 // TODO uniformize field name
2400 $fieldname = 'fk_mode_reglement';
2401 if ($this->element == 'societe') {
2402 $fieldname = 'mode_reglement';
2404 if (get_class($this) == 'Fournisseur') {
2405 $fieldname = 'mode_reglement_supplier';
2407 if (get_class($this) == 'Tva') {
2408 $fieldname = 'fk_typepayment';
2410 if (get_class($this) == 'Salary') {
2411 $fieldname = 'fk_typepayment';
2414 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2415 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2416 $sql .= ' WHERE rowid='.((int) $this->id);
2418 if ($this->db->query($sql)) {
2419 $this->mode_reglement_id = $id;
2421 if (get_class($this) == 'Fournisseur') {
2422 $this->mode_reglement_supplier_id = $id;
2425 if (!$error && !$notrigger) {
2427 if (get_class($this) == 'Commande') {
2428 $result = $this->call_trigger('ORDER_MODIFY', $user);
2430 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2435 // End call triggers
2439 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2440 $this->error = $this->db->error();
2444 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2445 $this->error = 'Status of the object is incompatible '.$this->statut;
2456 public function setMulticurrencyCode($code)
2458 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2459 if ($this->statut >= 0 || $this->element == 'societe') {
2460 $fieldname = 'multicurrency_code';
2462 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2463 $sql .= " SET
".$fieldname." =
'".$this->db->escape($code)."'";
2464 $sql .= ' WHERE rowid='.((int) $this->id);
2466 if ($this->db->query($sql)) {
2467 $this->multicurrency_code = $code;
2469 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2471 $this->setMulticurrencyRate($rate, 2);
2476 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2477 $this->error = $this->db->error();
2481 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2482 $this->error = 'Status of the object is incompatible '.$this->statut;
2494 public function setMulticurrencyRate($rate, $mode = 1)
2496 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2497 if ($this->statut >= 0 || $this->element == 'societe') {
2498 $fieldname = 'multicurrency_tx';
2500 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2501 $sql .= " SET
".$fieldname." =
".((float) $rate);
2502 $sql .= ' WHERE rowid='.((int) $this->id);
2504 if ($this->db->query($sql)) {
2505 $this->multicurrency_tx = $rate;
2507 // Update line price
2508 if (!empty($this->lines)) {
2509 foreach ($this->lines as &$line) {
2510 // Amounts in company currency will be recalculated
2512 $line->subprice = 0;
2515 // Amounts in foreign currency will be recalculated
2517 $line->multicurrency_subprice = 0;
2520 switch ($this->element) {
2526 $line->remise_percent,
2528 $line->localtax1_tx,
2529 $line->localtax2_tx,
2530 ($line->description ? $line->description : $line->desc),
2533 $line->special_code,
2534 $line->fk_parent_line,
2535 $line->skip_update_total,
2536 $line->fk_fournprice,
2539 $line->product_type,
2542 $line->array_options,
2544 $line->multicurrency_subprice
2550 ($line->description ? $line->description : $line->desc),
2553 $line->remise_percent,
2555 $line->localtax1_tx,
2556 $line->localtax2_tx,
2561 $line->product_type,
2562 $line->fk_parent_line,
2563 $line->skip_update_total,
2564 $line->fk_fournprice,
2567 $line->special_code,
2568 $line->array_options,
2570 $line->multicurrency_subprice
2576 ($line->description ? $line->description : $line->desc),
2579 $line->remise_percent,
2583 $line->localtax1_tx,
2584 $line->localtax2_tx,
2587 $line->product_type,
2588 $line->fk_parent_line,
2589 $line->skip_update_total,
2590 $line->fk_fournprice,
2593 $line->special_code,
2594 $line->array_options,
2595 $line->situation_percent,
2597 $line->multicurrency_subprice
2600 case 'supplier_proposal':
2605 $line->remise_percent,
2607 $line->localtax1_tx,
2608 $line->localtax2_tx,
2609 ($line->description ? $line->description : $line->desc),
2612 $line->special_code,
2613 $line->fk_parent_line,
2614 $line->skip_update_total,
2615 $line->fk_fournprice,
2618 $line->product_type,
2619 $line->array_options,
2621 $line->multicurrency_subprice
2624 case 'order_supplier':
2627 ($line->description ? $line->description : $line->desc),
2630 $line->remise_percent,
2632 $line->localtax1_tx,
2633 $line->localtax2_tx,
2636 $line->product_type,
2640 $line->array_options,
2642 $line->multicurrency_subprice,
2646 case 'invoice_supplier':
2649 ($line->description ? $line->description : $line->desc),
2652 $line->localtax1_tx,
2653 $line->localtax2_tx,
2658 $line->product_type,
2659 $line->remise_percent,
2663 $line->array_options,
2665 $line->multicurrency_subprice,
2670 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2678 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2679 $this->error = $this->db->error();
2683 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2684 $this->error = 'Status of the object is incompatible '.$this->statut;
2696 public function setPaymentTerms($id, $deposit_percent = null)
2698 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2699 if ($this->statut >= 0 || $this->element == 'societe') {
2700 // TODO uniformize field name
2701 $fieldname = 'fk_cond_reglement';
2702 if ($this->element == 'societe') {
2703 $fieldname = 'cond_reglement';
2705 if (get_class($this) == 'Fournisseur') {
2706 $fieldname = 'cond_reglement_supplier';
2709 if (empty($deposit_percent) || $deposit_percent < 0) {
2710 $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2713 if ($deposit_percent > 100) {
2714 $deposit_percent = 100;
2717 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2718 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2719 if (in_array($this->table_element, array('propal', 'commande'))) {
2720 $sql .= " , deposit_percent =
" . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2722 $sql .= ' WHERE rowid='.((int) $this->id);
2724 if ($this->db->query($sql)) {
2725 $this->cond_reglement_id = $id;
2727 if (get_class($this) == 'Fournisseur') {
2728 $this->cond_reglement_supplier_id = $id;
2730 $this->cond_reglement = $id; // for compatibility
2731 $this->deposit_percent = $deposit_percent;
2734 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2735 $this->error = $this->db->error();
2739 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2740 $this->error = 'Status of the object is incompatible '.$this->statut;
2751 public function setTransportMode($id)
2753 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2754 if ($this->statut >= 0 || $this->element == 'societe') {
2755 $fieldname = 'fk_transport_mode';
2756 if ($this->element == 'societe') {
2757 $fieldname = 'transport_mode';
2759 if (get_class($this) == 'Fournisseur') {
2760 $fieldname = 'transport_mode_supplier';
2763 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2764 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2765 $sql .= ' WHERE rowid='.((int) $this->id);
2767 if ($this->db->query($sql)) {
2768 $this->transport_mode_id = $id;
2770 if (get_class($this) == 'Fournisseur') {
2771 $this->transport_mode_supplier_id = $id;
2775 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2776 $this->error = $this->db->error();
2780 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2781 $this->error = 'Status of the object is incompatible '.$this->statut;
2792 public function setRetainedWarrantyPaymentTerms($id)
2794 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2795 if ($this->statut >= 0 || $this->element == 'societe') {
2796 $fieldname = 'retained_warranty_fk_cond_reglement';
2798 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2799 $sql .= " SET
".$fieldname." =
".((int) $id);
2800 $sql .= ' WHERE rowid='.((int) $this->id);
2802 if ($this->db->query($sql)) {
2803 $this->retained_warranty_fk_cond_reglement = $id;
2806 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2807 $this->error = $this->db->error();
2811 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2812 $this->error = 'Status of the object is incompatible '.$this->statut;
2824 public function setDeliveryAddress($id)
2826 $fieldname = 'fk_delivery_address';
2827 if ($this->element == 'delivery' || $this->element == 'shipping') {
2828 $fieldname = 'fk_address';
2831 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET
".$fieldname." =
".((int) $id);
2832 $sql .= " WHERE
rowid =
".((int) $this->id)." AND fk_statut = 0
";
2834 if ($this->db->query($sql)) {
2835 $this->fk_delivery_address = $id;
2838 $this->error = $this->db->error();
2839 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2854 public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2858 if (empty($userused)) {
2864 if (!$this->table_element) {
2865 dol_syslog(get_class($this)."::
setShippingMethod was called on objet with property table_element not defined
", LOG_ERR);
2871 if ($shipping_method_id < 0) {
2872 $shipping_method_id = 'NULL';
2874 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2876 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2877 $sql .= " SET fk_shipping_method =
".((int) $shipping_method_id);
2878 $sql .= " WHERE
rowid=
".((int) $this->id);
2879 $resql = $this->db->query($sql);
2881 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2882 $this->error = $this->db->lasterror();
2887 $this->context = array('shippingmethodupdate'=>1);
2888 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2896 $this->db->rollback();
2899 $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2900 $this->db->commit();
2912 public function setWarehouse($warehouse_id)
2914 if (!$this->table_element) {
2915 dol_syslog(get_class($this)."::
setWarehouse was called on objet with property table_element not defined
", LOG_ERR);
2918 if ($warehouse_id < 0) {
2919 $warehouse_id = 'NULL';
2921 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2923 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2924 $sql .= " SET fk_warehouse =
".((int) $warehouse_id);
2925 $sql .= " WHERE
rowid=
".((int) $this->id);
2927 if ($this->db->query($sql)) {
2928 $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2931 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2932 $this->error = $this->db->error();
2945 public function setDocModel($user, $modelpdf)
2947 if (!$this->table_element) {
2948 dol_syslog(get_class($this)."::
setDocModel was called on objet with property table_element not defined
", LOG_ERR);
2952 $newmodelpdf = dol_trunc($modelpdf, 255);
2954 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2955 $sql .= " SET model_pdf =
'".$this->db->escape($newmodelpdf)."'";
2956 $sql .= " WHERE
rowid =
".((int) $this->id);
2958 dol_syslog(get_class($this)."::
setDocModel", LOG_DEBUG);
2959 $resql = $this->db->query($sql);
2961 $this->model_pdf = $modelpdf;
2962 $this->modelpdf = $modelpdf; // For bakward compatibility
2965 dol_print_error($this->db);
2979 public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2983 if (empty($userused)) {
2989 if (!$this->table_element) {
2990 dol_syslog(get_class($this)."::
setBankAccount was called on objet with property table_element not defined
", LOG_ERR);
2995 if ($fk_account < 0) {
2996 $fk_account = 'NULL';
2998 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3000 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3001 $sql .= " SET fk_account =
".((int) $fk_account);
3002 $sql .= " WHERE
rowid=
".((int) $this->id);
3004 $resql = $this->db->query($sql);
3006 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3007 $this->error = $this->db->lasterror();
3012 $this->context = array('bankaccountupdate'=>1);
3013 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3021 $this->db->rollback();
3024 $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3025 $this->db->commit();
3031 // TODO: Move line related operations to CommonObjectLine?
3033 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3043 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3046 if (!$this->table_element_line) {
3047 dol_syslog(get_class($this)."::
line_order was called on objet with property table_element_line not defined
", LOG_ERR);
3050 if (!$this->fk_element) {
3051 dol_syslog(get_class($this)."::
line_order was called on objet with property fk_element not defined
", LOG_ERR);
3055 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3056 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3057 $fieldposition = 'position';
3060 // Count number of lines to reorder (according to choice $renum)
3062 $sql = "SELECT count(
rowid) FROM
".$this->db->prefix().$this->table_element_line;
3063 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3065 $sql .= " AND
" . $fieldposition . " = 0
";
3068 $sql .= " AND
" . $fieldposition . " <> 0
";
3071 dol_syslog(get_class($this)."::
line_order", LOG_DEBUG);
3072 $resql = $this->db->query($sql);
3074 $row = $this->db->fetch_row($resql);
3077 dol_print_error($this->db);
3080 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3083 // We first search all lines that are parent lines (for multilevel details lines)
3084 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3085 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3086 if ($fk_parent_line) {
3087 $sql .= ' AND fk_parent_line IS NULL';
3089 $sql .= " ORDER BY
" . $fieldposition . " ASC,
rowid " . $rowidorder;
3091 dol_syslog(get_class($this)."::
line_order search all parent lines
", LOG_DEBUG);
3092 $resql = $this->db->query($sql);
3095 $num = $this->db->num_rows($resql);
3097 $row = $this->db->fetch_row($resql);
3098 $rows[] = $row[0]; // Add parent line into array rows
3099 $childrens = $this->getChildrenOfLine($row[0]);
3100 if (!empty($childrens)) {
3101 foreach ($childrens as $child) {
3102 array_push($rows, $child);
3108 // Now we set a new number for each lines (parent and children with children included into parent tree)
3109 if (!empty($rows)) {
3110 foreach ($rows as $key => $row) {
3111 $this->updateRangOfLine($row, ($key + 1));
3115 dol_print_error($this->db);
3128 public function getChildrenOfLine($id, $includealltree = 0)
3130 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3131 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3132 $fieldposition = 'position';
3137 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3138 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3139 $sql .= ' AND fk_parent_line = '.((int) $id);
3140 $sql .= " ORDER BY
" . $fieldposition . " ASC
";
3142 dol_syslog(get_class($this)."::
getChildrenOfLine search children lines
for line
".$id, LOG_DEBUG);
3143 $resql = $this->db->query($sql);
3145 if ($this->db->num_rows($resql) > 0) {
3146 while ($row = $this->db->fetch_row($resql)) {
3148 if (!empty($includealltree)) {
3149 $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3157 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3165 public function line_up($rowid, $fk_parent_line = true)
3168 $this->line_order(false, 'ASC', $fk_parent_line);
3171 $rang = $this->getRangOfLine($rowid);
3173 // Update position of line
3174 $this->updateLineUp($rowid, $rang);
3177 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3185 public function line_down($rowid, $fk_parent_line = true)
3188 $this->line_order(false, 'ASC', $fk_parent_line);
3191 $rang = $this->getRangOfLine($rowid);
3193 // Get max value for rang
3194 $max = $this->line_max();
3196 // Update position of line
3197 $this->updateLineDown($rowid, $rang, $max);
3207 public function updateRangOfLine($rowid, $rang)
3209 global $hookmanager;
3210 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3211 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3212 $fieldposition = 'position';
3215 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3216 $sql .= ' WHERE rowid = '.((int) $rowid);
3219 if (!$this->db->query($sql)) {
3220 dol_print_error($this->db);
3223 $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3225 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3230 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3237 public function line_ajaxorder($rows)
3240 $num = count($rows);
3241 for ($i = 0; $i < $num; $i++) {
3242 $this->updateRangOfLine($rows[$i], ($i + 1));
3253 public function updateLineUp($rowid, $rang)
3256 $fieldposition = 'rang';
3257 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3258 $fieldposition = 'position';
3261 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3262 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3263 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang - 1));
3264 if ($this->db->query($sql)) {
3265 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang - 1));
3266 $sql .= ' WHERE rowid = '.((int) $rowid);
3267 if (!$this->db->query($sql)) {
3268 dol_print_error($this->db);
3271 dol_print_error($this->db);
3284 public function updateLineDown($rowid, $rang, $max)
3287 $fieldposition = 'rang';
3288 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3289 $fieldposition = 'position';
3292 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3293 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3294 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang + 1));
3295 if ($this->db->query($sql)) {
3296 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang + 1));
3297 $sql .= ' WHERE rowid = '.((int) $rowid);
3298 if (!$this->db->query($sql)) {
3299 dol_print_error($this->db);
3302 dol_print_error($this->db);
3313 public function getRangOfLine($rowid)
3315 $fieldposition = 'rang';
3316 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3317 $fieldposition = 'position';
3320 $sql = "SELECT
" . $fieldposition . " FROM
".$this->db->prefix().$this->table_element_line;
3321 $sql .= " WHERE
rowid =
".((int) $rowid);
3324 $resql = $this->db->query($sql);
3326 $row = $this->db->fetch_row($resql);
3337 public function getIdOfLine($rang)
3339 $fieldposition = 'rang';
3340 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3341 $fieldposition = 'position';
3344 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3345 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3346 $sql .= " AND
" . $fieldposition . " =
".((int) $rang);
3347 $resql = $this->db->query($sql);
3349 $row = $this->db->fetch_row($resql);
3354 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3361 public function line_max($fk_parent_line = 0)
3364 $positionfield = 'rang';
3365 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3366 $positionfield = 'position';
3369 // Search the last rang with fk_parent_line
3370 if ($fk_parent_line) {
3371 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3372 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3373 $sql .= " AND fk_parent_line =
".((int) $fk_parent_line);
3375 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3376 $resql = $this->db->query($sql);
3378 $row = $this->db->fetch_row($resql);
3379 if (!empty($row[0])) {
3382 return $this->getRangOfLine($fk_parent_line);
3386 // If not, search the last rang of element
3387 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3388 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3390 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3391 $resql = $this->db->query($sql);
3393 $row = $this->db->fetch_row($resql);
3399 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3406 public function update_ref_ext($ref_ext)
3409 if (!$this->table_element) {
3410 dol_syslog(get_class($this)."::
update_ref_ext was called on objet with property table_element not defined
", LOG_ERR);
3414 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3415 $sql .= " SET ref_ext =
'".$this->db->escape($ref_ext)."'";
3416 $sql .= " WHERE
".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." =
".((int) $this->id);
3419 if ($this->db->query($sql)) {
3420 $this->ref_ext = $ref_ext;
3423 $this->error = $this->db->error();
3428 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3436 public function update_note($note, $suffix = '')
3441 if (!$this->table_element) {
3442 $this->error = 'update_note was called on objet with property table_element not defined';
3443 dol_syslog(get_class($this)."::
update_note was called on objet with property table_element not defined
", LOG_ERR);
3446 if (!in_array($suffix, array('', '_public', '_private'))) {
3447 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3448 dol_syslog(get_class($this)."::
update_note Parameter suffix must be empty,
'_private' or
'_public'", LOG_ERR);
3452 $newsuffix = $suffix;
3455 if ($this->table_element == 'product' && $newsuffix == '_private') {
3458 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3459 $fieldusermod = "fk_user_mod
";
3460 } elseif ($this->table_element == 'ecm_files') {
3461 $fieldusermod = "fk_user_m
";
3463 $fieldusermod = "fk_user_modif
";
3465 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3466 $sql .= " SET note
".$newsuffix." =
".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL
");
3467 $sql .= ",
".$fieldusermod." =
".((int) $user->id);
3468 $sql .= " WHERE
rowid =
".((int) $this->id);
3470 dol_syslog(get_class($this)."::
update_note", LOG_DEBUG);
3471 if ($this->db->query($sql)) {
3472 if ($suffix == '_public') {
3473 $this->note_public = $note;
3474 } elseif ($suffix == '_private') {
3475 $this->note_private = $note;
3477 $this->note = $note; // deprecated
3478 $this->note_private = $note;
3482 $this->error = $this->db->lasterror();
3487 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3496 public function update_note_public($note)
3499 return $this->update_note($note, '_public');
3502 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3513 public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3516 global $conf, $hookmanager, $action;
3518 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3519 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3521 return 1; // replacement code
3522 } elseif ($reshook < 0) {
3523 return -1; // failure
3524 } // reshook = 0 => execute normal code
3526 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3528 if ($this->element == 'propal') {
3529 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL
";
3530 } elseif ($this->element == 'commande' || $this->element == 'order') {
3531 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER
";
3532 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3533 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE
";
3534 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3535 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE
";
3536 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3537 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER
";
3538 } elseif ($this->element == 'supplier_proposal') {
3539 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL
";
3542 if (!empty($MODULE)) {
3543 if (!empty($conf->global->$MODULE)) {
3544 $modsactivated = explode(',', $conf->global->$MODULE);
3545 foreach ($modsactivated as $mod) {
3546 if ($conf->$mod->enabled) {
3547 return 1; // update was disabled by specific setup
3553 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3555 if ($roundingadjust == '-1') {
3556 $roundingadjust = 'auto'; // For backward compatibility
3559 $forcedroundingmode = $roundingadjust;
3560 if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3561 $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3562 } elseif ($forcedroundingmode == 'auto') {
3563 $forcedroundingmode = '0';
3568 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3570 // Define constants to find lines to sum
3571 $fieldtva = 'total_tva';
3572 $fieldlocaltax1 = 'total_localtax1';
3573 $fieldlocaltax2 = 'total_localtax2';
3574 $fieldup = 'subprice';
3575 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3579 if ($this->element == 'invoice_supplier_rec') {
3582 if ($this->element == 'expensereport') {
3583 $fieldup = 'value_unit';
3586 $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,
";
3587 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3588 if ($this->table_element_line == 'facturedet') {
3589 $sql .= ', situation_percent';
3591 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3592 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
3593 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3595 $product_field = 'product_type';
3596 if ($this->table_element_line == 'contratdet') {
3597 $product_field = ''; // contratdet table has no product_type field
3599 if ($product_field) {
3600 $sql .= " AND
".$product_field." <> 9
";
3603 $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
3605 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3606 $resql = $this->db->query($sql);
3608 $this->total_ht = 0;
3609 $this->total_tva = 0;
3610 $this->total_localtax1 = 0;
3611 $this->total_localtax2 = 0;
3612 $this->total_ttc = 0;
3613 $total_ht_by_vats = array();
3614 $total_tva_by_vats = array();
3615 $total_ttc_by_vats = array();
3616 $this->multicurrency_total_ht = 0;
3617 $this->multicurrency_total_tva = 0;
3618 $this->multicurrency_total_ttc = 0;
3620 $num = $this->db->num_rows($resql);
3623 $obj = $this->db->fetch_object($resql);
3625 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3626 $parameters = array('fk_element' => $obj->rowid);
3627 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3629 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'
3630 // This part of code is to fix data. We should not call it too often.
3631 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3632 $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);
3634 $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price adn unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3635 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3636 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
3637 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3639 if ($diff_when_using_price_ht && $diff_on_current_total) {
3640 $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);
3641 dol_syslog('We found unconsistent 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, LOG_WARNING);
3642 $resqlfix = $this->db->query($sqlfix);
3644 dol_print_error($this->db, 'Failed to update line');
3646 $obj->total_tva = $tmpcal[1];
3647 $obj->total_ttc = $tmpcal[2];
3651 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3652 $this->total_tva += $obj->total_tva;
3653 $this->total_localtax1 += $obj->total_localtax1;
3654 $this->total_localtax2 += $obj->total_localtax2;
3655 $this->total_ttc += $obj->total_ttc;
3656 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3657 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3658 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3660 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3661 $total_ht_by_vats[$obj->vatrate] = 0;
3663 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3664 $total_tva_by_vats[$obj->vatrate] = 0;
3666 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3667 $total_ttc_by_vats[$obj->vatrate] = 0;
3669 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3670 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3671 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3673 if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3674 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3675 $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3676 //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
";
3678 if (abs($diff) > 0.1) {
3679 $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.';
3680 dol_syslog($errmsg, LOG_WARNING);
3681 dol_print_error('', $errmsg);
3684 $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);
3685 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);
3687 $resqlfix = $this->db->query($sqlfix);
3690 dol_print_error($this->db, 'Failed to update line');
3693 $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3694 $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3695 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3696 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3703 // Add revenue stamp to total
3704 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3705 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3707 // Situations totals
3708 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3709 $prev_sits = $this->get_prev_sits();
3711 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3712 $this->total_ht -= $sit->total_ht;
3713 $this->total_tva -= $sit->total_tva;
3714 $this->total_localtax1 -= $sit->total_localtax1;
3715 $this->total_localtax2 -= $sit->total_localtax2;
3716 $this->total_ttc -= $sit->total_ttc;
3717 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3718 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3719 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3724 $this->total_ht = (float) price2num($this->total_ht);
3725 $this->total_tva = (float) price2num($this->total_tva);
3726 $this->total_localtax1 = (float) price2num($this->total_localtax1);
3727 $this->total_localtax2 = (float) price2num($this->total_localtax2);
3728 $this->total_ttc = (float) price2num($this->total_ttc);
3730 $this->db->free($resql);
3732 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
3733 $fieldht = 'total_ht';
3735 $fieldlocaltax1 = 'localtax1';
3736 $fieldlocaltax2 = 'localtax2';
3737 $fieldttc = 'total_ttc';
3738 // Specific code for backward compatibility with old field names
3739 if ($this->element == 'facture' || $this->element == 'facturerec') {
3740 $fieldtva = 'total_tva';
3742 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3743 $fieldtva = 'total_tva';
3745 if ($this->element == 'propal') {
3746 $fieldtva = 'total_tva';
3748 if ($this->element == 'expensereport') {
3749 $fieldtva = 'total_tva';
3751 if ($this->element == 'supplier_proposal') {
3752 $fieldtva = 'total_tva';
3754 if ($this->element == 'commande') {
3755 $fieldtva = 'total_tva';
3757 if ($this->element == 'order_supplier') {
3758 $fieldtva = 'total_tva';
3761 if (empty($nodatabaseupdate)) {
3762 $sql = "UPDATE
".$this->db->prefix().$this->table_element.' SET';
3763 $sql .= " ".$fieldht." =
".((float) price2num($this->total_ht, 'MT', 1)).",
";
3764 $sql .= " ".$fieldtva." =
".((float) price2num($this->total_tva, 'MT', 1)).",
";
3765 $sql .= " ".$fieldlocaltax1." =
".((float) price2num($this->total_localtax1, 'MT', 1)).",
";
3766 $sql .= " ".$fieldlocaltax2." =
".((float) price2num($this->total_localtax2, 'MT', 1)).",
";
3767 $sql .= " ".$fieldttc." =
".((float) price2num($this->total_ttc, 'MT', 1));
3768 $sql .= ", multicurrency_total_ht =
".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3769 $sql .= ", multicurrency_total_tva =
".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3770 $sql .= ", multicurrency_total_ttc =
".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3771 $sql .= " WHERE
rowid =
".((int) $this->id);
3773 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3774 $resql = $this->db->query($sql);
3778 $this->error = $this->db->lasterror();
3779 $this->errors[] = $this->db->lasterror();
3789 dol_print_error($this->db, 'Bad request in update_price');
3794 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3805 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3808 global $user, $hookmanager, $action;
3809 $origin = (!empty($origin) ? $origin : $this->origin);
3810 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3811 $f_user = isset($f_user) ? $f_user : $user;
3814 if ($origin == 'order') {
3815 $origin = 'commande';
3817 if ($origin == 'invoice') {
3818 $origin = 'facture';
3820 if ($origin == 'invoice_template') {
3821 $origin = 'facturerec';
3823 if ($origin == 'supplierorder') {
3824 $origin = 'order_supplier';
3827 // 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.
3828 // 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.
3829 $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3830 // Add module part to target type if object has $module property and isn't in core modules.
3831 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3833 $parameters = array('targettype'=>$targettype);
3834 // Hook for explicitly set the targettype if it must be differtent than $this->element
3835 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3837 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3843 $sql = "INSERT INTO
" . $this->db->prefix() . "element_element (
";
3844 $sql .= "fk_source
";
3845 $sql .= ", sourcetype
";
3846 $sql .= ", fk_target
";
3847 $sql .= ", targettype
";
3848 $sql .= ") VALUES (
";
3849 $sql .= ((int) $origin_id);
3850 $sql .= ",
'" . $this->db->escape($origin) . "'";
3851 $sql .= ",
" . ((int) $this->id);
3852 $sql .= ",
'" . $this->db->escape($targettype) . "'";
3856 if ($this->db->query($sql)) {
3859 $this->context['link_origin'] = $origin;
3860 $this->context['link_origin_id'] = $origin_id;
3861 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3865 // End call triggers
3868 $this->error = $this->db->lasterror();
3873 $this->db->commit();
3876 $this->db->rollback();
3903 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3905 global $conf, $hookmanager, $action;
3907 // Important for pdf generation time reduction
3908 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3909 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3913 $this->linkedObjectsIds = array();
3914 $this->linkedObjects = array();
3916 $justsource = false;
3917 $justtarget = false;
3918 $withtargettype = false;
3919 $withsourcetype = false;
3921 $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3922 // Hook for explicitly set the targettype if it must be differtent than $this->element
3923 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3925 if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3926 if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3927 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3928 if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3931 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3932 $justsource = true; // the source (id and type) is a search criteria
3933 if (!empty($targettype)) {
3934 $withtargettype = true;
3937 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3938 $justtarget = true; // the target (id and type) is a search criteria
3939 if (!empty($sourcetype)) {
3940 $withsourcetype = true;
3944 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3945 $targetid = (!empty($targetid) ? $targetid : $this->id);
3946 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3947 $targettype = (!empty($targettype) ? $targettype : $this->element);
3949 /*if (empty($sourceid) && empty($targetid))
3951 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3955 // Links between objects are stored in table element_element
3956 $sql = "SELECT
rowid, fk_source, sourcetype, fk_target, targettype
";
3957 $sql .= " FROM
".$this->db->prefix()."element_element
";
3959 if ($justsource || $justtarget) {
3961 $sql .= "fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3962 if ($withtargettype) {
3963 $sql .= " AND targettype =
'".$this->db->escape($targettype)."'";
3965 } elseif ($justtarget) {
3966 $sql .= "fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."'";
3967 if ($withsourcetype) {
3968 $sql .= " AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3972 $sql .= "(fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."')
";
3973 $sql .= " ".$clause." (fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."')
";
3974 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3975 $this->linkedObjectsFullLoaded[$this->id] = true;
3978 $sql .= " ORDER BY
".$orderby;
3980 dol_syslog(get_class($this)."::fetchObjectLink
", LOG_DEBUG);
3981 $resql = $this->db->query($sql);
3983 $num = $this->db->num_rows($resql);
3986 $obj = $this->db->fetch_object($resql);
3987 if ($justsource || $justtarget) {
3989 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3990 } elseif ($justtarget) {
3991 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3994 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
3995 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3997 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
3998 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4004 if (!empty($this->linkedObjectsIds)) {
4005 $tmparray = $this->linkedObjectsIds;
4006 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4007 // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4008 $module = $element = $subelement = $objecttype;
4010 if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4011 && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4012 $module = $element = $regs[1];
4013 $subelement = $regs[2];
4016 $classpath = $element.'/class';
4017 // To work with non standard classpath or module name
4018 if ($objecttype == 'facture') {
4019 $classpath = 'compta/facture/class';
4020 } elseif ($objecttype == 'facturerec') {
4021 $classpath = 'compta/facture/class';
4022 $module = 'facture';
4023 } elseif ($objecttype == 'propal') {
4024 $classpath = 'comm/propal/class';
4025 } elseif ($objecttype == 'supplier_proposal') {
4026 $classpath = 'supplier_proposal/class';
4027 } elseif ($objecttype == 'shipping') {
4028 $classpath = 'expedition/class';
4029 $subelement = 'expedition';
4030 $module = 'expedition_bon';
4031 } elseif ($objecttype == 'delivery') {
4032 $classpath = 'delivery/class';
4033 $subelement = 'delivery';
4034 $module = 'delivery_note';
4035 } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4036 $classpath = 'fourn/class';
4037 $module = 'fournisseur';
4038 } elseif ($objecttype == 'fichinter') {
4039 $classpath = 'fichinter/class';
4040 $subelement = 'fichinter';
4041 $module = 'ficheinter';
4042 } elseif ($objecttype == 'subscription') {
4043 $classpath = 'adherents/class';
4044 $module = 'adherent';
4045 } elseif ($objecttype == 'contact') {
4046 $module = 'societe';
4049 $classfile = strtolower($subelement);
4050 $classname = ucfirst($subelement);
4052 if ($objecttype == 'order') {
4053 $classfile = 'commande';
4054 $classname = 'Commande';
4055 } elseif ($objecttype == 'invoice_supplier') {
4056 $classfile = 'fournisseur.facture';
4057 $classname = 'FactureFournisseur';
4058 } elseif ($objecttype == 'order_supplier') {
4059 $classfile = 'fournisseur.commande';
4060 $classname = 'CommandeFournisseur';
4061 } elseif ($objecttype == 'supplier_proposal') {
4062 $classfile = 'supplier_proposal';
4063 $classname = 'SupplierProposal';
4064 } elseif ($objecttype == 'facturerec') {
4065 $classfile = 'facture-rec';
4066 $classname = 'FactureRec';
4067 } elseif ($objecttype == 'subscription') {
4068 $classfile = 'subscription';
4069 $classname = 'Subscription';
4070 } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4071 $classpath = 'projet/class';
4072 $classfile = 'project';
4073 $classname = 'Project';
4074 } elseif ($objecttype == 'conferenceorboothattendee') {
4075 $classpath = 'eventorganization/class';
4076 $classfile = 'conferenceorboothattendee';
4077 $classname = 'ConferenceOrBoothAttendee';
4078 $module = 'eventorganization';
4079 } elseif ($objecttype == 'conferenceorbooth') {
4080 $classpath = 'eventorganization/class';
4081 $classfile = 'conferenceorbooth';
4082 $classname = 'ConferenceOrBooth';
4083 $module = 'eventorganization';
4084 } elseif ($objecttype == 'mo') {
4085 $classpath = 'mrp/class';
4091 // Here $module, $classfile and $classname are set, we can use them.
4092 if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
4093 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4094 dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4095 //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4096 if (class_exists($classname)) {
4097 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4098 $object = new $classname($this->db);
4099 $ret = $object->fetch($objectid);
4101 $this->linkedObjects[$objecttype][$i] = $object;
4107 unset($this->linkedObjectsIds[$objecttype]);
4113 dol_print_error($this->db);
4124 public function clearObjectLinkedCache()
4126 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4127 unset($this->linkedObjectsFullLoaded[$this->id]);
4145 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4148 $updatesource = false;
4149 $updatetarget = false;
4150 $f_user = isset($f_user) ? $f_user : $user;
4152 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4153 $updatesource = true;
4154 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4155 $updatetarget = true;
4161 $sql = "UPDATE
" . $this->db->prefix() . "element_element SET
";
4162 if ($updatesource) {
4163 $sql .= "fk_source =
" . ((int) $sourceid);
4164 $sql .= ", sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4165 $sql .= " WHERE fk_target =
" . ((int) $this->id);
4166 $sql .= " AND targettype =
'" . $this->db->escape($this->element) . "'";
4167 } elseif ($updatetarget) {
4168 $sql .= "fk_target =
" . ((int) $targetid);
4169 $sql .= ", targettype =
'" . $this->db->escape($targettype) . "'";
4170 $sql .= " WHERE fk_source =
" . ((int) $this->id);
4171 $sql .= " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4175 if ($this->db->query($sql)) {
4178 $this->context['link_source_id'] = $sourceid;
4179 $this->context['link_source_type'] = $sourcetype;
4180 $this->context['link_target_id'] = $targetid;
4181 $this->context['link_target_type'] = $targettype;
4182 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4186 // End call triggers
4189 $this->error = $this->db->lasterror();
4194 $this->db->commit();
4197 $this->db->rollback();
4215 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4218 $deletesource = false;
4219 $deletetarget = false;
4220 $f_user = isset($f_user) ? $f_user : $user;
4222 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4223 $deletesource = true;
4224 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4225 $deletetarget = true;
4228 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4229 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4230 $targetid = (!empty($targetid) ? $targetid : $this->id);
4231 $targettype = (!empty($targettype) ? $targettype : $this->element);
4237 $this->context['link_id'] = $rowid;
4238 $this->context['link_source_id'] = $sourceid;
4239 $this->context['link_source_type'] = $sourcetype;
4240 $this->context['link_target_id'] = $targetid;
4241 $this->context['link_target_type'] = $targettype;
4242 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4246 // End call triggers
4250 $sql = "DELETE FROM
" . $this->db->prefix() . "element_element
";
4253 $sql .= " rowid =
" . ((int) $rowid);
4255 if ($deletesource) {
4256 $sql .= " fk_source =
" . ((int) $sourceid) . " AND sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4257 $sql .= " AND fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "'";
4258 } elseif ($deletetarget) {
4259 $sql .= " fk_target =
" . ((int) $targetid) . " AND targettype =
'" . $this->db->escape($targettype) . "'";
4260 $sql .= " AND fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4262 $sql .= " (fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "')
";
4264 $sql .= " (fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "')
";
4269 if (!$this->db->query($sql)) {
4270 $this->error = $this->db->lasterror();
4271 $this->errors[] = $this->error;
4277 $this->db->commit();
4280 $this->db->rollback();
4294 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4296 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4302 $sql = "SELECT
".$field_select." FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4303 $resql = $db->query($sql);
4306 if (!empty($resql)) {
4307 while ($res = $db->fetch_object($resql)) {
4308 $TRes[] = $res->{$field_select};
4323 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4325 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4331 $sql = "DELETE FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4332 $resql = $db->query($sql);
4334 if (empty($resql)) {
4351 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4353 global $user, $langs, $conf;
4355 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4357 $elementId = (!empty($elementId) ? $elementId : $this->id);
4358 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4362 if ($elementTable == 'facture_rec') {
4363 $fieldstatus = "suspended
";
4365 if ($elementTable == 'mailing') {
4366 $fieldstatus = "statut
";
4368 if ($elementTable == 'cronjob') {
4369 $fieldstatus = "status
";
4371 if ($elementTable == 'user') {
4372 $fieldstatus = "statut
";
4374 if ($elementTable == 'expensereport') {
4375 $fieldstatus = "fk_statut
";
4377 if ($elementTable == 'commande_fournisseur_dispatch') {
4378 $fieldstatus = "status
";
4380 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4381 $fieldstatus = 'status';
4384 $sql = "UPDATE
".$this->db->prefix().$elementTable;
4385 $sql .= " SET
".$fieldstatus." =
".((int) $status);
4386 // If status = 1 = validated, update also fk_user_valid
4387 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4388 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4389 $sql .= ", fk_user_valid =
".((int) $user->id);
4391 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4392 $sql .= ", date_valid =
'".$this->db->idate(dol_now())."'";
4394 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4395 $sql .= ", date_validation =
'".$this->db->idate(dol_now())."'";
4397 $sql .= " WHERE
rowid =
".((int) $elementId);
4398 $sql .= " AND
".$fieldstatus." <>
".((int) $status); // We avoid update if status already correct
4400 dol_syslog(get_class($this)."::
setStatut", LOG_DEBUG);
4401 $resql = $this->db->query($sql);
4405 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4407 if ($nb_rows_affected > 0) {
4408 if (empty($trigkey)) {
4409 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4410 if ($this->element == 'supplier_proposal' && $status == 2) {
4411 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4413 if ($this->element == 'supplier_proposal' && $status == 3) {
4414 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4416 if ($this->element == 'supplier_proposal' && $status == 4) {
4417 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4419 if ($this->element == 'fichinter' && $status == 3) {
4420 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4422 if ($this->element == 'fichinter' && $status == 2) {
4423 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4425 if ($this->element == 'fichinter' && $status == 1) {
4426 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4432 $result = $this->call_trigger($trigkey, $user);
4436 // End call triggers
4439 // The status was probably already good. We do nothing more, no triggers.
4443 $this->db->commit();
4445 if (empty($savElementId)) {
4446 // If the element we update is $this (so $elementId was provided as null)
4447 if ($fieldstatus == 'tosell') {
4448 $this->status = $status;
4449 } elseif ($fieldstatus == 'tobuy') {
4450 $this->status_buy = $status;
4452 $this->statut = $status;
4453 $this->status = $status;
4459 $this->db->rollback();
4460 dol_syslog(get_class($this)."::
setStatut ".$this->error, LOG_ERR);
4464 $this->error = $this->db->lasterror();
4465 $this->db->rollback();
4478 public function getCanvas($id = 0, $ref = '')
4482 if (empty($id) && empty($ref)) {
4485 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4486 return 0; // To increase speed. Not enabled by default.
4492 $sql = "SELECT
rowid, canvas
";
4493 $sql .= " FROM
".$this->db->prefix().$this->table_element;
4494 $sql .= " WHERE entity IN (
".getEntity($this->element).")
";
4496 $sql .= " AND
rowid =
".((int) $id);
4499 $sql .= " AND
ref =
'".$this->db->escape($ref)."'";
4502 $resql = $this->db->query($sql);
4504 $obj = $this->db->fetch_object($resql);
4506 $this->canvas = $obj->canvas;
4512 dol_print_error($this->db);
4524 public function getSpecialCode($lineid)
4526 $sql = "SELECT special_code FROM
".$this->db->prefix().$this->table_element_line;
4527 $sql .= " WHERE
rowid =
".((int) $lineid);
4528 $resql = $this->db->query($sql);
4530 $row = $this->db->fetch_row($resql);
4543 public function isObjectUsed($id = 0, $entity = 0)
4552 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4553 dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4557 $arraytoscan = $this->childtables;
4558 // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4559 $tmparray = array_keys($this->childtables);
4560 if (is_numeric($tmparray[0])) {
4561 $arraytoscan = array_flip($this->childtables);
4564 // Test if child exists
4566 foreach ($arraytoscan as $table => $element) {
4567 //print $id.'-'.$table.'-'.$elementname.'<br>';
4568 // Check if element can be deleted
4569 $sql = "SELECT COUNT(*) as nb
";
4570 $sql.= " FROM
".$this->db->prefix().$table." as c
";
4571 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4572 $sql.= ",
".$this->db->prefix().$element['parent']." as p
";
4574 $sql.= " WHERE c.
".$this->fk_element." =
".((int) $id);
4575 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4576 $sql.= " AND c.
".$element['parentkey']." = p.rowid
";
4578 if (!empty($entity)) {
4579 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4580 $sql.= " AND p.entity =
".((int) $entity);
4582 $sql.= " AND c.entity =
".((int) $entity);
4585 $resql = $this->db->query($sql);
4587 $obj = $this->db->fetch_object($resql);
4589 $langs->load("errors
");
4590 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4591 $haschild += $obj->nb;
4592 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4593 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4594 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4595 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4596 } else { // new usage: $element['name']=Translation key
4597 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4599 break; // We found at least one, we stop here
4602 $this->errors[] = $this->db->lasterror();
4606 if ($haschild > 0) {
4607 $this->errors[] = "ErrorRecordHasChildren
";
4620 public function hasProductsOrServices($predefined = -1)
4624 foreach ($this->lines as $key => $val) {
4626 if ($predefined == -1) {
4629 if ($predefined == 1 && $val->fk_product > 0) {
4632 if ($predefined == 0 && $val->fk_product <= 0) {
4635 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4638 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4645 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4654 public function getTotalDiscount()
4656 if (!empty($this->table_element_line) ) {
4657 $total_discount = 0.00;
4659 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht
";
4660 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
4661 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
4663 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4664 $resql = $this->db->query($sql);
4666 $num = $this->db->num_rows($resql);
4669 $obj = $this->db->fetch_object($resql);
4671 $pu_ht = $obj->pu_ht;
4673 $total_ht = $obj->total_ht;
4675 $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4676 $total_discount += $total_discount_line;
4682 //print $total_discount; exit;
4683 return price2num($total_discount);
4696 public function getTotalWeightVolume()
4700 // defined for shipment only
4702 // defined for shipment only
4705 foreach ($this->lines as $line) {
4706 if (isset($line->qty_asked)) {
4707 if (empty($totalOrdered)) {
4708 $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4710 $totalOrdered += $line->qty_asked; // defined for shipment only
4712 if (isset($line->qty_shipped)) {
4713 if (empty($totalToShip)) {
4714 $totalToShip = 0; // Avoid warning because $totalToShip is ''
4716 $totalToShip += $line->qty_shipped; // defined for shipment only
4717 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4718 if (empty($totalToShip)) {
4721 $totalToShip += $line->qty; // defined for reception only
4724 // Define qty, weight, volume, weight_units, volume_units
4725 if ($this->element == 'shipping') {
4727 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4729 $qty = $line->qty ? $line->qty : 0;
4732 $weight = !empty($line->weight) ? $line->weight : 0;
4733 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4734 $volume = !empty($line->volume) ? $line->volume : 0;
4735 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4737 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4738 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4739 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4740 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4744 if (!empty($weight_units)) {
4745 $weightUnit = $weight_units;
4747 if (!empty($volume_units)) {
4748 $volumeUnit = $volume_units;
4751 if (empty($totalWeight)) {
4752 $totalWeight = 0; // Avoid warning because $totalWeight is ''
4754 if (empty($totalVolume)) {
4755 $totalVolume = 0; // Avoid warning because $totalVolume is ''
4758 //var_dump($line->volume_units);
4759 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4760 $trueWeightUnit = pow(10, $weightUnit);
4761 $totalWeight += $weight * $qty * $trueWeightUnit;
4763 if ($weight_units == 99) {
4764 // conversion 1 Pound = 0.45359237 KG
4765 $trueWeightUnit = 0.45359237;
4766 $totalWeight += $weight * $qty * $trueWeightUnit;
4767 } elseif ($weight_units == 98) {
4768 // conversion 1 Ounce = 0.0283495 KG
4769 $trueWeightUnit = 0.0283495;
4770 $totalWeight += $weight * $qty * $trueWeightUnit;
4772 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4775 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4776 //print $line->volume."x
".$line->volume_units."x
".($line->volume_units < 50)."x
".$volumeUnit;
4777 $trueVolumeUnit = pow(10, $volumeUnit);
4778 //print $line->volume;
4779 $totalVolume += $volume * $qty * $trueVolumeUnit;
4781 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4785 return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4794 public function setExtraParameters()
4798 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4800 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
4801 $sql .= " SET extraparams =
".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4802 $sql .= " WHERE
rowid =
".((int) $this->id);
4805 $resql = $this->db->query($sql);
4807 $this->error = $this->db->lasterror();
4808 $this->db->rollback();
4811 $this->db->commit();
4817 // --------------------
4818 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4819 // --------------------
4821 /* This is to show add lines */
4832 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4834 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4838 if (!is_object($extrafields)) {
4839 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4840 $extrafields = new ExtraFields($this->db);
4842 $extrafields->fetch_name_optionals_label($this->table_element_line);
4844 // Output template part (modules that overwrite templates must declare this into descriptor)
4845 // Use global variables + $dateSelector + $seller and $buyer
4846 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4847 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4848 foreach ($dirtpls as $module => $reldir) {
4849 if (!empty($module)) {
4850 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4852 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4855 if (empty($conf->file->strict_mode)) {
4856 $res = @include $tpl;
4858 $res = include $tpl; // for debug
4868 /* This is to show array of line of details */
4885 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4887 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4888 // TODO We should not use global var for this
4889 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4891 // Define usemargins
4893 if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4897 $num = count($this->lines);
4900 if (!is_object($extrafields)) {
4901 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4902 $extrafields = new ExtraFields($this->db);
4904 $extrafields->fetch_name_optionals_label($this->table_element_line);
4906 $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4907 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4908 if (empty($reshook)) {
4909 // Output template part (modules that overwrite templates must declare this into descriptor)
4910 // Use global variables + $dateSelector + $seller and $buyer
4911 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4912 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4913 foreach ($dirtpls as $module => $reldir) {
4914 if (!empty($module)) {
4915 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4917 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4919 if (empty($conf->file->strict_mode)) {
4920 $res = @include $tpl;
4922 $res = include $tpl; // for debug
4933 foreach ($this->lines as $line) {
4935 $line->fetch_optionals();
4937 //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4938 if (is_object($hookmanager)) { // Old code is commented on preceding line.
4939 if (empty($line->fk_parent_line)) {
4940 $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4941 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4943 $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);
4944 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4947 if (empty($reshook)) {
4948 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4973 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4975 global $conf, $langs, $user, $object, $hookmanager;
4977 global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4979 $object_rights = $this->getRights();
4981 $element = $this->element;
4986 // Line in view mode
4987 if ($action != 'editline' || $selected != $line->id) {
4989 if ($line->fk_product > 0) {
4990 $product_static = new Product($this->db);
4991 $product_static->fetch($line->fk_product);
4993 $product_static->ref = $line->ref; //can change ref in hook
4994 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
4996 $text = $product_static->getNomUrl(1);
4998 // Define output language and label
4999 if (!empty($conf->global->MAIN_MULTILANGS)) {
5000 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5001 dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5005 $prod = new Product($this->db);
5006 $prod->fetch($line->fk_product);
5008 $outputlangs = $langs;
5010 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5011 $newlang = GETPOST('lang_id', 'aZ09');
5013 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5014 $newlang = $this->thirdparty->default_lang; // To use language of customer
5016 if (!empty($newlang)) {
5017 $outputlangs = new Translate("", $conf);
5018 $outputlangs->setDefaultLang($newlang);
5021 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label
"])) ? $prod->multilangs[$outputlangs->defaultlang]["label
"] : $line->product_label;
5023 $label = $line->product_label;
5026 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5027 $description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5030 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5032 // Output template part (modules that overwrite templates must declare this into descriptor)
5033 // Use global variables + $dateSelector + $seller and $buyer
5034 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5035 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5036 foreach ($dirtpls as $module => $reldir) {
5037 if (!empty($module)) {
5038 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5040 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5043 if (empty($conf->file->strict_mode)) {
5044 $res = @include $tpl;
5046 $res = include $tpl; // for debug
5054 // Line in update mode
5055 if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5056 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5058 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5060 // Output template part (modules that overwrite templates must declare this into descriptor)
5061 // Use global variables + $dateSelector + $seller and $buyer
5062 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5063 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5064 foreach ($dirtpls as $module => $reldir) {
5065 if (!empty($module)) {
5066 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5068 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5071 if (empty($conf->file->strict_mode)) {
5072 $res = @include $tpl;
5074 $res = include $tpl; // for debug
5084 /* This is to show array of line of details of source object */
5097 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5099 global $langs, $hookmanager, $conf, $form, $action;
5101 print '<tr class="liste_titre
">';
5102 print '<td class="linecolref
">'.$langs->trans('Ref').'</td>';
5103 print '<td class="linecoldescription
">'.$langs->trans('Description').'</td>';
5104 print '<td class="linecolvat right
">'.$langs->trans('VATRate').'</td>';
5105 print '<td class="linecoluht right
">'.$langs->trans('PriceUHT').'</td>';
5106 if (!empty($conf->multicurrency->enabled)) {
5107 print '<td class="linecoluht_currency right
">'.$langs->trans('PriceUHTCurrency').'</td>';
5109 print '<td class="linecolqty right
">'.$langs->trans('Qty').'</td>';
5110 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5111 print '<td class="linecoluseunit left
">'.$langs->trans('Unit').'</td>';
5113 print '<td class="linecoldiscount right
">'.$langs->trans('ReductionShort').'</td>';
5114 print '<td class="linecolht right
">'.$langs->trans('TotalHT').'</td>';
5115 print '<td class="center
">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5119 if (!empty($this->lines)) {
5120 foreach ($this->lines as $line) {
5122 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5123 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5124 $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5125 if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5126 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5128 if (empty($reshook)) {
5129 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5150 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5152 global $langs, $conf;
5155 if (!empty($line->date_start)) {
5156 $date_start = $line->date_start;
5158 $date_start = $line->date_debut_prevue;
5159 if ($line->date_debut_reel) {
5160 $date_start = $line->date_debut_reel;
5163 if (!empty($line->date_end)) {
5164 $date_end = $line->date_end;
5166 $date_end = $line->date_fin_prevue;
5167 if ($line->date_fin_reel) {
5168 $date_end = $line->date_fin_reel;
5172 $this->tpl['id'] = $line->id;
5174 $this->tpl['label'] = '';
5175 if (!empty($line->fk_parent_line)) {
5176 $this->tpl['label'] .= img_picto('', 'rightarrow');
5179 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5180 $discount = new DiscountAbsolute($this->db);
5181 $discount->fk_soc = $this->socid;
5182 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5183 } elseif (!empty($line->fk_product)) {
5184 $productstatic = new Product($this->db);
5185 $productstatic->id = $line->fk_product;
5186 $productstatic->ref = $line->ref;
5187 $productstatic->type = $line->fk_product_type;
5188 if (empty($productstatic->ref)) {
5189 $line->fetch_product();
5190 $productstatic = $line->product;
5193 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5194 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5196 if ($line->product_type == 1 && ($date_start || $date_end)) {
5197 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5200 $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5201 if (!empty($line->desc)) {
5202 $this->tpl['label'] .= $line->desc;
5204 $this->tpl['label'] .= ($line->label ? ' '.$line->label : '');
5208 if ($line->product_type == 1 && ($date_start || $date_end)) {
5209 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5213 if (!empty($line->desc)) {
5214 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5215 $discount = new DiscountAbsolute($this->db);
5216 $discount->fetch($line->fk_remise_except);
5217 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote
", $discount->getNomUrl(0));
5218 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5219 $discount = new DiscountAbsolute($this->db);
5220 $discount->fetch($line->fk_remise_except);
5221 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit
", $discount->getNomUrl(0));
5222 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5223 $discount = new DiscountAbsolute($this->db);
5224 $discount->fetch($line->fk_remise_except);
5225 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived
", $discount->getNomUrl(0));
5226 } elseif ($line->desc == '(EXCESS PAID)') {
5227 $discount = new DiscountAbsolute($this->db);
5228 $discount->fetch($line->fk_remise_except);
5229 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid
", $discount->getNomUrl(0));
5231 $this->tpl['description'] = dol_trunc($line->desc, 60);
5234 $this->tpl['description'] = ' ';
5238 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5239 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5240 if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5241 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5244 $this->tpl['price'] = price($line->subprice);
5245 $this->tpl['total_ht'] = price($line->total_ht);
5246 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5247 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' ';
5248 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5249 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5251 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' ';
5253 // Is the line strike or not
5254 $this->tpl['strike'] = 0;
5255 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5256 $this->tpl['strike'] = 1;
5259 // Output template part (modules that overwrite templates must declare this into descriptor)
5260 // Use global variables + $dateSelector + $seller and $buyer
5261 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5262 foreach ($dirtpls as $module => $reldir) {
5263 if (!empty($module)) {
5264 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5266 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5269 if (empty($conf->file->strict_mode)) {
5270 $res = @include $tpl;
5272 $res = include $tpl; // for debug
5281 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5292 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5297 $sql = "INSERT INTO
".$this->db->prefix()."element_resources (
";
5298 $sql .= "resource_id
";
5299 $sql .= ", resource_type
";
5300 $sql .= ", element_id
";
5301 $sql .= ", element_type
";
5303 $sql .= ", mandatory
";
5304 $sql .= ") VALUES (
";
5305 $sql .= $resource_id;
5306 $sql .= ",
'".$this->db->escape($resource_type)."'";
5307 $sql .= ",
'".$this->db->escape($this->id)."'";
5308 $sql .= ",
'".$this->db->escape($this->element)."'";
5309 $sql .= ",
'".$this->db->escape($busy)."'";
5310 $sql .= ",
'".$this->db->escape($mandatory)."'";
5314 if ($this->db->query($sql)) {
5315 $this->db->commit();
5318 $this->error = $this->db->lasterror();
5319 $this->db->rollback();
5324 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5333 public function delete_resource($rowid, $element, $notrigger = 0)
5340 $sql = "DELETE FROM
".$this->db->prefix()."element_resources
";
5341 $sql .= " WHERE
rowid =
".((int) $rowid);
5345 $resql = $this->db->query($sql);
5347 $this->error = $this->db->lasterror();
5348 $this->db->rollback();
5352 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5354 $this->db->rollback();
5358 $this->db->commit();
5369 public function __clone()
5371 // Force a copy of this->lines, otherwise it will point to same object.
5372 if (isset($this->lines) && is_array($this->lines)) {
5373 $nboflines = count($this->lines);
5374 for ($i = 0; $i < $nboflines; $i++) {
5375 $this->lines[$i] = clone $this->lines[$i];
5393 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5395 global $conf, $langs, $user, $hookmanager, $action;
5397 $srctemplatepath = '';
5399 $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5400 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5402 if (empty($reshook)) {
5403 dol_syslog("commonGenerateDocument modele=
".$modele." outputlangs->defaultlang=
".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5405 if (empty($modele)) {
5406 $this->error = 'BadValueForParameterModele';
5410 // Increase limit for PDF build
5411 $err = error_reporting();
5413 @set_time_limit(120);
5414 error_reporting($err);
5416 // If selected model is a filename template (then $modele="modelname
" or "modelname:filename
")
5417 $tmp = explode(':', $modele, 2);
5418 if (!empty($tmp[1])) {
5420 $srctemplatepath = $tmp[1];
5423 // Search template files
5427 $dirmodels = array('/');
5428 if (is_array($conf->modules_parts['models'])) {
5429 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5431 foreach ($dirmodels as $reldir) {
5432 foreach (array('doc', 'pdf') as $prefix) {
5433 if (in_array(get_class($this), array('Adherent'))) {
5434 // Member module use prefix_modele.class.php
5435 $file = $prefix."_
".$modele.".class.php
";
5437 // Other module use prefix_modele.modules.php
5438 $file = $prefix."_
".$modele.".modules.php
";
5441 // On verifie l'emplacement du modele
5442 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5443 if (file_exists($file)) {
5445 $classname = $prefix.'_'.$modele;
5454 // If generator was found
5456 global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5460 $obj = new $classname($this->db);
5462 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5463 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5464 $varfortemplatedir = $obj->scandir;
5465 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5466 $dirtoscan = $conf->global->$varfortemplatedir;
5468 $listoffiles = array();
5470 // Now we add first model found in directories scanned
5471 $listofdir = explode(',', $dirtoscan);
5472 foreach ($listofdir as $key => $tmpdir) {
5473 $tmpdir = trim($tmpdir);
5474 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5476 unset($listofdir[$key]);
5479 if (is_dir($tmpdir)) {
5480 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5481 if (count($tmpfiles)) {
5482 $listoffiles = array_merge($listoffiles, $tmpfiles);
5487 if (count($listoffiles)) {
5488 foreach ($listoffiles as $record) {
5489 $srctemplatepath = $record['fullname'];
5495 if (empty($srctemplatepath)) {
5496 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5501 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5502 if (!dol_is_file($srctemplatepath)) {
5503 dol_syslog("Failed to locate
template file
".$srctemplatepath, LOG_WARNING);
5504 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5509 // We save charset_output to restore it because write_file can change it if needed for
5510 // output format that does not support UTF8.
5511 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5513 if (in_array(get_class($this), array('Adherent'))) {
5514 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5516 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5518 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5520 if ($resultwritefile > 0) {
5521 $outputlangs->charset_output = $sav_charset_output;
5523 // We delete old preview
5524 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5525 dol_delete_preview($this);
5527 // Index file in database
5528 if (!empty($obj->result['fullpath'])) {
5529 $destfull = $obj->result['fullpath'];
5531 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5532 $update_main_doc_field = 0;
5533 if (!empty($obj->update_main_doc_field)) {
5534 $update_main_doc_field = 1;
5537 $this->indexFile($destfull, $update_main_doc_field);
5539 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);
5542 // Success in building document. We build meta file.
5543 dol_meta_create($this);
5547 $outputlangs->charset_output = $sav_charset_output;
5548 $this->error = $obj->error;
5549 $this->errors = $obj->errors;
5550 dol_syslog("Error generating document
for ".__CLASS__.". Error:
".$obj->error, LOG_ERR);
5555 $this->error = $langs->trans("Error
").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5556 $this->errors[] = $this->error;
5557 dol_syslog($this->error, LOG_ERR);
5559 $this->error = $langs->trans("Error
")." ".$langs->trans("ErrorFileDoesNotExists
", $filefound);
5560 $this->errors[] = $this->error;
5561 dol_syslog($this->error, LOG_ERR);
5579 public function indexFile($destfull, $update_main_doc_field)
5581 global $conf, $user;
5583 $upload_dir = dirname($destfull);
5584 $destfile = basename($destfull);
5585 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5587 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5588 $filename = basename($destfile);
5589 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5590 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5592 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5593 $ecmfile = new EcmFiles($this->db);
5594 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5596 // Set the public "share
" key
5597 $setsharekey = false;
5598 if ($this->element == 'propal' || $this->element == 'proposal') {
5599 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5600 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5602 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5603 $setsharekey = true;
5606 if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5607 $setsharekey = true;
5609 if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5610 $setsharekey = true;
5612 if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5613 $setsharekey = true;
5615 if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5616 $setsharekey = true;
5618 if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5619 $setsharekey = true;
5623 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5624 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5625 $ecmfile->share = getRandomPassword(true);
5630 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5631 $ecmfile->fullpath_orig = '';
5632 $ecmfile->gen_or_uploaded = 'generated';
5633 $ecmfile->description = ''; // indexed content
5634 $ecmfile->keywords = ''; // keyword content
5635 $result = $ecmfile->update($user);
5637 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5641 $ecmfile->entity = $conf->entity;
5642 $ecmfile->filepath = $rel_dir;
5643 $ecmfile->filename = $filename;
5644 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5645 $ecmfile->fullpath_orig = '';
5646 $ecmfile->gen_or_uploaded = 'generated';
5647 $ecmfile->description = ''; // indexed content
5648 $ecmfile->keywords = ''; // keyword content
5649 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5650 $ecmfile->src_object_id = $this->id;
5652 $result = $ecmfile->create($user);
5654 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5659 /*$this->result['fullname']=$destfull;
5660 $this->result['filepath']=$ecmfile->filepath;
5661 $this->result['filename']=$ecmfile->filename;*/
5662 //var_dump($obj->update_main_doc_field);exit;
5664 if ($update_main_doc_field && !empty($this->table_element)) {
5665 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET last_main_doc =
'".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5666 $sql .= " WHERE
rowid =
".((int) $this->id);
5668 $resql = $this->db->query($sql);
5670 dol_print_error($this->db);
5673 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5688 public function addThumbs($file)
5690 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5692 $tmparraysize = getDefaultImageSizes();
5693 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5694 $maxheightsmall = $tmparraysize['maxheightsmall'];
5695 $maxwidthmini = $tmparraysize['maxwidthmini'];
5696 $maxheightmini = $tmparraysize['maxheightmini'];
5697 //$quality = $tmparraysize['quality'];
5698 $quality = 50; // For thumbs, we force quality to 50
5700 $file_osencoded = dol_osencode($file);
5701 if (file_exists($file_osencoded)) {
5702 // Create small thumbs for company (Ratio is near 16/9)
5703 // Used on logon for example
5704 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5706 // Create mini thumbs for company (Ratio is near 16/9)
5707 // Used on menu or for setup page for example
5708 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5713 /* Functions common to commonobject and commonobjectline */
5715 /* For default values */
5729 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5731 global $conf, $_POST;
5733 // If param here has been posted, we use this value first.
5734 if (GETPOSTISSET($fieldname)) {
5735 return GETPOST($fieldname, 'alphanohtml', 3);
5738 if (isset($alternatevalue)) {
5739 return $alternatevalue;
5742 $newelement = $this->element;
5743 if ($newelement == 'facture') {
5744 $newelement = 'invoice';
5746 if ($newelement == 'commande') {
5747 $newelement = 'order';
5749 if (empty($newelement)) {
5750 dol_syslog("Ask a
default value
using common method getDefaultCreateValueForField on an
object with no property ->element defined. Return empty
string.
", LOG_WARNING);
5754 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5755 //var_dump($keyforfieldname);
5756 if (isset($conf->global->$keyforfieldname)) {
5757 return $conf->global->$keyforfieldname;
5760 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5767 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5778 public function call_trigger($triggerName, $user)
5781 global $langs, $conf;
5782 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5783 dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_
" as required.');
5786 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5787 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5788 $langs = new Translate('', $conf);
5791 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5792 $interface = new Interfaces($this->db);
5793 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5796 if (!empty($this->errors)) {
5797 $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.
5799 $this->errors = $interface->errors;
5806 /* Functions for data in other language */
5816 public function fetchValuesForExtraLanguages()
5818 // To avoid SQL errors. Probably not the better solution though
5819 if (!$this->element) {
5822 if (!($this->id > 0)) {
5825 if (is_array($this->array_languages)) {
5829 $this->array_languages = array();
5831 $element = $this->element;
5832 if ($element == 'categorie') {
5833 $element = 'categories'; // For compatibility
5836 // Request to get translation values for object
5837 $sql = "SELECT
rowid, property, lang , value
";
5838 $sql .= " FROM
".$this->db->prefix()."object_lang
";
5839 $sql .= " WHERE type_object =
'".$this->db->escape($element)."'";
5840 $sql .= " AND fk_object =
".((int) $this->id);
5842 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
5843 $resql = $this->db->query($sql);
5845 $numrows = $this->db->num_rows($resql);
5848 while ($i < $numrows) {
5849 $obj = $this->db->fetch_object($resql);
5850 $key = $obj->property;
5851 $value = $obj->value;
5852 $codelang = $obj->lang;
5853 $type = $this->fields[$key]['type'];
5855 // we can add this attribute to object
5856 if (preg_match('/date/', $type)) {
5857 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5859 $this->array_languages[$key][$codelang] = $value;
5866 $this->db->free($resql);
5874 dol_print_error($this->db);
5885 public function setValuesForExtraLanguages($onlykey = '')
5887 global $_POST, $langs;
5890 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5891 $tmparray = explode('-', $postfieldkey);
5892 if ($tmparray[0] != 'field') {
5896 $element = $tmparray[1];
5897 $key = $tmparray[2];
5898 $codelang = $tmparray[3];
5899 //var_dump("postfieldkey=
".$postfieldkey." element=
".$element." key=
".$key." codelang=
".$codelang);
5901 if (!empty($onlykey) && $key != $onlykey) {
5904 if ($element != $this->element) {
5908 $key_type = $this->fields[$key]['type'];
5911 if (isset($this->fields[$key]['enabled'])) {
5912 $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5915 if (isset($this->fields[$key]['perms']))
5917 $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5919 if (empty($enabled)) {
5922 //if (empty($perms)) continue;
5924 if (in_array($key_type, array('date'))) {
5926 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5927 $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month
", 'int'), GETPOST($postfieldkey."day
", 'int'), GETPOST($postfieldkey."year
", 'int'));
5928 } elseif (in_array($key_type, array('datetime'))) {
5930 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5931 $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'));
5932 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5933 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5934 if (!empty($value_arr)) {
5935 $value_key = implode(',', $value_arr);
5939 } elseif (in_array($key_type, array('price', 'double'))) {
5940 $value_arr = GETPOST($postfieldkey, 'alpha');
5941 $value_key = price2num($value_arr);
5943 $value_key = GETPOST($postfieldkey);
5944 if (in_array($key_type, array('link')) && $value_key == '-1') {
5949 $this->array_languages[$key][$codelang] = $value_key;
5951 /*if ($nofillrequired) {
5952 $langs->load('errors');
5953 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5962 /* Functions for extrafields */
5970 public function fetchNoCompute($id)
5974 $savDisableCompute = $conf->disable_compute;
5975 $conf->disable_compute = 1;
5977 $ret = $this->fetch($id);
5979 $conf->disable_compute = $savDisableCompute;
5984 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5994 public function fetch_optionals($rowid = null, $optionsArray = null)
5997 global $conf, $extrafields;
5999 if (empty($rowid)) {
6002 if (empty($rowid) && isset($this->rowid)) {
6003 $rowid = $this->rowid; // deprecated
6006 // To avoid SQL errors. Probably not the better solution though
6007 if (!$this->table_element) {
6011 $this->array_options = array();
6013 if (!is_array($optionsArray)) {
6014 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6015 if (!isset($extrafields) || !is_object($extrafields)) {
6016 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6017 $extrafields = new ExtraFields($this->db);
6020 // Load array of extrafields for elementype = $this->table_element
6021 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6022 $extrafields->fetch_name_optionals_label($this->table_element);
6024 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6026 global $extrafields;
6027 dol_syslog("Warning:
fetch_optionals was called with param optionsArray defined when you should pass
null now
", LOG_WARNING);
6030 $table_element = $this->table_element;
6031 if ($table_element == 'categorie') {
6032 $table_element = 'categories'; // For compatibility
6035 // Request to get complementary values
6036 if (is_array($optionsArray) && count($optionsArray) > 0) {
6037 $sql = "SELECT
rowid";
6038 foreach ($optionsArray as $name => $label) {
6039 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6043 $sql .= " FROM
".$this->db->prefix().$table_element."_extrafields
";
6044 $sql .= " WHERE fk_object =
".((int) $rowid);
6046 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
6047 $resql = $this->db->query($sql);
6049 $numrows = $this->db->num_rows($resql);
6051 $tab = $this->db->fetch_array($resql);
6053 foreach ($tab as $key => $value) {
6054 // 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)
6055 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6056 // we can add this attribute to object
6057 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6058 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6059 $this->array_options["options_
".$key] = $this->db->jdate($value);
6061 $this->array_options["options_
".$key] = $value;
6064 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_
".$key]);
6069 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6070 // in the element's extrafields table)
6071 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6072 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6073 //var_dump($conf->disable_compute);
6074 if (empty($conf->disable_compute)) {
6075 global $objectoffield; // We set a global variable to $objectoffield so
6076 $objectoffield = $this; // we can use it inside computed formula
6077 $this->array_options["options_
".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6082 $this->db->free($resql);
6090 $this->errors[]=$this->db->lasterror;
6103 public function deleteExtraFields()
6107 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6113 $table_element = $this->table_element;
6114 if ($table_element == 'categorie') {
6115 $table_element = 'categories'; // For compatibility
6120 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6122 $resql = $this->db->query($sql_del);
6124 $this->error = $this->db->lasterror();
6125 $this->db->rollback();
6128 $this->db->commit();
6143 public function insertExtraFields($trigger = '', $userused = null)
6145 global $conf, $langs, $user;
6147 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6151 if (empty($userused)) {
6157 if (!empty($this->array_options)) {
6159 $langs->load('admin');
6160 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6161 $extrafields = new ExtraFields($this->db);
6162 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6164 // Eliminate copied source object extra fields that do not exist in target object
6165 $new_array_options = array();
6166 foreach ($this->array_options as $key => $value) {
6167 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6168 $new_array_options[$key] = $value;
6169 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6170 $new_array_options['options_'.$key] = $value;
6174 foreach ($new_array_options as $key => $value) {
6175 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6176 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6177 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6178 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6179 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6180 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6181 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6183 // If we clone, we have to clean unique extrafields to prevent duplicates.
6184 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6185 if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
6186 $new_array_options[$key] = null;
6189 // Similar code than into insertExtraFields
6190 if ($attributeRequired) {
6191 $mandatorypb = false;
6192 if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6193 $mandatorypb = true;
6195 if ($this->array_options[$key] === '') {
6196 $mandatorypb = true;
6198 if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6199 $mandatorypb = true;
6202 $langs->load("errors
");
6203 dol_syslog("Mandatory field
'".$key."' is empty during create and
set to required into definition of extrafields
");
6204 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6209 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6210 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6212 if (!empty($attrfieldcomputed)) {
6213 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6214 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6215 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6216 $new_array_options[$key] = $value;
6218 $new_array_options[$key] = null;
6222 switch ($attributeType) {
6224 if (!is_numeric($value) && $value != '') {
6225 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6227 } elseif ($value == '') {
6228 $new_array_options[$key] = null;
6233 $value = price2num($value);
6234 if (!is_numeric($value) && $value != '') {
6235 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." for ".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6236 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6238 } elseif ($value == '') {
6241 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6242 $new_array_options[$key] = $value;
6244 /*case 'select': // Not required, we chosed value='0' for undefined values
6247 $this->array_options[$key] = null;
6252 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6253 // If there is an encryption choice, we use it to crypt data before insert
6254 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6255 $algo = reset($tmparrays);
6257 //global $action; // $action may be 'create', 'update', 'update_extras'...
6258 //var_dump($action);
6259 //var_dump($this->oldcopy);exit;
6260 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
6261 //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6262 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.
6263 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6266 $newvalue = dol_hash($this->array_options[$key], $algo);
6267 $new_array_options[$key] = $newvalue;
6270 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6273 } else // Common usage
6275 $new_array_options[$key] = $this->array_options[$key];
6280 // If data is a string instead of a timestamp, we convert it
6281 if (!is_int($this->array_options[$key])) {
6282 $this->array_options[$key] = strtotime($this->array_options[$key]);
6284 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6287 $param_list = array_keys($attributeParam['options']);
6290 $InfoFieldList = explode(":
", $param_list[0]);
6291 dol_include_once($InfoFieldList[1]);
6292 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6293 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6294 $new_array_options[$key] = '';
6296 $object = new $InfoFieldList[0]($this->db);
6297 if (is_numeric($value)) {
6298 $res = $object->fetch($value); // Common case
6300 $res = $object->fetch('', $value); // For compatibility
6304 $new_array_options[$key] = $object->id;
6306 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6311 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6319 $table_element = $this->table_element;
6320 if ($table_element == 'categorie') {
6321 $table_element = 'categories'; // For compatibility
6324 dol_syslog(get_class($this)."::
insertExtraFields delete then insert
", LOG_DEBUG);
6326 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6327 $this->db->query($sql_del);
6329 $sql = "INSERT INTO
".$this->db->prefix().$table_element."_extrafields (fk_object
";
6330 foreach ($new_array_options as $key => $value) {
6331 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6332 // Add field of attribut
6333 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6334 $sql .= ",
".$attributeKey;
6337 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6338 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6339 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6340 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6341 $sql .= ",
".$tmpkey;
6345 $sql .= ") VALUES (
".$this->id;
6347 foreach ($new_array_options as $key => $value) {
6348 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6349 // Add field of attribute
6350 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6351 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6352 $sql .= ",
'".$this->db->escape($new_array_options[$key])."'";
6358 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6359 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6360 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6361 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6362 if (in_array($tmpval, array('int', 'double', 'price'))) {
6373 $resql = $this->db->query($sql);
6375 $this->error = $this->db->lasterror();
6379 if (!$error && $trigger) {
6381 $this->context = array('extrafieldaddupdate'=>1);
6382 $result = $this->call_trigger($trigger, $userused);
6390 $this->db->rollback();
6393 $this->db->commit();
6411 public function insertExtraLanguages($trigger = '', $userused = null)
6413 global $conf, $langs, $user;
6415 if (empty($userused)) {
6421 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6422 return 0; // For avoid conflicts if trigger used
6425 if (is_array($this->array_languages)) {
6426 $new_array_languages = $this->array_languages;
6428 foreach ($new_array_languages as $key => $value) {
6429 $attributeKey = $key;
6430 $attributeType = $this->fields[$attributeKey]['type'];
6431 $attributeLabel = $this->fields[$attributeKey]['label'];
6433 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6434 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6436 switch ($attributeType) {
6438 if (!is_numeric($value) && $value != '') {
6439 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6441 } elseif ($value == '') {
6442 $new_array_languages[$key] = null;
6446 $value = price2num($value);
6447 if (!is_numeric($value) && $value != '') {
6448 dol_syslog($langs->trans("ExtraLanguageHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6449 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6451 } elseif ($value == '') {
6452 $new_array_languages[$key] = null;
6454 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6455 $new_array_languages[$key] = $value;
6457 /*case 'select': // Not required, we chosed value='0' for undefined values
6460 $this->array_options[$key] = null;
6468 $table_element = $this->table_element;
6469 if ($table_element == 'categorie') {
6470 $table_element = 'categories'; // For compatibility
6475 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6476 foreach ($langcodearray as $langcode => $value) {
6477 $sql_del = "DELETE FROM
".$this->db->prefix()."object_lang
";
6478 $sql_del .= " WHERE fk_object =
".((int) $this->id)." AND property =
'".$this->db->escape($key)."' AND type_object =
'".$this->db->escape($table_element)."'";
6479 $sql_del .= " AND lang =
'".$this->db->escape($langcode)."'";
6480 $this->db->query($sql_del);
6482 if ($value !== '') {
6483 $sql = "INSERT INTO
".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value
";
6484 $sql .= ") VALUES (
".$this->id.",
'".$this->db->escape($key)."',
'".$this->db->escape($table_element)."',
'".$this->db->escape($langcode)."',
'".$this->db->escape($value)."'";
6487 $resql = $this->db->query($sql);
6489 $this->error = $this->db->lasterror();
6497 if (!$error && $trigger) {
6499 $this->context = array('extralanguagesaddupdate'=>1);
6500 $result = $this->call_trigger($trigger, $userused);
6508 $this->db->rollback();
6511 $this->db->commit();
6529 public function updateExtraField($key, $trigger = null, $userused = null)
6531 global $conf, $langs, $user;
6533 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6537 if (empty($userused)) {
6543 if (!empty($this->array_options) && isset($this->array_options["options_
".$key])) {
6545 $langs->load('admin');
6546 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6547 $extrafields = new ExtraFields($this->db);
6548 $extrafields->fetch_name_optionals_label($this->table_element);
6550 $value = $this->array_options["options_
".$key];
6552 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6553 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6554 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6555 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6556 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6558 // Similar code than into insertExtraFields
6559 if ($attributeRequired) {
6560 $mandatorypb = false;
6561 if ($attributeType == 'link' && $this->array_options["options_
".$key] == '-1') {
6562 $mandatorypb = true;
6564 if ($this->array_options["options_
".$key] === '') {
6565 $mandatorypb = true;
6568 $langs->load("errors
");
6569 dol_syslog("Mandatory field
'options_".$key."' is empty during update and
set to required into definition of extrafields
");
6570 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6575 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6576 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6578 if (!empty($attrfieldcomputed)) {
6579 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6580 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6581 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6582 $this->array_options["options_
".$key] = $value;
6584 $this->array_options["options_
".$key] = null;
6588 switch ($attributeType) {
6590 if (!is_numeric($value) && $value != '') {
6591 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6593 } elseif ($value === '') {
6594 $this->array_options["options_
".$key] = null;
6598 $value = price2num($value);
6599 if (!is_numeric($value) && $value != '') {
6600 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6601 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6603 } elseif ($value === '') {
6606 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6607 $this->array_options["options_
".$key] = $value;
6609 /*case 'select': // Not required, we chosed value='0' for undefined values
6612 $this->array_options[$key] = null;
6616 $this->array_options["options_
".$key] = price2num($this->array_options["options_
".$key]);
6620 if (empty($this->array_options["options_
".$key])) {
6621 $this->array_options["options_
".$key] = null;
6623 $this->array_options["options_
".$key] = $this->db->idate($this->array_options["options_
".$key]);
6627 if (empty($this->array_options["options_
".$key])) {
6628 $this->array_options["options_
".$key] = null;
6633 $param_list = array_keys($attributeParam['options']);
6636 $InfoFieldList = explode(":
", $param_list[0]);
6637 dol_include_once($InfoFieldList[1]);
6638 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6640 if ($value == '-1') // -1 is key for no defined in combo list of objects
6642 $new_array_options[$key] = '';
6644 $object = new $InfoFieldList[0]($this->db);
6645 if (is_numeric($value)) $res = $object->fetch($value); // Common case
6646 else $res = $object->fetch('', $value); // For compatibility
6648 if ($res > 0) $new_array_options[$key] = $object->id;
6650 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6651 $this->db->rollback();
6656 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6664 $linealreadyfound = 0;
6666 // 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)
6667 $sql = "SELECT COUNT(
rowid) as nb FROM
".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6668 $resql = $this->db->query($sql);
6670 $tmpobj = $this->db->fetch_object($resql);
6672 $linealreadyfound = $tmpobj->nb;
6676 if ($linealreadyfound) {
6677 if ($this->array_options["options_
".$key] === null) {
6678 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
null";
6680 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
'".$this->db->escape($this->array_options["options_".$key])."'";
6682 $sql .= " WHERE fk_object =
".((int) $this->id);
6684 $result = $this->insertExtraFields('', $user);
6690 $resql = $this->db->query($sql);
6693 $this->error = $this->db->lasterror();
6695 if (!$error && $trigger) {
6697 $this->context = array('extrafieldupdate'=>1);
6698 $result = $this->call_trigger($trigger, $userused);
6706 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6707 $this->db->rollback();
6710 $this->db->commit();
6728 public function updateExtraLanguages($key, $trigger = null, $userused = null)
6730 global $conf, $langs, $user;
6732 if (empty($userused)) {
6738 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6739 return 0; // For avoid conflicts if trigger used
6760 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6762 global $conf, $langs, $form;
6764 if (!is_object($form)) {
6765 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6766 $form = new Form($this->db);
6769 if (!empty($this->fields)) {
6770 $val = $this->fields[$key];
6773 // Validation tests and output
6774 $fieldValidationErrorMsg = '';
6775 $validationClass = '';
6776 $fieldValidationErrorMsg = $this->getFieldError($key);
6777 if (!empty($fieldValidationErrorMsg)) {
6778 $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
6780 $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
6787 $param['options'] = array();
6789 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6790 // Because we work on extrafields
6791 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6792 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6794 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6795 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6797 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6798 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6800 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6801 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6803 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6804 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6806 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6807 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6809 } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6810 $param['options'] = array();
6813 } elseif (preg_match('/varchar/', $val['type'])) {
6814 $param['options'] = array();
6817 $param['options'] = array();
6818 $type = $this->fields[$key]['type'];
6821 // Special case that force options and type ($type can be integer, varchar, ...)
6822 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6823 $param['options'] = $this->fields[$key]['arrayofkeyval'];
6827 $label = $this->fields[$key]['label'];
6828 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6829 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6830 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6831 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6832 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6833 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6835 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6836 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6837 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6839 $objectid = $this->id;
6842 if (!preg_match('/^search_/', $keyprefix)) {
6843 return '<span class="opacitymedium
">'.$langs->trans("AutomaticallyCalculated
").'</span>';
6849 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6850 if (empty($morecss) && !empty($val['css'])) {
6851 $morecss = $val['css'];
6852 } elseif (empty($morecss)) {
6853 if ($type == 'date') {
6854 $morecss = 'minwidth100imp';
6855 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6856 $morecss = 'minwidth200imp';
6857 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6858 $morecss = 'maxwidth75';
6859 } elseif ($type == 'url') {
6860 $morecss = 'minwidth400';
6861 } elseif ($type == 'boolean') {
6864 if (round($size) < 12) {
6865 $morecss = 'minwidth100';
6866 } elseif (round($size) <= 48) {
6867 $morecss = 'minwidth200';
6869 $morecss = 'minwidth400';
6874 // Add validation state class
6875 if (!empty($validationClass)) {
6876 $morecss.= $validationClass;
6879 if (in_array($type, array('date'))) {
6880 $tmp = explode(',', $size);
6884 // Do not show current date when field not required (see selectDate() method)
6885 if (!$required && $value == '') {
6889 // TODO Must also support $moreparam
6890 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6891 } elseif (in_array($type, array('datetime'))) {
6892 $tmp = explode(',', $size);
6896 // Do not show current date when field not required (see selectDate() method)
6897 if (!$required && $value == '') $value = '-1';
6899 // TODO Must also support $moreparam
6900 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6901 } elseif (in_array($type, array('duration'))) {
6902 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6903 } elseif (in_array($type, array('int', 'integer'))) {
6904 $tmp = explode(',', $size);
6906 $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' : '').'>';
6907 } elseif (in_array($type, array('real'))) {
6908 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6909 } elseif (preg_match('/varchar/', $type)) {
6910 $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' : '').'>';
6911 } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
6912 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6913 } elseif (preg_match('/^text/', $type)) {
6914 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6915 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6916 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6917 $out = $doleditor->Create(1);
6919 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6921 } elseif (preg_match('/^html/', $type)) {
6922 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6923 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6924 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6925 $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6927 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6929 } elseif ($type == 'boolean') {
6931 if (!empty($value)) {
6932 $checked = ' checked value="1
" ';
6934 $checked = ' value="1
" ';
6936 $out = '<input type="checkbox
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6937 } elseif ($type == 'price') {
6938 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6939 $value = price($value);
6941 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6942 } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6943 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6944 $value = price($value);
6946 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6947 } elseif ($type == 'select') {
6949 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6950 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6951 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6954 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6955 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6956 $out .= '<option value="0
"> </option>';
6958 foreach ($param['options'] as $keyb => $valb) {
6959 if ((string) $keyb == '') {
6962 if (strpos($valb, "|
") !== false) {
6963 list($valb, $parent) = explode('|', $valb);
6965 $out .= '<option value="'.$keyb.'"';
6966 $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6967 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6968 $out .= '>'.$valb.'</option>';
6970 $out .= '</select>';
6971 } elseif ($type == 'sellist') {
6973 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6974 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6975 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6978 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6979 if (is_array($param['options'])) {
6980 $param_list = array_keys($param['options']);
6981 $InfoFieldList = explode(":
", $param_list[0]);
6985 // 1 : label field name
6986 // 2 : key fields name (if differ of rowid)
6987 // 3 : key field parent (for dependent lists)
6988 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
6989 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
6991 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
6992 if (strpos($InfoFieldList[4], 'extra.') !== false) {
6993 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
6995 $keyList = $InfoFieldList[2].' as rowid';
6998 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
6999 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7000 $keyList .= ', '.$parentField;
7003 $fields_label = explode('|', $InfoFieldList[1]);
7004 if (is_array($fields_label)) {
7006 $keyList .= implode(', ', $fields_label);
7010 $sql = "SELECT
".$keyList;
7011 $sql .= " FROM
".$this->db->prefix().$InfoFieldList[0];
7012 if (!empty($InfoFieldList[4])) {
7013 // can use SELECT request
7014 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7015 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7018 // current object id can be use into filter
7019 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7020 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7022 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7025 //We have to join on extrafield table
7026 if (strpos($InfoFieldList[4], 'extra') !== false) {
7027 $sql .= " as main,
".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra
";
7028 $sqlwhere .= " WHERE extra.fk_object=main.
".$InfoFieldList[2]." AND
".$InfoFieldList[4];
7030 $sqlwhere .= " WHERE
".$InfoFieldList[4];
7033 $sqlwhere .= ' WHERE 1=1';
7035 // Some tables may have field, some other not. For the moment we disable it.
7036 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7037 $sqlwhere .= " AND entity =
".((int) $conf->entity);
7042 $sql .= ' ORDER BY '.implode(', ', $fields_label);
7044 dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
7045 $resql = $this->db->query($sql);
7047 $out .= '<option value="0
"> </option>';
7048 $num = $this->db->num_rows($resql);
7052 $obj = $this->db->fetch_object($resql);
7054 // Several field into label (eq table:code|libelle:rowid)
7056 $fields_label = explode('|', $InfoFieldList[1]);
7057 if (count($fields_label) > 1) {
7059 foreach ($fields_label as $field_toshow) {
7060 $labeltoshow .= $obj->$field_toshow.' ';
7063 $labeltoshow = $obj->{$InfoFieldList[1]};
7065 $labeltoshow = dol_trunc($labeltoshow, 45);
7067 if ($value == $obj->rowid) {
7068 foreach ($fields_label as $field_toshow) {
7069 $translabel = $langs->trans($obj->$field_toshow);
7070 if ($translabel != $obj->$field_toshow) {
7071 $labeltoshow = dol_trunc($translabel).' ';
7073 $labeltoshow = dol_trunc($obj->$field_toshow).' ';
7076 $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7079 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7080 if ($translabel != $obj->{$InfoFieldList[1]}) {
7081 $labeltoshow = dol_trunc($translabel, 18);
7083 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7086 if (empty($labeltoshow)) {
7087 $labeltoshow = '(not defined)';
7089 if ($value == $obj->rowid) {
7090 $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7093 if (!empty($InfoFieldList[3]) && $parentField) {
7094 $parent = $parentName.':'.$obj->{$parentField};
7098 $out .= '<option value="'.$obj->rowid.'"';
7099 $out .= ($value == $obj->rowid ? ' selected' : '');
7100 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7101 $out .= '>'.$labeltoshow.'</option>';
7106 $this->db->free($resql);
7108 print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7111 $out .= '</select>';
7112 } elseif ($type == 'checkbox') {
7113 $value_arr = explode(',', $value);
7114 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7115 } elseif ($type == 'radio') {
7117 foreach ($param['options'] as $keyopt => $valopt) {
7118 $out .= '<input class="flat
'.$morecss.'" type="radio
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7119 $out .= ' value="'.$keyopt.'"';
7120 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'"';
7121 $out .= ($value == $keyopt ? 'checked' : '');
7122 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'">'.$valopt.'</label><br>';
7124 } elseif ($type == 'chkbxlst') {
7125 if (is_array($value)) {
7126 $value_arr = $value;
7128 $value_arr = explode(',', $value);
7131 if (is_array($param['options'])) {
7132 $param_list = array_keys($param['options']);
7133 $InfoFieldList = explode(":
", $param_list[0]);
7137 // 1 : label field name
7138 // 2 : key fields name (if differ of rowid)
7139 // 3 : key field parent (for dependent lists)
7140 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7141 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7143 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7144 list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7145 $keyList .= ', '.$parentField;
7147 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7148 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7149 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7151 $keyList = $InfoFieldList[2].' as rowid';
7155 $fields_label = explode('|', $InfoFieldList[1]);
7156 if (is_array($fields_label)) {
7158 $keyList .= implode(', ', $fields_label);
7162 $sql = "SELECT
".$keyList;
7163 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7164 if (!empty($InfoFieldList[4])) {
7165 // can use SELECT request
7166 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7167 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7170 // current object id can be use into filter
7171 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7172 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7174 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7177 // We have to join on extrafield table
7178 if (strpos($InfoFieldList[4], 'extra') !== false) {
7179 $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
7180 $sqlwhere .= " WHERE extra.fk_object=main.
".$InfoFieldList[2]." AND
".$InfoFieldList[4];
7182 $sqlwhere .= " WHERE
".$InfoFieldList[4];
7185 $sqlwhere .= ' WHERE 1=1';
7187 // Some tables may have field, some other not. For the moment we disable it.
7188 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7189 $sqlwhere .= " AND entity =
".((int) $conf->entity);
7191 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7195 dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
7196 $resql = $this->db->query($sql);
7198 $num = $this->db->num_rows($resql);
7205 $obj = $this->db->fetch_object($resql);
7208 // Several field into label (eq table:code|libelle:rowid)
7209 $fields_label = explode('|', $InfoFieldList[1]);
7210 if (count($fields_label) > 1) {
7212 foreach ($fields_label as $field_toshow) {
7213 $labeltoshow .= $obj->$field_toshow.' ';
7216 $labeltoshow = $obj->{$InfoFieldList[1]};
7218 $labeltoshow = dol_trunc($labeltoshow, 45);
7220 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7221 foreach ($fields_label as $field_toshow) {
7222 $translabel = $langs->trans($obj->$field_toshow);
7223 if ($translabel != $obj->$field_toshow) {
7224 $labeltoshow = dol_trunc($translabel, 18).' ';
7226 $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
7230 $data[$obj->rowid] = $labeltoshow;