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)
1278 if (!$error && empty($notrigger)) {
1280 $this->context['contact_id'] = ((int) $rowid);
1281 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1285 // End call triggers
1291 $sql = "DELETE FROM
".MAIN_DB_PREFIX."element_contact
";
1292 $sql .= " WHERE
rowid =
".((int) $rowid);
1294 $result = $this->db->query($sql);
1297 $this->errors[] = $this->db->lasterror();
1302 $this->db->commit();
1305 $this->error = $this->db->lasterror();
1306 $this->db->rollback();
1311 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1319 public function delete_linked_contact($source = '', $code = '')
1324 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1326 if (!empty($typeContact)) {
1327 foreach ($typeContact as $key => $value) {
1328 array_push($temp, $key);
1330 $listId = implode(",
", $temp);
1333 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1334 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1335 if (empty($listId)) {
1339 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1340 $sql .= " WHERE element_id =
".((int) $this->id);
1341 $sql .= " AND fk_c_type_contact IN (
".$this->db->sanitize($listId).")
";
1344 if ($this->db->query($sql)) {
1347 $this->error = $this->db->lasterror();
1352 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1362 public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
1369 $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
1370 if ($source == 'internal') {
1371 $sql .= ",
'-1' as socid, t.statut as statuscontact, t.login, t.photo
";
1373 if ($source == 'external' || $source == 'thirdparty') {
1374 $sql .= ", t.fk_soc as socid, t.statut as statuscontact
";
1376 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email
";
1377 $sql .= ", tc.source, tc.element, tc.code, tc.libelle
";
1378 $sql .= " FROM
".$this->db->prefix()."c_type_contact tc
";
1379 $sql .= ",
".$this->db->prefix()."element_contact ec
";
1380 if ($source == 'internal') {
1381 $sql .= " LEFT JOIN
".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid
";
1383 if ($source == 'external' || $source == 'thirdparty') {
1384 $sql .= " LEFT JOIN
".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid
";
1386 $sql .= " WHERE ec.element_id =
".((int) $this->id);
1387 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1388 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1390 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1392 if ($source == 'internal') {
1393 $sql .= " AND tc.source =
'internal'";
1395 if ($source == 'external' || $source == 'thirdparty') {
1396 $sql .= " AND tc.source =
'external'";
1398 $sql .= " AND tc.active=1
";
1400 $sql .= " AND ec.statut =
".((int) $status);
1402 $sql .= " ORDER BY t.lastname ASC
";
1405 $resql = $this->db->query($sql);
1407 $num = $this->db->num_rows($resql);
1410 $obj = $this->db->fetch_object($resql);
1413 $transkey = "TypeContact_
".$obj->element."_
".$obj->source."_
".$obj->code;
1414 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1416 'source' => $obj->source,
1417 'socid' => $obj->socid,
1419 'nom' => $obj->lastname, // For backward compatibility
1420 'civility' => $obj->civility,
1421 'lastname' => $obj->lastname,
1422 'firstname' => $obj->firstname,
1423 'email'=>$obj->email,
1424 'login'=> (empty($obj->login) ? '' : $obj->login),
1425 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1426 'statuscontact' => $obj->statuscontact,
1427 'rowid' => $obj->rowid,
1428 'code' => $obj->code,
1429 'libelle' => $libelle_type,
1430 'status' => $obj->statuslink,
1431 'fk_c_type_contact' => $obj->fk_c_type_contact
1434 $tab[$i] = $obj->id;
1442 $this->error = $this->db->lasterror();
1443 dol_print_error($this->db);
1455 public function swapContactStatus($rowid)
1457 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,
";
1458 $sql .= " tc.code, tc.libelle
";
1459 $sql .= " FROM (
".$this->db->prefix()."element_contact as ec,
".$this->db->prefix()."c_type_contact as tc)
";
1460 $sql .= " WHERE ec.rowid =
".((int) $rowid);
1461 $sql .= " AND ec.fk_c_type_contact=tc.rowid
";
1462 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1465 $resql = $this->db->query($sql);
1467 $obj = $this->db->fetch_object($resql);
1468 $newstatut = ($obj->statut == 4) ? 5 : 4;
1469 $result = $this->update_contact($rowid, $newstatut);
1470 $this->db->free($resql);
1473 $this->error = $this->db->error();
1474 dol_print_error($this->db);
1479 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1490 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1495 if (empty($order)) {
1496 $order = 'position';
1498 if ($order == 'position') {
1503 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position
";
1504 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1505 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1506 if ($activeonly == 1) {
1507 $sql .= " AND tc.active=1
"; // only the active types
1509 if (!empty($source) && $source != 'all') {
1510 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1512 if (!empty($code)) {
1513 $sql .= " AND tc.code=
'".$this->db->escape($code)."'";
1515 $sql .= $this->db->order($order, 'ASC');
1517 //print "sql=
".$sql;
1518 $resql = $this->db->query($sql);
1520 $num = $this->db->num_rows($resql);
1523 $obj = $this->db->fetch_object($resql);
1525 $transkey = "TypeContact_
".$this->element."_
".$source."_
".$obj->code;
1526 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1527 if (empty($option)) {
1528 $tab[$obj->rowid] = $libelle_type;
1530 $tab[$obj->code] = $libelle_type;
1536 $this->error = $this->db->lasterror();
1537 //dol_print_error($this->db);
1542 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1554 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1557 global $langs, $conf;
1559 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1563 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element
";
1564 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1566 $sqlWhere = array();
1567 if (!empty($element)) {
1568 $sqlWhere[] = " tc.element=
'".$this->db->escape($element)."'";
1570 if (!empty($excludeelement)) {
1571 $sqlWhere[] = " tc.element <>
'".$this->db->escape($excludeelement)."'";
1574 if ($activeonly == 1) {
1575 $sqlWhere[] = " tc.active=1
"; // only the active types
1578 if (!empty($source) && $source != 'all') {
1579 $sqlWhere[] = " tc.source=
'".$this->db->escape($source)."'";
1582 if (!empty($code)) {
1583 $sqlWhere[] = " tc.code=
'".$this->db->escape($code)."'";
1586 if (count($sqlWhere) > 0) {
1587 $sql .= " WHERE
".implode(' AND ', $sqlWhere);
1590 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1592 dol_syslog(__METHOD__, LOG_DEBUG);
1593 $resql = $this->db->query($sql);
1595 $num = $this->db->num_rows($resql);
1597 $langs->loadLangs(array("propal
", "orders
", "bills
", "suppliers
", "contracts
", "supplier_proposal
"));
1599 while ($obj = $this->db->fetch_object($resql)) {
1600 $modulename = $obj->element;
1601 if (strpos($obj->element, 'project') !== false) {
1602 $modulename = 'projet';
1603 } elseif ($obj->element == 'contrat') {
1604 $element = 'contract';
1605 } elseif ($obj->element == 'action') {
1606 $modulename = 'agenda';
1607 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1608 $modulename = 'fournisseur';
1609 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1610 $modulename = 'fournisseur';
1612 if (!empty($conf->{$modulename}->enabled)) {
1613 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1614 $tmpelement = $obj->element;
1615 $transkey = "TypeContact_
".$tmpelement."_
".$source."_
".$obj->code;
1616 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1617 if (empty($option)) {
1618 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1620 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1627 $this->error = $this->db->lasterror();
1643 public function getIdContact($source, $code, $status = 0)
1649 //cas particulier pour les expeditions
1650 if ($this->element == 'shipping' && $this->origin_id != 0) {
1651 $id = $this->origin_id;
1652 $element = 'commande';
1653 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1654 $id = $this->origin_id;
1655 $element = 'order_supplier';
1658 $element = $this->element;
1661 $sql = "SELECT ec.fk_socpeople
";
1662 $sql .= " FROM
".$this->db->prefix()."element_contact as ec,
";
1663 if ($source == 'internal') {
1664 $sql .= " ".$this->db->prefix()."user as c,
";
1666 if ($source == 'external') {
1667 $sql .= " ".$this->db->prefix()."socpeople as c,
";
1669 $sql .= " ".$this->db->prefix()."c_type_contact as tc
";
1670 $sql .= " WHERE ec.element_id =
".((int) $id);
1671 $sql .= " AND ec.fk_socpeople = c.rowid
";
1672 if ($source == 'internal') {
1673 $sql .= " AND c.entity IN (
".getEntity('user').")
";
1675 if ($source == 'external') {
1676 $sql .= " AND c.entity IN (
".getEntity('societe').")
";
1678 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1679 $sql .= " AND tc.element =
'".$this->db->escape($element)."'";
1680 $sql .= " AND tc.source =
'".$this->db->escape($source)."'";
1682 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1684 $sql .= " AND tc.active = 1
";
1686 $sql .= " AND ec.statut =
".((int) $status);
1690 $resql = $this->db->query($sql);
1692 while ($obj = $this->db->fetch_object($resql)) {
1693 $result[$i] = $obj->fk_socpeople;
1697 $this->error = $this->db->error();
1704 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1711 public function fetch_contact($contactid = null)
1714 if (empty($contactid)) {
1715 $contactid = $this->contact_id;
1718 if (empty($contactid)) {
1722 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1723 $contact = new Contact($this->db);
1724 $result = $contact->fetch($contactid);
1725 $this->contact = $contact;
1729 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736 public function fetch_thirdparty($force_thirdparty_id = 0)
1741 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1745 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1747 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1748 if ($force_thirdparty_id) {
1749 $idtofetch = $force_thirdparty_id;
1753 $thirdparty = new Societe($this->db);
1754 $result = $thirdparty->fetch($idtofetch);
1756 $this->errors=array_merge($this->errors, $thirdparty->errors);
1758 $this->thirdparty = $thirdparty;
1760 // Use first price level if level not defined for third party
1761 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1762 $this->thirdparty->price_level = 1;
1779 public function fetchOneLike($ref)
1781 if (!$this->table_ref_field) {
1785 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element." WHERE
".$this->table_ref_field." LIKE
'".$this->db->escape($ref)."' LIMIT 1
";
1787 $query = $this->db->query($sql);
1789 if (!$this->db->num_rows($query)) {
1793 $result = $this->db->fetch_object($query);
1795 return $this->fetch($result->rowid);
1798 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1806 public function fetch_barcode()
1811 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1813 $idtype = $this->barcode_type;
1814 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
1815 if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1816 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1817 } elseif ($this->element == 'societe') {
1818 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1820 dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1825 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
1826 $sql = "SELECT
rowid,
code, libelle as label, coder
";
1827 $sql .= " FROM
".$this->db->prefix()."c_barcode_type
";
1828 $sql .= " WHERE
rowid =
".((int) $idtype);
1829 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1830 $resql = $this->db->query($sql);
1832 $obj = $this->db->fetch_object($resql);
1833 $this->barcode_type = $obj->rowid;
1834 $this->barcode_type_code = $obj->code;
1835 $this->barcode_type_label = $obj->label;
1836 $this->barcode_type_coder = $obj->coder;
1839 dol_print_error($this->db);
1847 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1853 public function fetch_project()
1856 return $this->fetch_projet();
1859 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1865 public function fetch_projet()
1868 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1870 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1871 $this->fk_project = $this->fk_projet; // For backward compatibility
1873 if (empty($this->fk_project)) {
1877 $project = new Project($this->db);
1878 $result = $project->fetch($this->fk_project);
1880 $this->projet = $project; // deprecated
1881 $this->project = $project;
1885 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1891 public function fetch_product()
1894 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1896 if (empty($this->fk_product)) {
1900 $product = new Product($this->db);
1901 $result = $product->fetch($this->fk_product);
1903 $this->product = $product;
1907 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1914 public function fetch_user($userid)
1917 $user = new User($this->db);
1918 $result = $user->fetch($userid);
1919 $this->user = $user;
1923 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1929 public function fetch_origin()
1932 if ($this->origin == 'shipping') {
1933 $this->origin = 'expedition';
1935 if ($this->origin == 'delivery') {
1936 $this->origin = 'livraison';
1938 if ($this->origin == 'order_supplier') {
1939 $this->origin = 'commandeFournisseur';
1942 $origin = $this->origin;
1944 $classname = ucfirst($origin);
1945 $this->$origin = new $classname($this->db);
1946 $this->$origin->fetch($this->origin_id);
1958 public function fetchObjectFrom($table, $field, $key, $element = null)
1964 $sql = "SELECT
rowid FROM
".$this->db->prefix().$table;
1965 $sql .= " WHERE
".$field." =
'".$this->db->escape($key)."'";
1966 if (!empty($element)) {
1967 $sql .= " AND entity IN (
".getEntity($element).")
";
1969 $sql .= " AND entity =
".((int) $conf->entity);
1972 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1973 $resql = $this->db->query($sql);
1975 $row = $this->db->fetch_row($resql);
1976 // Test for avoid error -1
1978 $result = $this->fetch($row[0]);
1993 public function getValueFrom($table, $id, $field)
1996 if (!empty($id) && !empty($field) && !empty($table)) {
1997 $sql = "SELECT
".$field." FROM
".$this->db->prefix().$table;
1998 $sql .= " WHERE
rowid =
".((int) $id);
2000 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2001 $resql = $this->db->query($sql);
2003 $row = $this->db->fetch_row($resql);
2026 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2028 global $user, $langs, $conf;
2030 if (empty($table)) {
2031 $table = $this->table_element;
2036 if (empty($format)) {
2039 if (empty($id_field)) {
2040 $id_field = 'rowid';
2048 if ($table == 'product' && $field == 'note_private') {
2051 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2052 $fk_user_field = 'fk_user_mod';
2055 $sql = "UPDATE
".$this->db->prefix().$table." SET
";
2057 if ($format == 'text') {
2058 $sql .= $field." =
'".$this->db->escape($value)."'";
2059 } elseif ($format == 'int') {
2060 $sql .= $field." =
".((int) $value);
2061 } elseif ($format == 'date') {
2062 $sql .= $field." =
".($value ? "'".$this->db->idate($value)."'" : "null");
2065 if ($fk_user_field) {
2066 if (!empty($fuser) && is_object($fuser)) {
2067 $sql .= ",
".$fk_user_field." =
".((int) $fuser->id);
2068 } elseif (empty($fuser) || $fuser != 'none') {
2069 $sql .= ",
".$fk_user_field." =
".((int) $user->id);
2073 $sql .= " WHERE
".$id_field." =
".((int) $id);
2075 dol_syslog(__METHOD__."", LOG_DEBUG);
2076 $resql = $this->db->query($sql);
2079 // call trigger with updated object values
2080 if (empty($this->fields) && method_exists($this, 'fetch')) {
2081 $result = $this->fetch($id);
2083 $result = $this->fetchCommon($id);
2086 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2094 if (property_exists($this, $field)) {
2095 $this->$field = $value;
2097 $this->db->commit();
2100 $this->db->rollback();
2104 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2105 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2107 $this->error = $this->db->lasterror();
2109 $this->db->rollback();
2114 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2123 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2126 global $conf, $user;
2128 if (!$this->table_element) {
2129 dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with
property table_element not defined
");
2132 if ($fieldid == 'none') {
2136 // For backward compatibility
2137 if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2141 // Security on socid
2143 if ($user->socid > 0) {
2144 $socid = $user->socid;
2147 // this->ismultientitymanaged contains
2148 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2149 $aliastablesociete = 's';
2150 if ($this->element == 'societe') {
2151 $aliastablesociete = 'te'; // te as table_element
2153 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2154 $sql = "SELECT MAX(te.
".$fieldid.")
";
2155 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2156 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2157 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2159 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2160 $tmparray = explode('@', $this->ismultientitymanaged);
2161 $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
2162 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2163 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2164 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2165 $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
2167 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2168 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2170 $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)
2171 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2172 $sql .= " AND sc.fk_user =
".((int) $user->id);
2174 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2175 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2177 if (!empty($filter)) {
2178 if (!preg_match('/^\s*AND/i', $filter)) {
2179 $sql .= " AND
"; // For backward compatibility
2183 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2184 $tmparray = explode('@', $this->ismultientitymanaged);
2185 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2186 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2187 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2189 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2190 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2191 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2192 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2194 $sql .= " AND ug.fk_user = te.rowid
";
2195 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2198 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2201 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2202 $tmparray = explode('@', $this->ismultientitymanaged);
2203 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2205 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2206 $sql .= ' AND te.fk_soc = '.((int) $socid);
2208 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2209 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2211 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2212 $sql .= ' AND te.rowid = '.((int) $socid);
2214 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2216 $result = $this->db->query($sql);
2218 $this->error = $this->db->lasterror();
2221 $row = $this->db->fetch_row($result);
2222 $this->ref_previous = $row[0];
2224 $sql = "SELECT MIN(te.
".$fieldid.")
";
2225 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2226 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2227 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2229 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2230 $tmparray = explode('@', $this->ismultientitymanaged);
2231 $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
2232 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2233 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2234 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2235 $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
2237 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2238 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2240 $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)
2241 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2242 $sql .= " AND sc.fk_user =
".((int) $user->id);
2244 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2245 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2247 if (!empty($filter)) {
2248 if (!preg_match('/^\s*AND/i', $filter)) {
2249 $sql .= " AND
"; // For backward compatibility
2253 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2254 $tmparray = explode('@', $this->ismultientitymanaged);
2255 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2256 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2257 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2259 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2260 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2261 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2262 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2264 $sql .= " AND ug.fk_user = te.rowid
";
2265 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2268 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2271 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2272 $tmparray = explode('@', $this->ismultientitymanaged);
2273 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2275 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2276 $sql .= ' AND te.fk_soc = '.((int) $socid);
2278 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2279 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2281 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2282 $sql .= ' AND te.rowid = '.((int) $socid);
2284 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2285 // 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
2287 $result = $this->db->query($sql);
2289 $this->error = $this->db->lasterror();
2292 $row = $this->db->fetch_row($result);
2293 $this->ref_next = $row[0];
2306 public function getListContactId($source = 'external')
2308 $contactAlreadySelected = array();
2309 $tab = $this->liste_contact(-1, $source);
2313 if ($source == 'thirdparty') {
2314 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2316 $contactAlreadySelected[$i] = $tab[$i]['id'];
2320 return $contactAlreadySelected;
2331 public function setProject($projectid, $notrigger = 0)
2336 if (!$this->table_element) {
2337 dol_syslog(get_class($this)."::
setProject was called on objet with property table_element not defined
", LOG_ERR);
2341 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2342 if (!empty($this->fields['fk_project'])) { // Common case
2344 $sql .= " SET fk_project =
".((int) $projectid);
2346 $sql .= " SET fk_project = NULL
";
2348 $sql .= ' WHERE rowid = '.((int) $this->id);
2349 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2351 $sql .= " SET fk_project =
".((int) $projectid);
2353 $sql .= " SET fk_project = NULL
";
2355 $sql .= ' WHERE id = '.((int) $this->id);
2356 } else // Special case for old architecture objects
2359 $sql .= ' SET fk_projet = '.((int) $projectid);
2361 $sql .= ' SET fk_projet = NULL';
2363 $sql .= " WHERE
rowid =
".((int) $this->id);
2368 dol_syslog(get_class($this)."::
setProject", LOG_DEBUG);
2369 if ($this->db->query($sql)) {
2370 $this->fk_project = ((int) $projectid);
2372 dol_print_error($this->db);
2377 if (!$error && !$notrigger) {
2379 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2382 } //Do also here what you must do to rollback action if trigger fail
2383 // End call triggers
2386 // Commit or rollback
2388 $this->db->rollback();
2391 $this->db->commit();
2402 public function setPaymentMethods($id)
2406 $error = 0; $notrigger = 0;
2408 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2410 if ($this->statut >= 0 || $this->element == 'societe') {
2411 // TODO uniformize field name
2412 $fieldname = 'fk_mode_reglement';
2413 if ($this->element == 'societe') {
2414 $fieldname = 'mode_reglement';
2416 if (get_class($this) == 'Fournisseur') {
2417 $fieldname = 'mode_reglement_supplier';
2419 if (get_class($this) == 'Tva') {
2420 $fieldname = 'fk_typepayment';
2422 if (get_class($this) == 'Salary') {
2423 $fieldname = 'fk_typepayment';
2426 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2427 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2428 $sql .= ' WHERE rowid='.((int) $this->id);
2430 if ($this->db->query($sql)) {
2431 $this->mode_reglement_id = $id;
2433 if (get_class($this) == 'Fournisseur') {
2434 $this->mode_reglement_supplier_id = $id;
2437 if (!$error && !$notrigger) {
2439 if (get_class($this) == 'Commande') {
2440 $result = $this->call_trigger('ORDER_MODIFY', $user);
2442 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2447 // End call triggers
2451 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2452 $this->error = $this->db->error();
2456 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2457 $this->error = 'Status of the object is incompatible '.$this->statut;
2468 public function setMulticurrencyCode($code)
2470 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2471 if ($this->statut >= 0 || $this->element == 'societe') {
2472 $fieldname = 'multicurrency_code';
2474 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2475 $sql .= " SET
".$fieldname." =
'".$this->db->escape($code)."'";
2476 $sql .= ' WHERE rowid='.((int) $this->id);
2478 if ($this->db->query($sql)) {
2479 $this->multicurrency_code = $code;
2481 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2483 $this->setMulticurrencyRate($rate, 2);
2488 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2489 $this->error = $this->db->error();
2493 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2494 $this->error = 'Status of the object is incompatible '.$this->statut;
2506 public function setMulticurrencyRate($rate, $mode = 1)
2508 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2509 if ($this->statut >= 0 || $this->element == 'societe') {
2510 $fieldname = 'multicurrency_tx';
2512 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2513 $sql .= " SET
".$fieldname." =
".((float) $rate);
2514 $sql .= ' WHERE rowid='.((int) $this->id);
2516 if ($this->db->query($sql)) {
2517 $this->multicurrency_tx = $rate;
2519 // Update line price
2520 if (!empty($this->lines)) {
2521 foreach ($this->lines as &$line) {
2522 // Amounts in company currency will be recalculated
2524 $line->subprice = 0;
2527 // Amounts in foreign currency will be recalculated
2529 $line->multicurrency_subprice = 0;
2532 switch ($this->element) {
2538 $line->remise_percent,
2540 $line->localtax1_tx,
2541 $line->localtax2_tx,
2542 ($line->description ? $line->description : $line->desc),
2545 $line->special_code,
2546 $line->fk_parent_line,
2547 $line->skip_update_total,
2548 $line->fk_fournprice,
2551 $line->product_type,
2554 $line->array_options,
2556 $line->multicurrency_subprice
2562 ($line->description ? $line->description : $line->desc),
2565 $line->remise_percent,
2567 $line->localtax1_tx,
2568 $line->localtax2_tx,
2573 $line->product_type,
2574 $line->fk_parent_line,
2575 $line->skip_update_total,
2576 $line->fk_fournprice,
2579 $line->special_code,
2580 $line->array_options,
2582 $line->multicurrency_subprice
2588 ($line->description ? $line->description : $line->desc),
2591 $line->remise_percent,
2595 $line->localtax1_tx,
2596 $line->localtax2_tx,
2599 $line->product_type,
2600 $line->fk_parent_line,
2601 $line->skip_update_total,
2602 $line->fk_fournprice,
2605 $line->special_code,
2606 $line->array_options,
2607 $line->situation_percent,
2609 $line->multicurrency_subprice
2612 case 'supplier_proposal':
2617 $line->remise_percent,
2619 $line->localtax1_tx,
2620 $line->localtax2_tx,
2621 ($line->description ? $line->description : $line->desc),
2624 $line->special_code,
2625 $line->fk_parent_line,
2626 $line->skip_update_total,
2627 $line->fk_fournprice,
2630 $line->product_type,
2631 $line->array_options,
2633 $line->multicurrency_subprice
2636 case 'order_supplier':
2639 ($line->description ? $line->description : $line->desc),
2642 $line->remise_percent,
2644 $line->localtax1_tx,
2645 $line->localtax2_tx,
2648 $line->product_type,
2652 $line->array_options,
2654 $line->multicurrency_subprice,
2658 case 'invoice_supplier':
2661 ($line->description ? $line->description : $line->desc),
2664 $line->localtax1_tx,
2665 $line->localtax2_tx,
2670 $line->product_type,
2671 $line->remise_percent,
2675 $line->array_options,
2677 $line->multicurrency_subprice,
2682 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2690 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2691 $this->error = $this->db->error();
2695 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2696 $this->error = 'Status of the object is incompatible '.$this->statut;
2708 public function setPaymentTerms($id, $deposit_percent = null)
2710 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2711 if ($this->statut >= 0 || $this->element == 'societe') {
2712 // TODO uniformize field name
2713 $fieldname = 'fk_cond_reglement';
2714 if ($this->element == 'societe') {
2715 $fieldname = 'cond_reglement';
2717 if (get_class($this) == 'Fournisseur') {
2718 $fieldname = 'cond_reglement_supplier';
2721 if (empty($deposit_percent) || $deposit_percent < 0) {
2722 $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2725 if ($deposit_percent > 100) {
2726 $deposit_percent = 100;
2729 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2730 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2731 if (in_array($this->table_element, array('propal', 'commande'))) {
2732 $sql .= " , deposit_percent =
" . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2734 $sql .= ' WHERE rowid='.((int) $this->id);
2736 if ($this->db->query($sql)) {
2737 $this->cond_reglement_id = $id;
2739 if (get_class($this) == 'Fournisseur') {
2740 $this->cond_reglement_supplier_id = $id;
2742 $this->cond_reglement = $id; // for compatibility
2743 $this->deposit_percent = $deposit_percent;
2746 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2747 $this->error = $this->db->error();
2751 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2752 $this->error = 'Status of the object is incompatible '.$this->statut;
2763 public function setTransportMode($id)
2765 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2766 if ($this->statut >= 0 || $this->element == 'societe') {
2767 $fieldname = 'fk_transport_mode';
2768 if ($this->element == 'societe') {
2769 $fieldname = 'transport_mode';
2771 if (get_class($this) == 'Fournisseur') {
2772 $fieldname = 'transport_mode_supplier';
2775 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2776 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2777 $sql .= ' WHERE rowid='.((int) $this->id);
2779 if ($this->db->query($sql)) {
2780 $this->transport_mode_id = $id;
2782 if (get_class($this) == 'Fournisseur') {
2783 $this->transport_mode_supplier_id = $id;
2787 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2788 $this->error = $this->db->error();
2792 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2793 $this->error = 'Status of the object is incompatible '.$this->statut;
2804 public function setRetainedWarrantyPaymentTerms($id)
2806 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2807 if ($this->statut >= 0 || $this->element == 'societe') {
2808 $fieldname = 'retained_warranty_fk_cond_reglement';
2810 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2811 $sql .= " SET
".$fieldname." =
".((int) $id);
2812 $sql .= ' WHERE rowid='.((int) $this->id);
2814 if ($this->db->query($sql)) {
2815 $this->retained_warranty_fk_cond_reglement = $id;
2818 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2819 $this->error = $this->db->error();
2823 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2824 $this->error = 'Status of the object is incompatible '.$this->statut;
2836 public function setDeliveryAddress($id)
2838 $fieldname = 'fk_delivery_address';
2839 if ($this->element == 'delivery' || $this->element == 'shipping') {
2840 $fieldname = 'fk_address';
2843 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET
".$fieldname." =
".((int) $id);
2844 $sql .= " WHERE
rowid =
".((int) $this->id)." AND fk_statut = 0
";
2846 if ($this->db->query($sql)) {
2847 $this->fk_delivery_address = $id;
2850 $this->error = $this->db->error();
2851 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2866 public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2870 if (empty($userused)) {
2876 if (!$this->table_element) {
2877 dol_syslog(get_class($this)."::
setShippingMethod was called on objet with property table_element not defined
", LOG_ERR);
2883 if ($shipping_method_id < 0) {
2884 $shipping_method_id = 'NULL';
2886 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2888 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2889 $sql .= " SET fk_shipping_method =
".((int) $shipping_method_id);
2890 $sql .= " WHERE
rowid=
".((int) $this->id);
2891 $resql = $this->db->query($sql);
2893 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2894 $this->error = $this->db->lasterror();
2899 $this->context = array('shippingmethodupdate'=>1);
2900 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2908 $this->db->rollback();
2911 $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2912 $this->db->commit();
2924 public function setWarehouse($warehouse_id)
2926 if (!$this->table_element) {
2927 dol_syslog(get_class($this)."::
setWarehouse was called on objet with property table_element not defined
", LOG_ERR);
2930 if ($warehouse_id < 0) {
2931 $warehouse_id = 'NULL';
2933 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2935 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2936 $sql .= " SET fk_warehouse =
".((int) $warehouse_id);
2937 $sql .= " WHERE
rowid=
".((int) $this->id);
2939 if ($this->db->query($sql)) {
2940 $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2943 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2944 $this->error = $this->db->error();
2957 public function setDocModel($user, $modelpdf)
2959 if (!$this->table_element) {
2960 dol_syslog(get_class($this)."::
setDocModel was called on objet with property table_element not defined
", LOG_ERR);
2964 $newmodelpdf = dol_trunc($modelpdf, 255);
2966 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2967 $sql .= " SET model_pdf =
'".$this->db->escape($newmodelpdf)."'";
2968 $sql .= " WHERE
rowid =
".((int) $this->id);
2970 dol_syslog(get_class($this)."::
setDocModel", LOG_DEBUG);
2971 $resql = $this->db->query($sql);
2973 $this->model_pdf = $modelpdf;
2974 $this->modelpdf = $modelpdf; // For bakward compatibility
2977 dol_print_error($this->db);
2991 public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2995 if (empty($userused)) {
3001 if (!$this->table_element) {
3002 dol_syslog(get_class($this)."::
setBankAccount was called on objet with property table_element not defined
", LOG_ERR);
3007 if ($fk_account < 0) {
3008 $fk_account = 'NULL';
3010 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3012 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3013 $sql .= " SET fk_account =
".((int) $fk_account);
3014 $sql .= " WHERE
rowid=
".((int) $this->id);
3016 $resql = $this->db->query($sql);
3018 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3019 $this->error = $this->db->lasterror();
3024 $this->context = array('bankaccountupdate'=>1);
3025 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3033 $this->db->rollback();
3036 $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3037 $this->db->commit();
3043 // TODO: Move line related operations to CommonObjectLine?
3045 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3055 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3058 if (!$this->table_element_line) {
3059 dol_syslog(get_class($this)."::
line_order was called on objet with property table_element_line not defined
", LOG_ERR);
3062 if (!$this->fk_element) {
3063 dol_syslog(get_class($this)."::
line_order was called on objet with property fk_element not defined
", LOG_ERR);
3067 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3068 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3069 $fieldposition = 'position';
3072 // Count number of lines to reorder (according to choice $renum)
3074 $sql = "SELECT count(
rowid) FROM
".$this->db->prefix().$this->table_element_line;
3075 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3077 $sql .= " AND
" . $fieldposition . " = 0
";
3080 $sql .= " AND
" . $fieldposition . " <> 0
";
3083 dol_syslog(get_class($this)."::
line_order", LOG_DEBUG);
3084 $resql = $this->db->query($sql);
3086 $row = $this->db->fetch_row($resql);
3089 dol_print_error($this->db);
3092 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3095 // We first search all lines that are parent lines (for multilevel details lines)
3096 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3097 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3098 if ($fk_parent_line) {
3099 $sql .= ' AND fk_parent_line IS NULL';
3101 $sql .= " ORDER BY
" . $fieldposition . " ASC,
rowid " . $rowidorder;
3103 dol_syslog(get_class($this)."::
line_order search all parent lines
", LOG_DEBUG);
3104 $resql = $this->db->query($sql);
3107 $num = $this->db->num_rows($resql);
3109 $row = $this->db->fetch_row($resql);
3110 $rows[] = $row[0]; // Add parent line into array rows
3111 $childrens = $this->getChildrenOfLine($row[0]);
3112 if (!empty($childrens)) {
3113 foreach ($childrens as $child) {
3114 array_push($rows, $child);
3120 // Now we set a new number for each lines (parent and children with children included into parent tree)
3121 if (!empty($rows)) {
3122 foreach ($rows as $key => $row) {
3123 $this->updateRangOfLine($row, ($key + 1));
3127 dol_print_error($this->db);
3140 public function getChildrenOfLine($id, $includealltree = 0)
3142 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3143 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3144 $fieldposition = 'position';
3149 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3150 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3151 $sql .= ' AND fk_parent_line = '.((int) $id);
3152 $sql .= " ORDER BY
" . $fieldposition . " ASC
";
3154 dol_syslog(get_class($this)."::
getChildrenOfLine search children lines
for line
".$id, LOG_DEBUG);
3155 $resql = $this->db->query($sql);
3157 if ($this->db->num_rows($resql) > 0) {
3158 while ($row = $this->db->fetch_row($resql)) {
3160 if (!empty($includealltree)) {
3161 $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3169 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3177 public function line_up($rowid, $fk_parent_line = true)
3180 $this->line_order(false, 'ASC', $fk_parent_line);
3183 $rang = $this->getRangOfLine($rowid);
3185 // Update position of line
3186 $this->updateLineUp($rowid, $rang);
3189 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3197 public function line_down($rowid, $fk_parent_line = true)
3200 $this->line_order(false, 'ASC', $fk_parent_line);
3203 $rang = $this->getRangOfLine($rowid);
3205 // Get max value for rang
3206 $max = $this->line_max();
3208 // Update position of line
3209 $this->updateLineDown($rowid, $rang, $max);
3219 public function updateRangOfLine($rowid, $rang)
3221 global $hookmanager;
3222 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3223 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3224 $fieldposition = 'position';
3227 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3228 $sql .= ' WHERE rowid = '.((int) $rowid);
3231 if (!$this->db->query($sql)) {
3232 dol_print_error($this->db);
3235 $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3237 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3242 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3249 public function line_ajaxorder($rows)
3252 $num = count($rows);
3253 for ($i = 0; $i < $num; $i++) {
3254 $this->updateRangOfLine($rows[$i], ($i + 1));
3265 public function updateLineUp($rowid, $rang)
3268 $fieldposition = 'rang';
3269 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3270 $fieldposition = 'position';
3273 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3274 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3275 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang - 1));
3276 if ($this->db->query($sql)) {
3277 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang - 1));
3278 $sql .= ' WHERE rowid = '.((int) $rowid);
3279 if (!$this->db->query($sql)) {
3280 dol_print_error($this->db);
3283 dol_print_error($this->db);
3296 public function updateLineDown($rowid, $rang, $max)
3299 $fieldposition = 'rang';
3300 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3301 $fieldposition = 'position';
3304 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3305 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3306 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang + 1));
3307 if ($this->db->query($sql)) {
3308 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang + 1));
3309 $sql .= ' WHERE rowid = '.((int) $rowid);
3310 if (!$this->db->query($sql)) {
3311 dol_print_error($this->db);
3314 dol_print_error($this->db);
3325 public function getRangOfLine($rowid)
3327 $fieldposition = 'rang';
3328 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3329 $fieldposition = 'position';
3332 $sql = "SELECT
" . $fieldposition . " FROM
".$this->db->prefix().$this->table_element_line;
3333 $sql .= " WHERE
rowid =
".((int) $rowid);
3336 $resql = $this->db->query($sql);
3338 $row = $this->db->fetch_row($resql);
3349 public function getIdOfLine($rang)
3351 $fieldposition = 'rang';
3352 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3353 $fieldposition = 'position';
3356 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3357 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3358 $sql .= " AND
" . $fieldposition . " =
".((int) $rang);
3359 $resql = $this->db->query($sql);
3361 $row = $this->db->fetch_row($resql);
3366 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3373 public function line_max($fk_parent_line = 0)
3376 $positionfield = 'rang';
3377 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3378 $positionfield = 'position';
3381 // Search the last rang with fk_parent_line
3382 if ($fk_parent_line) {
3383 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3384 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3385 $sql .= " AND fk_parent_line =
".((int) $fk_parent_line);
3387 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3388 $resql = $this->db->query($sql);
3390 $row = $this->db->fetch_row($resql);
3391 if (!empty($row[0])) {
3394 return $this->getRangOfLine($fk_parent_line);
3398 // If not, search the last rang of element
3399 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3400 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3402 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3403 $resql = $this->db->query($sql);
3405 $row = $this->db->fetch_row($resql);
3411 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3418 public function update_ref_ext($ref_ext)
3421 if (!$this->table_element) {
3422 dol_syslog(get_class($this)."::
update_ref_ext was called on objet with property table_element not defined
", LOG_ERR);
3426 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3427 $sql .= " SET ref_ext =
'".$this->db->escape($ref_ext)."'";
3428 $sql .= " WHERE
".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." =
".((int) $this->id);
3431 if ($this->db->query($sql)) {
3432 $this->ref_ext = $ref_ext;
3435 $this->error = $this->db->error();
3440 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3448 public function update_note($note, $suffix = '')
3453 if (!$this->table_element) {
3454 $this->error = 'update_note was called on objet with property table_element not defined';
3455 dol_syslog(get_class($this)."::
update_note was called on objet with property table_element not defined
", LOG_ERR);
3458 if (!in_array($suffix, array('', '_public', '_private'))) {
3459 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3460 dol_syslog(get_class($this)."::
update_note Parameter suffix must be empty,
'_private' or
'_public'", LOG_ERR);
3464 $newsuffix = $suffix;
3467 if ($this->table_element == 'product' && $newsuffix == '_private') {
3470 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3471 $fieldusermod = "fk_user_mod
";
3472 } elseif ($this->table_element == 'ecm_files') {
3473 $fieldusermod = "fk_user_m
";
3475 $fieldusermod = "fk_user_modif
";
3477 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3478 $sql .= " SET note
".$newsuffix." =
".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL
");
3479 $sql .= ",
".$fieldusermod." =
".((int) $user->id);
3480 $sql .= " WHERE
rowid =
".((int) $this->id);
3482 dol_syslog(get_class($this)."::
update_note", LOG_DEBUG);
3483 if ($this->db->query($sql)) {
3484 if ($suffix == '_public') {
3485 $this->note_public = $note;
3486 } elseif ($suffix == '_private') {
3487 $this->note_private = $note;
3489 $this->note = $note; // deprecated
3490 $this->note_private = $note;
3494 $this->error = $this->db->lasterror();
3499 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3508 public function update_note_public($note)
3511 return $this->update_note($note, '_public');
3514 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3525 public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3528 global $conf, $hookmanager, $action;
3530 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3531 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3533 return 1; // replacement code
3534 } elseif ($reshook < 0) {
3535 return -1; // failure
3536 } // reshook = 0 => execute normal code
3538 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3540 if ($this->element == 'propal') {
3541 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL
";
3542 } elseif ($this->element == 'commande' || $this->element == 'order') {
3543 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER
";
3544 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3545 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE
";
3546 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3547 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE
";
3548 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3549 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER
";
3550 } elseif ($this->element == 'supplier_proposal') {
3551 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL
";
3554 if (!empty($MODULE)) {
3555 if (!empty($conf->global->$MODULE)) {
3556 $modsactivated = explode(',', $conf->global->$MODULE);
3557 foreach ($modsactivated as $mod) {
3558 if ($conf->$mod->enabled) {
3559 return 1; // update was disabled by specific setup
3565 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3567 if ($roundingadjust == '-1') {
3568 $roundingadjust = 'auto'; // For backward compatibility
3571 $forcedroundingmode = $roundingadjust;
3572 if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3573 $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3574 } elseif ($forcedroundingmode == 'auto') {
3575 $forcedroundingmode = '0';
3580 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3582 // Define constants to find lines to sum
3583 $fieldtva = 'total_tva';
3584 $fieldlocaltax1 = 'total_localtax1';
3585 $fieldlocaltax2 = 'total_localtax2';
3586 $fieldup = 'subprice';
3587 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3591 if ($this->element == 'invoice_supplier_rec') {
3594 if ($this->element == 'expensereport') {
3595 $fieldup = 'value_unit';
3598 $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,
";
3599 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3600 if ($this->table_element_line == 'facturedet') {
3601 $sql .= ', situation_percent';
3603 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3604 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
3605 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3607 $product_field = 'product_type';
3608 if ($this->table_element_line == 'contratdet') {
3609 $product_field = ''; // contratdet table has no product_type field
3611 if ($product_field) {
3612 $sql .= " AND
".$product_field." <> 9
";
3615 $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
3617 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3618 $resql = $this->db->query($sql);
3620 $this->total_ht = 0;
3621 $this->total_tva = 0;
3622 $this->total_localtax1 = 0;
3623 $this->total_localtax2 = 0;
3624 $this->total_ttc = 0;
3625 $total_ht_by_vats = array();
3626 $total_tva_by_vats = array();
3627 $total_ttc_by_vats = array();
3628 $this->multicurrency_total_ht = 0;
3629 $this->multicurrency_total_tva = 0;
3630 $this->multicurrency_total_ttc = 0;
3632 $num = $this->db->num_rows($resql);
3635 $obj = $this->db->fetch_object($resql);
3637 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3638 $parameters = array('fk_element' => $obj->rowid);
3639 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3641 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'
3642 // This part of code is to fix data. We should not call it too often.
3643 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3644 $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);
3646 $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.
3647 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3648 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
3649 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3651 if ($diff_when_using_price_ht && $diff_on_current_total) {
3652 $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);
3653 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);
3654 $resqlfix = $this->db->query($sqlfix);
3656 dol_print_error($this->db, 'Failed to update line');
3658 $obj->total_tva = $tmpcal[1];
3659 $obj->total_ttc = $tmpcal[2];
3663 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3664 $this->total_tva += $obj->total_tva;
3665 $this->total_localtax1 += $obj->total_localtax1;
3666 $this->total_localtax2 += $obj->total_localtax2;
3667 $this->total_ttc += $obj->total_ttc;
3668 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3669 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3670 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3672 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3673 $total_ht_by_vats[$obj->vatrate] = 0;
3675 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3676 $total_tva_by_vats[$obj->vatrate] = 0;
3678 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3679 $total_ttc_by_vats[$obj->vatrate] = 0;
3681 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3682 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3683 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3685 if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3686 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3687 $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3688 //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
";
3690 if (abs($diff) > (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)))) {
3691 // If error is more than 10 times the accurancy of rounding. This should not happen.
3692 $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.';
3693 dol_syslog($errmsg, LOG_WARNING);
3694 dol_print_error('', $errmsg);
3697 $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);
3698 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);
3700 $resqlfix = $this->db->query($sqlfix);
3703 dol_print_error($this->db, 'Failed to update line');
3706 $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3707 $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3708 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3709 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3716 // Add revenue stamp to total
3717 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3718 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3720 // Situations totals
3721 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3722 $prev_sits = $this->get_prev_sits();
3724 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3725 $this->total_ht -= $sit->total_ht;
3726 $this->total_tva -= $sit->total_tva;
3727 $this->total_localtax1 -= $sit->total_localtax1;
3728 $this->total_localtax2 -= $sit->total_localtax2;
3729 $this->total_ttc -= $sit->total_ttc;
3730 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3731 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3732 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3737 $this->total_ht = (float) price2num($this->total_ht);
3738 $this->total_tva = (float) price2num($this->total_tva);
3739 $this->total_localtax1 = (float) price2num($this->total_localtax1);
3740 $this->total_localtax2 = (float) price2num($this->total_localtax2);
3741 $this->total_ttc = (float) price2num($this->total_ttc);
3743 $this->db->free($resql);
3745 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
3746 $fieldht = 'total_ht';
3748 $fieldlocaltax1 = 'localtax1';
3749 $fieldlocaltax2 = 'localtax2';
3750 $fieldttc = 'total_ttc';
3751 // Specific code for backward compatibility with old field names
3752 if ($this->element == 'facture' || $this->element == 'facturerec') {
3753 $fieldtva = 'total_tva';
3755 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3756 $fieldtva = 'total_tva';
3758 if ($this->element == 'propal') {
3759 $fieldtva = 'total_tva';
3761 if ($this->element == 'expensereport') {
3762 $fieldtva = 'total_tva';
3764 if ($this->element == 'supplier_proposal') {
3765 $fieldtva = 'total_tva';
3767 if ($this->element == 'commande') {
3768 $fieldtva = 'total_tva';
3770 if ($this->element == 'order_supplier') {
3771 $fieldtva = 'total_tva';
3774 if (empty($nodatabaseupdate)) {
3775 $sql = "UPDATE
".$this->db->prefix().$this->table_element.' SET';
3776 $sql .= " ".$fieldht." =
".((float) price2num($this->total_ht, 'MT', 1)).",
";
3777 $sql .= " ".$fieldtva." =
".((float) price2num($this->total_tva, 'MT', 1)).",
";
3778 $sql .= " ".$fieldlocaltax1." =
".((float) price2num($this->total_localtax1, 'MT', 1)).",
";
3779 $sql .= " ".$fieldlocaltax2." =
".((float) price2num($this->total_localtax2, 'MT', 1)).",
";
3780 $sql .= " ".$fieldttc." =
".((float) price2num($this->total_ttc, 'MT', 1));
3781 $sql .= ", multicurrency_total_ht =
".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3782 $sql .= ", multicurrency_total_tva =
".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3783 $sql .= ", multicurrency_total_ttc =
".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3784 $sql .= " WHERE
rowid =
".((int) $this->id);
3786 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3787 $resql = $this->db->query($sql);
3791 $this->error = $this->db->lasterror();
3792 $this->errors[] = $this->db->lasterror();
3802 dol_print_error($this->db, 'Bad request in update_price');
3807 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3818 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3821 global $user, $hookmanager, $action;
3822 $origin = (!empty($origin) ? $origin : $this->origin);
3823 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3824 $f_user = isset($f_user) ? $f_user : $user;
3827 if ($origin == 'order') {
3828 $origin = 'commande';
3830 if ($origin == 'invoice') {
3831 $origin = 'facture';
3833 if ($origin == 'invoice_template') {
3834 $origin = 'facturerec';
3836 if ($origin == 'supplierorder') {
3837 $origin = 'order_supplier';
3840 // 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.
3841 // 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.
3842 $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3843 // Add module part to target type if object has $module property and isn't in core modules.
3844 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3846 $parameters = array('targettype'=>$targettype);
3847 // Hook for explicitly set the targettype if it must be differtent than $this->element
3848 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3850 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3856 $sql = "INSERT INTO
" . $this->db->prefix() . "element_element (
";
3857 $sql .= "fk_source
";
3858 $sql .= ", sourcetype
";
3859 $sql .= ", fk_target
";
3860 $sql .= ", targettype
";
3861 $sql .= ") VALUES (
";
3862 $sql .= ((int) $origin_id);
3863 $sql .= ",
'" . $this->db->escape($origin) . "'";
3864 $sql .= ",
" . ((int) $this->id);
3865 $sql .= ",
'" . $this->db->escape($targettype) . "'";
3869 if ($this->db->query($sql)) {
3872 $this->context['link_origin'] = $origin;
3873 $this->context['link_origin_id'] = $origin_id;
3874 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3878 // End call triggers
3881 $this->error = $this->db->lasterror();
3886 $this->db->commit();
3889 $this->db->rollback();
3916 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3918 global $conf, $hookmanager, $action;
3920 // Important for pdf generation time reduction
3921 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3922 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3926 $this->linkedObjectsIds = array();
3927 $this->linkedObjects = array();
3929 $justsource = false;
3930 $justtarget = false;
3931 $withtargettype = false;
3932 $withsourcetype = false;
3934 $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3935 // Hook for explicitly set the targettype if it must be differtent than $this->element
3936 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3938 if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3939 if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3940 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3941 if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3944 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3945 $justsource = true; // the source (id and type) is a search criteria
3946 if (!empty($targettype)) {
3947 $withtargettype = true;
3950 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3951 $justtarget = true; // the target (id and type) is a search criteria
3952 if (!empty($sourcetype)) {
3953 $withsourcetype = true;
3957 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3958 $targetid = (!empty($targetid) ? $targetid : $this->id);
3959 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3960 $targettype = (!empty($targettype) ? $targettype : $this->element);
3962 /*if (empty($sourceid) && empty($targetid))
3964 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3968 // Links between objects are stored in table element_element
3969 $sql = "SELECT
rowid, fk_source, sourcetype, fk_target, targettype
";
3970 $sql .= " FROM
".$this->db->prefix()."element_element
";
3972 if ($justsource || $justtarget) {
3974 $sql .= "fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3975 if ($withtargettype) {
3976 $sql .= " AND targettype =
'".$this->db->escape($targettype)."'";
3978 } elseif ($justtarget) {
3979 $sql .= "fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."'";
3980 if ($withsourcetype) {
3981 $sql .= " AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3985 $sql .= "(fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."')
";
3986 $sql .= " ".$clause." (fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."')
";
3987 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3988 $this->linkedObjectsFullLoaded[$this->id] = true;
3991 $sql .= " ORDER BY
".$orderby;
3993 dol_syslog(get_class($this)."::fetchObjectLink
", LOG_DEBUG);
3994 $resql = $this->db->query($sql);
3996 $num = $this->db->num_rows($resql);
3999 $obj = $this->db->fetch_object($resql);
4000 if ($justsource || $justtarget) {
4002 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4003 } elseif ($justtarget) {
4004 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4007 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4008 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4010 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4011 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4017 if (!empty($this->linkedObjectsIds)) {
4018 $tmparray = $this->linkedObjectsIds;
4019 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4020 // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4021 $module = $element = $subelement = $objecttype;
4023 if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4024 && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4025 $module = $element = $regs[1];
4026 $subelement = $regs[2];
4029 $classpath = $element.'/class';
4030 // To work with non standard classpath or module name
4031 if ($objecttype == 'facture') {
4032 $classpath = 'compta/facture/class';
4033 } elseif ($objecttype == 'facturerec') {
4034 $classpath = 'compta/facture/class';
4035 $module = 'facture';
4036 } elseif ($objecttype == 'propal') {
4037 $classpath = 'comm/propal/class';
4038 } elseif ($objecttype == 'supplier_proposal') {
4039 $classpath = 'supplier_proposal/class';
4040 } elseif ($objecttype == 'shipping') {
4041 $classpath = 'expedition/class';
4042 $subelement = 'expedition';
4043 $module = 'expedition_bon';
4044 } elseif ($objecttype == 'delivery') {
4045 $classpath = 'delivery/class';
4046 $subelement = 'delivery';
4047 $module = 'delivery_note';
4048 } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4049 $classpath = 'fourn/class';
4050 $module = 'fournisseur';
4051 } elseif ($objecttype == 'fichinter') {
4052 $classpath = 'fichinter/class';
4053 $subelement = 'fichinter';
4054 $module = 'ficheinter';
4055 } elseif ($objecttype == 'subscription') {
4056 $classpath = 'adherents/class';
4057 $module = 'adherent';
4058 } elseif ($objecttype == 'contact') {
4059 $module = 'societe';
4062 $classfile = strtolower($subelement);
4063 $classname = ucfirst($subelement);
4065 if ($objecttype == 'order') {
4066 $classfile = 'commande';
4067 $classname = 'Commande';
4068 } elseif ($objecttype == 'invoice_supplier') {
4069 $classfile = 'fournisseur.facture';
4070 $classname = 'FactureFournisseur';
4071 } elseif ($objecttype == 'order_supplier') {
4072 $classfile = 'fournisseur.commande';
4073 $classname = 'CommandeFournisseur';
4074 } elseif ($objecttype == 'supplier_proposal') {
4075 $classfile = 'supplier_proposal';
4076 $classname = 'SupplierProposal';
4077 } elseif ($objecttype == 'facturerec') {
4078 $classfile = 'facture-rec';
4079 $classname = 'FactureRec';
4080 } elseif ($objecttype == 'subscription') {
4081 $classfile = 'subscription';
4082 $classname = 'Subscription';
4083 } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4084 $classpath = 'projet/class';
4085 $classfile = 'project';
4086 $classname = 'Project';
4087 } elseif ($objecttype == 'conferenceorboothattendee') {
4088 $classpath = 'eventorganization/class';
4089 $classfile = 'conferenceorboothattendee';
4090 $classname = 'ConferenceOrBoothAttendee';
4091 $module = 'eventorganization';
4092 } elseif ($objecttype == 'conferenceorbooth') {
4093 $classpath = 'eventorganization/class';
4094 $classfile = 'conferenceorbooth';
4095 $classname = 'ConferenceOrBooth';
4096 $module = 'eventorganization';
4097 } elseif ($objecttype == 'mo') {
4098 $classpath = 'mrp/class';
4104 // Here $module, $classfile and $classname are set, we can use them.
4105 if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
4106 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4107 dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4108 //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4109 if (class_exists($classname)) {
4110 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4111 $object = new $classname($this->db);
4112 $ret = $object->fetch($objectid);
4114 $this->linkedObjects[$objecttype][$i] = $object;
4120 unset($this->linkedObjectsIds[$objecttype]);
4126 dol_print_error($this->db);
4137 public function clearObjectLinkedCache()
4139 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4140 unset($this->linkedObjectsFullLoaded[$this->id]);
4158 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4161 $updatesource = false;
4162 $updatetarget = false;
4163 $f_user = isset($f_user) ? $f_user : $user;
4165 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4166 $updatesource = true;
4167 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4168 $updatetarget = true;
4174 $sql = "UPDATE
" . $this->db->prefix() . "element_element SET
";
4175 if ($updatesource) {
4176 $sql .= "fk_source =
" . ((int) $sourceid);
4177 $sql .= ", sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4178 $sql .= " WHERE fk_target =
" . ((int) $this->id);
4179 $sql .= " AND targettype =
'" . $this->db->escape($this->element) . "'";
4180 } elseif ($updatetarget) {
4181 $sql .= "fk_target =
" . ((int) $targetid);
4182 $sql .= ", targettype =
'" . $this->db->escape($targettype) . "'";
4183 $sql .= " WHERE fk_source =
" . ((int) $this->id);
4184 $sql .= " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4188 if ($this->db->query($sql)) {
4191 $this->context['link_source_id'] = $sourceid;
4192 $this->context['link_source_type'] = $sourcetype;
4193 $this->context['link_target_id'] = $targetid;
4194 $this->context['link_target_type'] = $targettype;
4195 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4199 // End call triggers
4202 $this->error = $this->db->lasterror();
4207 $this->db->commit();
4210 $this->db->rollback();
4228 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4231 $deletesource = false;
4232 $deletetarget = false;
4233 $f_user = isset($f_user) ? $f_user : $user;
4235 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4236 $deletesource = true;
4237 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4238 $deletetarget = true;
4241 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4242 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4243 $targetid = (!empty($targetid) ? $targetid : $this->id);
4244 $targettype = (!empty($targettype) ? $targettype : $this->element);
4250 $this->context['link_id'] = $rowid;
4251 $this->context['link_source_id'] = $sourceid;
4252 $this->context['link_source_type'] = $sourcetype;
4253 $this->context['link_target_id'] = $targetid;
4254 $this->context['link_target_type'] = $targettype;
4255 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4259 // End call triggers
4263 $sql = "DELETE FROM
" . $this->db->prefix() . "element_element
";
4266 $sql .= " rowid =
" . ((int) $rowid);
4268 if ($deletesource) {
4269 $sql .= " fk_source =
" . ((int) $sourceid) . " AND sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4270 $sql .= " AND fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "'";
4271 } elseif ($deletetarget) {
4272 $sql .= " fk_target =
" . ((int) $targetid) . " AND targettype =
'" . $this->db->escape($targettype) . "'";
4273 $sql .= " AND fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4275 $sql .= " (fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "')
";
4277 $sql .= " (fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "')
";
4282 if (!$this->db->query($sql)) {
4283 $this->error = $this->db->lasterror();
4284 $this->errors[] = $this->error;
4290 $this->db->commit();
4293 $this->db->rollback();
4307 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4309 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4315 $sql = "SELECT
".$field_select." FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4316 $resql = $db->query($sql);
4319 if (!empty($resql)) {
4320 while ($res = $db->fetch_object($resql)) {
4321 $TRes[] = $res->{$field_select};
4336 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4338 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4344 $sql = "DELETE FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4345 $resql = $db->query($sql);
4347 if (empty($resql)) {
4364 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4366 global $user, $langs, $conf;
4368 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4370 $elementId = (!empty($elementId) ? $elementId : $this->id);
4371 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4375 if ($elementTable == 'facture_rec') {
4376 $fieldstatus = "suspended
";
4378 if ($elementTable == 'mailing') {
4379 $fieldstatus = "statut
";
4381 if ($elementTable == 'cronjob') {
4382 $fieldstatus = "status
";
4384 if ($elementTable == 'user') {
4385 $fieldstatus = "statut
";
4387 if ($elementTable == 'expensereport') {
4388 $fieldstatus = "fk_statut
";
4390 if ($elementTable == 'commande_fournisseur_dispatch') {
4391 $fieldstatus = "status
";
4393 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4394 $fieldstatus = 'status';
4397 $sql = "UPDATE
".$this->db->prefix().$elementTable;
4398 $sql .= " SET
".$fieldstatus." =
".((int) $status);
4399 // If status = 1 = validated, update also fk_user_valid
4400 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4401 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4402 $sql .= ", fk_user_valid =
".((int) $user->id);
4404 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4405 $sql .= ", date_valid =
'".$this->db->idate(dol_now())."'";
4407 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4408 $sql .= ", date_validation =
'".$this->db->idate(dol_now())."'";
4410 $sql .= " WHERE
rowid =
".((int) $elementId);
4411 $sql .= " AND
".$fieldstatus." <>
".((int) $status); // We avoid update if status already correct
4413 dol_syslog(get_class($this)."::
setStatut", LOG_DEBUG);
4414 $resql = $this->db->query($sql);
4418 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4420 if ($nb_rows_affected > 0) {
4421 if (empty($trigkey)) {
4422 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4423 if ($this->element == 'supplier_proposal' && $status == 2) {
4424 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4426 if ($this->element == 'supplier_proposal' && $status == 3) {
4427 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4429 if ($this->element == 'supplier_proposal' && $status == 4) {
4430 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4432 if ($this->element == 'fichinter' && $status == 3) {
4433 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4435 if ($this->element == 'fichinter' && $status == 2) {
4436 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4438 if ($this->element == 'fichinter' && $status == 1) {
4439 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4445 $result = $this->call_trigger($trigkey, $user);
4449 // End call triggers
4452 // The status was probably already good. We do nothing more, no triggers.
4456 $this->db->commit();
4458 if (empty($savElementId)) {
4459 // If the element we update is $this (so $elementId was provided as null)
4460 if ($fieldstatus == 'tosell') {
4461 $this->status = $status;
4462 } elseif ($fieldstatus == 'tobuy') {
4463 $this->status_buy = $status;
4465 $this->statut = $status;
4466 $this->status = $status;
4472 $this->db->rollback();
4473 dol_syslog(get_class($this)."::
setStatut ".$this->error, LOG_ERR);
4477 $this->error = $this->db->lasterror();
4478 $this->db->rollback();
4491 public function getCanvas($id = 0, $ref = '')
4495 if (empty($id) && empty($ref)) {
4498 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4499 return 0; // To increase speed. Not enabled by default.
4505 $sql = "SELECT
rowid, canvas
";
4506 $sql .= " FROM
".$this->db->prefix().$this->table_element;
4507 $sql .= " WHERE entity IN (
".getEntity($this->element).")
";
4509 $sql .= " AND
rowid =
".((int) $id);
4512 $sql .= " AND
ref =
'".$this->db->escape($ref)."'";
4515 $resql = $this->db->query($sql);
4517 $obj = $this->db->fetch_object($resql);
4519 $this->canvas = $obj->canvas;
4525 dol_print_error($this->db);
4537 public function getSpecialCode($lineid)
4539 $sql = "SELECT special_code FROM
".$this->db->prefix().$this->table_element_line;
4540 $sql .= " WHERE
rowid =
".((int) $lineid);
4541 $resql = $this->db->query($sql);
4543 $row = $this->db->fetch_row($resql);
4556 public function isObjectUsed($id = 0, $entity = 0)
4565 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4566 dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4570 $arraytoscan = $this->childtables;
4571 // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4572 $tmparray = array_keys($this->childtables);
4573 if (is_numeric($tmparray[0])) {
4574 $arraytoscan = array_flip($this->childtables);
4577 // Test if child exists
4579 foreach ($arraytoscan as $table => $element) {
4580 //print $id.'-'.$table.'-'.$elementname.'<br>';
4581 // Check if element can be deleted
4582 $sql = "SELECT COUNT(*) as nb
";
4583 $sql.= " FROM
".$this->db->prefix().$table." as c
";
4584 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4585 $sql.= ",
".$this->db->prefix().$element['parent']." as p
";
4587 $sql.= " WHERE c.
".$this->fk_element." =
".((int) $id);
4588 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4589 $sql.= " AND c.
".$element['parentkey']." = p.rowid
";
4591 if (!empty($entity)) {
4592 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4593 $sql.= " AND p.entity =
".((int) $entity);
4595 $sql.= " AND c.entity =
".((int) $entity);
4598 $resql = $this->db->query($sql);
4600 $obj = $this->db->fetch_object($resql);
4602 $langs->load("errors
");
4603 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4604 $haschild += $obj->nb;
4605 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4606 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4607 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4608 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4609 } else { // new usage: $element['name']=Translation key
4610 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4612 break; // We found at least one, we stop here
4615 $this->errors[] = $this->db->lasterror();
4619 if ($haschild > 0) {
4620 $this->errors[] = "ErrorRecordHasChildren
";
4633 public function hasProductsOrServices($predefined = -1)
4637 foreach ($this->lines as $key => $val) {
4639 if ($predefined == -1) {
4642 if ($predefined == 1 && $val->fk_product > 0) {
4645 if ($predefined == 0 && $val->fk_product <= 0) {
4648 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4651 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4658 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4667 public function getTotalDiscount()
4669 if (!empty($this->table_element_line) ) {
4670 $total_discount = 0.00;
4672 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht
";
4673 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
4674 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
4676 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4677 $resql = $this->db->query($sql);
4679 $num = $this->db->num_rows($resql);
4682 $obj = $this->db->fetch_object($resql);
4684 $pu_ht = $obj->pu_ht;
4686 $total_ht = $obj->total_ht;
4688 $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4689 $total_discount += $total_discount_line;
4695 //print $total_discount; exit;
4696 return price2num($total_discount);
4709 public function getTotalWeightVolume()
4713 // defined for shipment only
4715 // defined for shipment only
4718 foreach ($this->lines as $line) {
4719 if (isset($line->qty_asked)) {
4720 if (empty($totalOrdered)) {
4721 $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4723 $totalOrdered += $line->qty_asked; // defined for shipment only
4725 if (isset($line->qty_shipped)) {
4726 if (empty($totalToShip)) {
4727 $totalToShip = 0; // Avoid warning because $totalToShip is ''
4729 $totalToShip += $line->qty_shipped; // defined for shipment only
4730 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4731 if (empty($totalToShip)) {
4734 $totalToShip += $line->qty; // defined for reception only
4737 // Define qty, weight, volume, weight_units, volume_units
4738 if ($this->element == 'shipping') {
4740 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4742 $qty = $line->qty ? $line->qty : 0;
4745 $weight = !empty($line->weight) ? $line->weight : 0;
4746 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4747 $volume = !empty($line->volume) ? $line->volume : 0;
4748 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4750 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4751 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4752 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4753 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4757 if (!empty($weight_units)) {
4758 $weightUnit = $weight_units;
4760 if (!empty($volume_units)) {
4761 $volumeUnit = $volume_units;
4764 if (empty($totalWeight)) {
4765 $totalWeight = 0; // Avoid warning because $totalWeight is ''
4767 if (empty($totalVolume)) {
4768 $totalVolume = 0; // Avoid warning because $totalVolume is ''
4771 //var_dump($line->volume_units);
4772 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4773 $trueWeightUnit = pow(10, $weightUnit);
4774 $totalWeight += $weight * $qty * $trueWeightUnit;
4776 if ($weight_units == 99) {
4777 // conversion 1 Pound = 0.45359237 KG
4778 $trueWeightUnit = 0.45359237;
4779 $totalWeight += $weight * $qty * $trueWeightUnit;
4780 } elseif ($weight_units == 98) {
4781 // conversion 1 Ounce = 0.0283495 KG
4782 $trueWeightUnit = 0.0283495;
4783 $totalWeight += $weight * $qty * $trueWeightUnit;
4785 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4788 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4789 //print $line->volume."x
".$line->volume_units."x
".($line->volume_units < 50)."x
".$volumeUnit;
4790 $trueVolumeUnit = pow(10, $volumeUnit);
4791 //print $line->volume;
4792 $totalVolume += $volume * $qty * $trueVolumeUnit;
4794 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4798 return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4807 public function setExtraParameters()
4811 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4813 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
4814 $sql .= " SET extraparams =
".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4815 $sql .= " WHERE
rowid =
".((int) $this->id);
4818 $resql = $this->db->query($sql);
4820 $this->error = $this->db->lasterror();
4821 $this->db->rollback();
4824 $this->db->commit();
4830 // --------------------
4831 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4832 // --------------------
4834 /* This is to show add lines */
4845 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4847 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4851 if (!is_object($extrafields)) {
4852 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4853 $extrafields = new ExtraFields($this->db);
4855 $extrafields->fetch_name_optionals_label($this->table_element_line);
4857 // Output template part (modules that overwrite templates must declare this into descriptor)
4858 // Use global variables + $dateSelector + $seller and $buyer
4859 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4860 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4861 foreach ($dirtpls as $module => $reldir) {
4862 if (!empty($module)) {
4863 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4865 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4868 if (empty($conf->file->strict_mode)) {
4869 $res = @include $tpl;
4871 $res = include $tpl; // for debug
4881 /* This is to show array of line of details */
4898 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4900 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4901 // TODO We should not use global var for this
4902 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4904 // Define usemargins
4906 if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4910 $num = count($this->lines);
4913 if (!is_object($extrafields)) {
4914 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4915 $extrafields = new ExtraFields($this->db);
4917 $extrafields->fetch_name_optionals_label($this->table_element_line);
4919 $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4920 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4921 if (empty($reshook)) {
4922 // Output template part (modules that overwrite templates must declare this into descriptor)
4923 // Use global variables + $dateSelector + $seller and $buyer
4924 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4925 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4926 foreach ($dirtpls as $module => $reldir) {
4927 if (!empty($module)) {
4928 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4930 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4932 if (empty($conf->file->strict_mode)) {
4933 $res = @include $tpl;
4935 $res = include $tpl; // for debug
4946 foreach ($this->lines as $line) {
4948 $line->fetch_optionals();
4950 //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4951 if (is_object($hookmanager)) { // Old code is commented on preceding line.
4952 if (empty($line->fk_parent_line)) {
4953 $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4954 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4956 $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);
4957 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4960 if (empty($reshook)) {
4961 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4986 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4988 global $conf, $langs, $user, $object, $hookmanager;
4990 global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4992 $object_rights = $this->getRights();
4994 $element = $this->element;
4999 // Line in view mode
5000 if ($action != 'editline' || $selected != $line->id) {
5002 if ($line->fk_product > 0) {
5003 $product_static = new Product($this->db);
5004 $product_static->fetch($line->fk_product);
5006 $product_static->ref = $line->ref; //can change ref in hook
5007 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5009 $text = $product_static->getNomUrl(1);
5011 // Define output language and label
5012 if (!empty($conf->global->MAIN_MULTILANGS)) {
5013 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5014 dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5018 $prod = new Product($this->db);
5019 $prod->fetch($line->fk_product);
5021 $outputlangs = $langs;
5023 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5024 $newlang = GETPOST('lang_id', 'aZ09');
5026 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5027 $newlang = $this->thirdparty->default_lang; // To use language of customer
5029 if (!empty($newlang)) {
5030 $outputlangs = new Translate("", $conf);
5031 $outputlangs->setDefaultLang($newlang);
5034 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label
"])) ? $prod->multilangs[$outputlangs->defaultlang]["label
"] : $line->product_label;
5036 $label = $line->product_label;
5039 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5040 $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.
5043 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5045 // Output template part (modules that overwrite templates must declare this into descriptor)
5046 // Use global variables + $dateSelector + $seller and $buyer
5047 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5048 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5049 foreach ($dirtpls as $module => $reldir) {
5050 if (!empty($module)) {
5051 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5053 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5056 if (empty($conf->file->strict_mode)) {
5057 $res = @include $tpl;
5059 $res = include $tpl; // for debug
5067 // Line in update mode
5068 if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5069 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5071 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5073 // Output template part (modules that overwrite templates must declare this into descriptor)
5074 // Use global variables + $dateSelector + $seller and $buyer
5075 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5076 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5077 foreach ($dirtpls as $module => $reldir) {
5078 if (!empty($module)) {
5079 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5081 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5084 if (empty($conf->file->strict_mode)) {
5085 $res = @include $tpl;
5087 $res = include $tpl; // for debug
5097 /* This is to show array of line of details of source object */
5110 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5112 global $langs, $hookmanager, $conf, $form, $action;
5114 print '<tr class="liste_titre
">';
5115 print '<td class="linecolref
">'.$langs->trans('Ref').'</td>';
5116 print '<td class="linecoldescription
">'.$langs->trans('Description').'</td>';
5117 print '<td class="linecolvat right
">'.$langs->trans('VATRate').'</td>';
5118 print '<td class="linecoluht right
">'.$langs->trans('PriceUHT').'</td>';
5119 if (!empty($conf->multicurrency->enabled)) {
5120 print '<td class="linecoluht_currency right
">'.$langs->trans('PriceUHTCurrency').'</td>';
5122 print '<td class="linecolqty right
">'.$langs->trans('Qty').'</td>';
5123 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5124 print '<td class="linecoluseunit left
">'.$langs->trans('Unit').'</td>';
5126 print '<td class="linecoldiscount right
">'.$langs->trans('ReductionShort').'</td>';
5127 print '<td class="linecolht right
">'.$langs->trans('TotalHT').'</td>';
5128 print '<td class="center
">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5132 if (!empty($this->lines)) {
5133 foreach ($this->lines as $line) {
5135 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5136 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5137 $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5138 if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5139 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5141 if (empty($reshook)) {
5142 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5163 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5165 global $langs, $conf;
5168 if (!empty($line->date_start)) {
5169 $date_start = $line->date_start;
5171 $date_start = $line->date_debut_prevue;
5172 if ($line->date_debut_reel) {
5173 $date_start = $line->date_debut_reel;
5176 if (!empty($line->date_end)) {
5177 $date_end = $line->date_end;
5179 $date_end = $line->date_fin_prevue;
5180 if ($line->date_fin_reel) {
5181 $date_end = $line->date_fin_reel;
5185 $this->tpl['id'] = $line->id;
5187 $this->tpl['label'] = '';
5188 if (!empty($line->fk_parent_line)) {
5189 $this->tpl['label'] .= img_picto('', 'rightarrow');
5192 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5193 $discount = new DiscountAbsolute($this->db);
5194 $discount->fk_soc = $this->socid;
5195 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5196 } elseif (!empty($line->fk_product)) {
5197 $productstatic = new Product($this->db);
5198 $productstatic->id = $line->fk_product;
5199 $productstatic->ref = $line->ref;
5200 $productstatic->type = $line->fk_product_type;
5201 if (empty($productstatic->ref)) {
5202 $line->fetch_product();
5203 $productstatic = $line->product;
5206 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5207 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5209 if ($line->product_type == 1 && ($date_start || $date_end)) {
5210 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5213 $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5214 if (!empty($line->desc)) {
5215 $this->tpl['label'] .= $line->desc;
5217 $this->tpl['label'] .= ($line->label ? ' '.$line->label : '');
5221 if ($line->product_type == 1 && ($date_start || $date_end)) {
5222 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5226 if (!empty($line->desc)) {
5227 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5228 $discount = new DiscountAbsolute($this->db);
5229 $discount->fetch($line->fk_remise_except);
5230 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote
", $discount->getNomUrl(0));
5231 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5232 $discount = new DiscountAbsolute($this->db);
5233 $discount->fetch($line->fk_remise_except);
5234 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit
", $discount->getNomUrl(0));
5235 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5236 $discount = new DiscountAbsolute($this->db);
5237 $discount->fetch($line->fk_remise_except);
5238 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived
", $discount->getNomUrl(0));
5239 } elseif ($line->desc == '(EXCESS PAID)') {
5240 $discount = new DiscountAbsolute($this->db);
5241 $discount->fetch($line->fk_remise_except);
5242 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid
", $discount->getNomUrl(0));
5244 $this->tpl['description'] = dol_trunc($line->desc, 60);
5247 $this->tpl['description'] = ' ';
5251 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5252 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5253 if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5254 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5257 $this->tpl['price'] = price($line->subprice);
5258 $this->tpl['total_ht'] = price($line->total_ht);
5259 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5260 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' ';
5261 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5262 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5264 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' ';
5266 // Is the line strike or not
5267 $this->tpl['strike'] = 0;
5268 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5269 $this->tpl['strike'] = 1;
5272 // Output template part (modules that overwrite templates must declare this into descriptor)
5273 // Use global variables + $dateSelector + $seller and $buyer
5274 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5275 foreach ($dirtpls as $module => $reldir) {
5276 if (!empty($module)) {
5277 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5279 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5282 if (empty($conf->file->strict_mode)) {
5283 $res = @include $tpl;
5285 $res = include $tpl; // for debug
5294 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5305 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5310 $sql = "INSERT INTO
".$this->db->prefix()."element_resources (
";
5311 $sql .= "resource_id
";
5312 $sql .= ", resource_type
";
5313 $sql .= ", element_id
";
5314 $sql .= ", element_type
";
5316 $sql .= ", mandatory
";
5317 $sql .= ") VALUES (
";
5318 $sql .= $resource_id;
5319 $sql .= ",
'".$this->db->escape($resource_type)."'";
5320 $sql .= ",
'".$this->db->escape($this->id)."'";
5321 $sql .= ",
'".$this->db->escape($this->element)."'";
5322 $sql .= ",
'".$this->db->escape($busy)."'";
5323 $sql .= ",
'".$this->db->escape($mandatory)."'";
5327 if ($this->db->query($sql)) {
5328 $this->db->commit();
5331 $this->error = $this->db->lasterror();
5332 $this->db->rollback();
5337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5346 public function delete_resource($rowid, $element, $notrigger = 0)
5353 $sql = "DELETE FROM
".$this->db->prefix()."element_resources
";
5354 $sql .= " WHERE
rowid =
".((int) $rowid);
5358 $resql = $this->db->query($sql);
5360 $this->error = $this->db->lasterror();
5361 $this->db->rollback();
5365 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5367 $this->db->rollback();
5371 $this->db->commit();
5382 public function __clone()
5384 // Force a copy of this->lines, otherwise it will point to same object.
5385 if (isset($this->lines) && is_array($this->lines)) {
5386 $nboflines = count($this->lines);
5387 for ($i = 0; $i < $nboflines; $i++) {
5388 $this->lines[$i] = clone $this->lines[$i];
5406 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5408 global $conf, $langs, $user, $hookmanager, $action;
5410 $srctemplatepath = '';
5412 $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5413 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5415 if (empty($reshook)) {
5416 dol_syslog("commonGenerateDocument modele=
".$modele." outputlangs->defaultlang=
".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5418 if (empty($modele)) {
5419 $this->error = 'BadValueForParameterModele';
5423 // Increase limit for PDF build
5424 $err = error_reporting();
5426 @set_time_limit(120);
5427 error_reporting($err);
5429 // If selected model is a filename template (then $modele="modelname
" or "modelname:filename
")
5430 $tmp = explode(':', $modele, 2);
5431 if (!empty($tmp[1])) {
5433 $srctemplatepath = $tmp[1];
5436 // Search template files
5440 $dirmodels = array('/');
5441 if (is_array($conf->modules_parts['models'])) {
5442 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5444 foreach ($dirmodels as $reldir) {
5445 foreach (array('doc', 'pdf') as $prefix) {
5446 if (in_array(get_class($this), array('Adherent'))) {
5447 // Member module use prefix_modele.class.php
5448 $file = $prefix."_
".$modele.".class.php
";
5450 // Other module use prefix_modele.modules.php
5451 $file = $prefix."_
".$modele.".modules.php
";
5454 // On verifie l'emplacement du modele
5455 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5456 if (file_exists($file)) {
5458 $classname = $prefix.'_'.$modele;
5467 // If generator was found
5469 global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5473 $obj = new $classname($this->db);
5475 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5476 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5477 $varfortemplatedir = $obj->scandir;
5478 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5479 $dirtoscan = $conf->global->$varfortemplatedir;
5481 $listoffiles = array();
5483 // Now we add first model found in directories scanned
5484 $listofdir = explode(',', $dirtoscan);
5485 foreach ($listofdir as $key => $tmpdir) {
5486 $tmpdir = trim($tmpdir);
5487 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5489 unset($listofdir[$key]);
5492 if (is_dir($tmpdir)) {
5493 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5494 if (count($tmpfiles)) {
5495 $listoffiles = array_merge($listoffiles, $tmpfiles);
5500 if (count($listoffiles)) {
5501 foreach ($listoffiles as $record) {
5502 $srctemplatepath = $record['fullname'];
5508 if (empty($srctemplatepath)) {
5509 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5514 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5515 if (!dol_is_file($srctemplatepath)) {
5516 dol_syslog("Failed to locate
template file
".$srctemplatepath, LOG_WARNING);
5517 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5522 // We save charset_output to restore it because write_file can change it if needed for
5523 // output format that does not support UTF8.
5524 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5526 if (in_array(get_class($this), array('Adherent'))) {
5527 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5529 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5531 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5533 if ($resultwritefile > 0) {
5534 $outputlangs->charset_output = $sav_charset_output;
5536 // We delete old preview
5537 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5538 dol_delete_preview($this);
5540 // Index file in database
5541 if (!empty($obj->result['fullpath'])) {
5542 $destfull = $obj->result['fullpath'];
5544 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5545 $update_main_doc_field = 0;
5546 if (!empty($obj->update_main_doc_field)) {
5547 $update_main_doc_field = 1;
5550 $this->indexFile($destfull, $update_main_doc_field);
5552 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);
5555 // Success in building document. We build meta file.
5556 dol_meta_create($this);
5560 $outputlangs->charset_output = $sav_charset_output;
5561 $this->error = $obj->error;
5562 $this->errors = $obj->errors;
5563 dol_syslog("Error generating document
for ".__CLASS__.". Error:
".$obj->error, LOG_ERR);
5568 $this->error = $langs->trans("Error
").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5569 $this->errors[] = $this->error;
5570 dol_syslog($this->error, LOG_ERR);
5572 $this->error = $langs->trans("Error
")." ".$langs->trans("ErrorFileDoesNotExists
", $filefound);
5573 $this->errors[] = $this->error;
5574 dol_syslog($this->error, LOG_ERR);
5592 public function indexFile($destfull, $update_main_doc_field)
5594 global $conf, $user;
5596 $upload_dir = dirname($destfull);
5597 $destfile = basename($destfull);
5598 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5600 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5601 $filename = basename($destfile);
5602 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5603 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5605 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5606 $ecmfile = new EcmFiles($this->db);
5607 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5609 // Set the public "share
" key
5610 $setsharekey = false;
5611 if ($this->element == 'propal' || $this->element == 'proposal') {
5612 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5613 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5615 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5616 $setsharekey = true;
5619 if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5620 $setsharekey = true;
5622 if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5623 $setsharekey = true;
5625 if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5626 $setsharekey = true;
5628 if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5629 $setsharekey = true;
5631 if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5632 $setsharekey = true;
5636 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5637 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5638 $ecmfile->share = getRandomPassword(true);
5643 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5644 $ecmfile->fullpath_orig = '';
5645 $ecmfile->gen_or_uploaded = 'generated';
5646 $ecmfile->description = ''; // indexed content
5647 $ecmfile->keywords = ''; // keyword content
5648 $result = $ecmfile->update($user);
5650 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5654 $ecmfile->entity = $conf->entity;
5655 $ecmfile->filepath = $rel_dir;
5656 $ecmfile->filename = $filename;
5657 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5658 $ecmfile->fullpath_orig = '';
5659 $ecmfile->gen_or_uploaded = 'generated';
5660 $ecmfile->description = ''; // indexed content
5661 $ecmfile->keywords = ''; // keyword content
5662 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5663 $ecmfile->src_object_id = $this->id;
5665 $result = $ecmfile->create($user);
5667 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5672 /*$this->result['fullname']=$destfull;
5673 $this->result['filepath']=$ecmfile->filepath;
5674 $this->result['filename']=$ecmfile->filename;*/
5675 //var_dump($obj->update_main_doc_field);exit;
5677 if ($update_main_doc_field && !empty($this->table_element)) {
5678 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET last_main_doc =
'".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5679 $sql .= " WHERE
rowid =
".((int) $this->id);
5681 $resql = $this->db->query($sql);
5683 dol_print_error($this->db);
5686 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5701 public function addThumbs($file)
5703 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5705 $tmparraysize = getDefaultImageSizes();
5706 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5707 $maxheightsmall = $tmparraysize['maxheightsmall'];
5708 $maxwidthmini = $tmparraysize['maxwidthmini'];
5709 $maxheightmini = $tmparraysize['maxheightmini'];
5710 //$quality = $tmparraysize['quality'];
5711 $quality = 50; // For thumbs, we force quality to 50
5713 $file_osencoded = dol_osencode($file);
5714 if (file_exists($file_osencoded)) {
5715 // Create small thumbs for company (Ratio is near 16/9)
5716 // Used on logon for example
5717 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5719 // Create mini thumbs for company (Ratio is near 16/9)
5720 // Used on menu or for setup page for example
5721 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5726 /* Functions common to commonobject and commonobjectline */
5728 /* For default values */
5742 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5744 global $conf, $_POST;
5746 // If param here has been posted, we use this value first.
5747 if (GETPOSTISSET($fieldname)) {
5748 return GETPOST($fieldname, 'alphanohtml', 3);
5751 if (isset($alternatevalue)) {
5752 return $alternatevalue;
5755 $newelement = $this->element;
5756 if ($newelement == 'facture') {
5757 $newelement = 'invoice';
5759 if ($newelement == 'commande') {
5760 $newelement = 'order';
5762 if (empty($newelement)) {
5763 dol_syslog("Ask a
default value
using common method getDefaultCreateValueForField on an
object with no property ->element defined. Return empty
string.
", LOG_WARNING);
5767 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5768 //var_dump($keyforfieldname);
5769 if (isset($conf->global->$keyforfieldname)) {
5770 return $conf->global->$keyforfieldname;
5773 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5780 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5791 public function call_trigger($triggerName, $user)
5794 global $langs, $conf;
5795 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5796 dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_
" as required.');
5799 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5800 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5801 $langs = new Translate('', $conf);
5804 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5805 $interface = new Interfaces($this->db);
5806 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5809 if (!empty($this->errors)) {
5810 $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.
5812 $this->errors = $interface->errors;
5819 /* Functions for data in other language */
5829 public function fetchValuesForExtraLanguages()
5831 // To avoid SQL errors. Probably not the better solution though
5832 if (!$this->element) {
5835 if (!($this->id > 0)) {
5838 if (is_array($this->array_languages)) {
5842 $this->array_languages = array();
5844 $element = $this->element;
5845 if ($element == 'categorie') {
5846 $element = 'categories'; // For compatibility
5849 // Request to get translation values for object
5850 $sql = "SELECT
rowid, property, lang , value
";
5851 $sql .= " FROM
".$this->db->prefix()."object_lang
";
5852 $sql .= " WHERE type_object =
'".$this->db->escape($element)."'";
5853 $sql .= " AND fk_object =
".((int) $this->id);
5855 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
5856 $resql = $this->db->query($sql);
5858 $numrows = $this->db->num_rows($resql);
5861 while ($i < $numrows) {
5862 $obj = $this->db->fetch_object($resql);
5863 $key = $obj->property;
5864 $value = $obj->value;
5865 $codelang = $obj->lang;
5866 $type = $this->fields[$key]['type'];
5868 // we can add this attribute to object
5869 if (preg_match('/date/', $type)) {
5870 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5872 $this->array_languages[$key][$codelang] = $value;
5879 $this->db->free($resql);
5887 dol_print_error($this->db);
5898 public function setValuesForExtraLanguages($onlykey = '')
5900 global $_POST, $langs;
5903 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5904 $tmparray = explode('-', $postfieldkey);
5905 if ($tmparray[0] != 'field') {
5909 $element = $tmparray[1];
5910 $key = $tmparray[2];
5911 $codelang = $tmparray[3];
5912 //var_dump("postfieldkey=
".$postfieldkey." element=
".$element." key=
".$key." codelang=
".$codelang);
5914 if (!empty($onlykey) && $key != $onlykey) {
5917 if ($element != $this->element) {
5921 $key_type = $this->fields[$key]['type'];
5924 if (isset($this->fields[$key]['enabled'])) {
5925 $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5928 if (isset($this->fields[$key]['perms']))
5930 $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5932 if (empty($enabled)) {
5935 //if (empty($perms)) continue;
5937 if (in_array($key_type, array('date'))) {
5939 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5940 $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month
", 'int'), GETPOST($postfieldkey."day
", 'int'), GETPOST($postfieldkey."year
", 'int'));
5941 } elseif (in_array($key_type, array('datetime'))) {
5943 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5944 $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'));
5945 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5946 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5947 if (!empty($value_arr)) {
5948 $value_key = implode(',', $value_arr);
5952 } elseif (in_array($key_type, array('price', 'double'))) {
5953 $value_arr = GETPOST($postfieldkey, 'alpha');
5954 $value_key = price2num($value_arr);
5956 $value_key = GETPOST($postfieldkey);
5957 if (in_array($key_type, array('link')) && $value_key == '-1') {
5962 $this->array_languages[$key][$codelang] = $value_key;
5964 /*if ($nofillrequired) {
5965 $langs->load('errors');
5966 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5975 /* Functions for extrafields */
5983 public function fetchNoCompute($id)
5987 $savDisableCompute = $conf->disable_compute;
5988 $conf->disable_compute = 1;
5990 $ret = $this->fetch($id);
5992 $conf->disable_compute = $savDisableCompute;
5997 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6007 public function fetch_optionals($rowid = null, $optionsArray = null)
6010 global $conf, $extrafields;
6012 if (empty($rowid)) {
6015 if (empty($rowid) && isset($this->rowid)) {
6016 $rowid = $this->rowid; // deprecated
6019 // To avoid SQL errors. Probably not the better solution though
6020 if (!$this->table_element) {
6024 $this->array_options = array();
6026 if (!is_array($optionsArray)) {
6027 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6028 if (!isset($extrafields) || !is_object($extrafields)) {
6029 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6030 $extrafields = new ExtraFields($this->db);
6033 // Load array of extrafields for elementype = $this->table_element
6034 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6035 $extrafields->fetch_name_optionals_label($this->table_element);
6037 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6039 global $extrafields;
6040 dol_syslog("Warning:
fetch_optionals was called with param optionsArray defined when you should pass
null now
", LOG_WARNING);
6043 $table_element = $this->table_element;
6044 if ($table_element == 'categorie') {
6045 $table_element = 'categories'; // For compatibility
6048 // Request to get complementary values
6049 if (is_array($optionsArray) && count($optionsArray) > 0) {
6050 $sql = "SELECT
rowid";
6051 foreach ($optionsArray as $name => $label) {
6052 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6056 $sql .= " FROM
".$this->db->prefix().$table_element."_extrafields
";
6057 $sql .= " WHERE fk_object =
".((int) $rowid);
6059 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
6060 $resql = $this->db->query($sql);
6062 $numrows = $this->db->num_rows($resql);
6064 $tab = $this->db->fetch_array($resql);
6066 foreach ($tab as $key => $value) {
6067 // 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)
6068 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6069 // we can add this attribute to object
6070 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6071 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6072 $this->array_options["options_
".$key] = $this->db->jdate($value);
6074 $this->array_options["options_
".$key] = $value;
6077 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_
".$key]);
6082 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6083 // in the element's extrafields table)
6084 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6085 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6086 //var_dump($conf->disable_compute);
6087 if (empty($conf->disable_compute)) {
6088 global $objectoffield; // We set a global variable to $objectoffield so
6089 $objectoffield = $this; // we can use it inside computed formula
6090 $this->array_options["options_
".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6095 $this->db->free($resql);
6103 $this->errors[]=$this->db->lasterror;
6116 public function deleteExtraFields()
6120 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6126 $table_element = $this->table_element;
6127 if ($table_element == 'categorie') {
6128 $table_element = 'categories'; // For compatibility
6133 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6135 $resql = $this->db->query($sql_del);
6137 $this->error = $this->db->lasterror();
6138 $this->db->rollback();
6141 $this->db->commit();
6156 public function insertExtraFields($trigger = '', $userused = null)
6158 global $conf, $langs, $user;
6160 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6164 if (empty($userused)) {
6170 if (!empty($this->array_options)) {
6172 $langs->load('admin');
6173 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6174 $extrafields = new ExtraFields($this->db);
6175 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6177 // Eliminate copied source object extra fields that do not exist in target object
6178 $new_array_options = array();
6179 foreach ($this->array_options as $key => $value) {
6180 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6181 $new_array_options[$key] = $value;
6182 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6183 $new_array_options['options_'.$key] = $value;
6187 foreach ($new_array_options as $key => $value) {
6188 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6189 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6190 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6191 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6192 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6193 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6194 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6196 // If we clone, we have to clean unique extrafields to prevent duplicates.
6197 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6198 if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
6199 $new_array_options[$key] = null;
6202 // Similar code than into insertExtraFields
6203 if ($attributeRequired) {
6204 $mandatorypb = false;
6205 if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6206 $mandatorypb = true;
6208 if ($this->array_options[$key] === '') {
6209 $mandatorypb = true;
6211 if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6212 $mandatorypb = true;
6215 $langs->load("errors
");
6216 dol_syslog("Mandatory field
'".$key."' is empty during create and
set to required into definition of extrafields
");
6217 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6222 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6223 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6225 if (!empty($attrfieldcomputed)) {
6226 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6227 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6228 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6229 $new_array_options[$key] = $value;
6231 $new_array_options[$key] = null;
6235 switch ($attributeType) {
6237 if (!is_numeric($value) && $value != '') {
6238 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6240 } elseif ($value == '') {
6241 $new_array_options[$key] = null;
6246 $value = price2num($value);
6247 if (!is_numeric($value) && $value != '') {
6248 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." for ".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6249 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6251 } elseif ($value == '') {
6254 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6255 $new_array_options[$key] = $value;
6257 /*case 'select': // Not required, we chosed value='0' for undefined values
6260 $this->array_options[$key] = null;
6265 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6266 // If there is an encryption choice, we use it to crypt data before insert
6267 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6268 $algo = reset($tmparrays);
6270 //global $action; // $action may be 'create', 'update', 'update_extras'...
6271 //var_dump($action);
6272 //var_dump($this->oldcopy);exit;
6273 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
6274 //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6275 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.
6276 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6279 $newvalue = dol_hash($this->array_options[$key], $algo);
6280 $new_array_options[$key] = $newvalue;
6283 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6286 } else // Common usage
6288 $new_array_options[$key] = $this->array_options[$key];
6293 // If data is a string instead of a timestamp, we convert it
6294 if (!is_int($this->array_options[$key])) {
6295 $this->array_options[$key] = strtotime($this->array_options[$key]);
6297 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6300 $param_list = array_keys($attributeParam['options']);
6303 $InfoFieldList = explode(":
", $param_list[0]);
6304 dol_include_once($InfoFieldList[1]);
6305 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6306 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6307 $new_array_options[$key] = '';
6309 $object = new $InfoFieldList[0]($this->db);
6310 if (is_numeric($value)) {
6311 $res = $object->fetch($value); // Common case
6313 $res = $object->fetch('', $value); // For compatibility
6317 $new_array_options[$key] = $object->id;
6319 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6324 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6332 $table_element = $this->table_element;
6333 if ($table_element == 'categorie') {
6334 $table_element = 'categories'; // For compatibility
6337 dol_syslog(get_class($this)."::
insertExtraFields delete then insert
", LOG_DEBUG);
6339 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6340 $this->db->query($sql_del);
6342 $sql = "INSERT INTO
".$this->db->prefix().$table_element."_extrafields (fk_object
";
6343 foreach ($new_array_options as $key => $value) {
6344 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6345 // Add field of attribut
6346 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6347 $sql .= ",
".$attributeKey;
6350 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6351 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6352 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6353 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6354 $sql .= ",
".$tmpkey;
6358 $sql .= ") VALUES (
".$this->id;
6360 foreach ($new_array_options as $key => $value) {
6361 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6362 // Add field of attribute
6363 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6364 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6365 $sql .= ",
'".$this->db->escape($new_array_options[$key])."'";
6371 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6372 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6373 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6374 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6375 if (in_array($tmpval, array('int', 'double', 'price'))) {
6386 $resql = $this->db->query($sql);
6388 $this->error = $this->db->lasterror();
6392 if (!$error && $trigger) {
6394 $this->context = array('extrafieldaddupdate'=>1);
6395 $result = $this->call_trigger($trigger, $userused);
6403 $this->db->rollback();
6406 $this->db->commit();
6424 public function insertExtraLanguages($trigger = '', $userused = null)
6426 global $conf, $langs, $user;
6428 if (empty($userused)) {
6434 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6435 return 0; // For avoid conflicts if trigger used
6438 if (is_array($this->array_languages)) {
6439 $new_array_languages = $this->array_languages;
6441 foreach ($new_array_languages as $key => $value) {
6442 $attributeKey = $key;
6443 $attributeType = $this->fields[$attributeKey]['type'];
6444 $attributeLabel = $this->fields[$attributeKey]['label'];
6446 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6447 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6449 switch ($attributeType) {
6451 if (!is_numeric($value) && $value != '') {
6452 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6454 } elseif ($value == '') {
6455 $new_array_languages[$key] = null;
6459 $value = price2num($value);
6460 if (!is_numeric($value) && $value != '') {
6461 dol_syslog($langs->trans("ExtraLanguageHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6462 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6464 } elseif ($value == '') {
6465 $new_array_languages[$key] = null;
6467 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6468 $new_array_languages[$key] = $value;
6470 /*case 'select': // Not required, we chosed value='0' for undefined values
6473 $this->array_options[$key] = null;
6481 $table_element = $this->table_element;
6482 if ($table_element == 'categorie') {
6483 $table_element = 'categories'; // For compatibility
6488 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6489 foreach ($langcodearray as $langcode => $value) {
6490 $sql_del = "DELETE FROM
".$this->db->prefix()."object_lang
";
6491 $sql_del .= " WHERE fk_object =
".((int) $this->id)." AND property =
'".$this->db->escape($key)."' AND type_object =
'".$this->db->escape($table_element)."'";
6492 $sql_del .= " AND lang =
'".$this->db->escape($langcode)."'";
6493 $this->db->query($sql_del);
6495 if ($value !== '') {
6496 $sql = "INSERT INTO
".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value
";
6497 $sql .= ") VALUES (
".$this->id.",
'".$this->db->escape($key)."',
'".$this->db->escape($table_element)."',
'".$this->db->escape($langcode)."',
'".$this->db->escape($value)."'";
6500 $resql = $this->db->query($sql);
6502 $this->error = $this->db->lasterror();
6510 if (!$error && $trigger) {
6512 $this->context = array('extralanguagesaddupdate'=>1);
6513 $result = $this->call_trigger($trigger, $userused);
6521 $this->db->rollback();
6524 $this->db->commit();
6542 public function updateExtraField($key, $trigger = null, $userused = null)
6544 global $conf, $langs, $user;
6546 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6550 if (empty($userused)) {
6556 if (!empty($this->array_options) && isset($this->array_options["options_
".$key])) {
6558 $langs->load('admin');
6559 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6560 $extrafields = new ExtraFields($this->db);
6561 $extrafields->fetch_name_optionals_label($this->table_element);
6563 $value = $this->array_options["options_
".$key];
6565 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6566 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6567 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6568 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6569 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6571 // Similar code than into insertExtraFields
6572 if ($attributeRequired) {
6573 $mandatorypb = false;
6574 if ($attributeType == 'link' && $this->array_options["options_
".$key] == '-1') {
6575 $mandatorypb = true;
6577 if ($this->array_options["options_
".$key] === '') {
6578 $mandatorypb = true;
6581 $langs->load("errors
");
6582 dol_syslog("Mandatory field
'options_".$key."' is empty during update and
set to required into definition of extrafields
");
6583 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6588 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6589 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6591 if (!empty($attrfieldcomputed)) {
6592 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6593 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6594 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6595 $this->array_options["options_
".$key] = $value;
6597 $this->array_options["options_
".$key] = null;
6601 switch ($attributeType) {
6603 if (!is_numeric($value) && $value != '') {
6604 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6606 } elseif ($value === '') {
6607 $this->array_options["options_
".$key] = null;
6611 $value = price2num($value);
6612 if (!is_numeric($value) && $value != '') {
6613 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6614 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6616 } elseif ($value === '') {
6619 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6620 $this->array_options["options_
".$key] = $value;
6622 /*case 'select': // Not required, we chosed value='0' for undefined values
6625 $this->array_options[$key] = null;
6629 $this->array_options["options_
".$key] = price2num($this->array_options["options_
".$key]);
6633 if (empty($this->array_options["options_
".$key])) {
6634 $this->array_options["options_
".$key] = null;
6636 $this->array_options["options_
".$key] = $this->db->idate($this->array_options["options_
".$key]);
6640 if (empty($this->array_options["options_
".$key])) {
6641 $this->array_options["options_
".$key] = null;
6645 if ($this->array_options["options_
".$key] === '') {
6646 $this->array_options["options_
".$key] = null;
6651 $param_list = array_keys($attributeParam['options']);
6654 $InfoFieldList = explode(":
", $param_list[0]);
6655 dol_include_once($InfoFieldList[1]);
6656 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6658 if ($value == '-1') // -1 is key for no defined in combo list of objects
6660 $new_array_options[$key] = '';
6662 $object = new $InfoFieldList[0]($this->db);
6663 if (is_numeric($value)) $res = $object->fetch($value); // Common case
6664 else $res = $object->fetch('', $value); // For compatibility
6666 if ($res > 0) $new_array_options[$key] = $object->id;
6668 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6669 $this->db->rollback();
6674 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6682 $linealreadyfound = 0;
6684 // 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)
6685 $sql = "SELECT COUNT(
rowid) as nb FROM
".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6686 $resql = $this->db->query($sql);
6688 $tmpobj = $this->db->fetch_object($resql);
6690 $linealreadyfound = $tmpobj->nb;
6694 if ($linealreadyfound) {
6695 if ($this->array_options["options_
".$key] === null) {
6696 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
null";
6698 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
'".$this->db->escape($this->array_options["options_".$key])."'";
6700 $sql .= " WHERE fk_object =
".((int) $this->id);
6702 $result = $this->insertExtraFields('', $user);
6708 $resql = $this->db->query($sql);
6711 $this->error = $this->db->lasterror();
6713 if (!$error && $trigger) {
6715 $this->context = array('extrafieldupdate'=>1);
6716 $result = $this->call_trigger($trigger, $userused);
6724 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6725 $this->db->rollback();
6728 $this->db->commit();
6746 public function updateExtraLanguages($key, $trigger = null, $userused = null)
6748 global $conf, $langs, $user;
6750 if (empty($userused)) {
6756 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6757 return 0; // For avoid conflicts if trigger used
6778 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6780 global $conf, $langs, $form;
6782 if (!is_object($form)) {
6783 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6784 $form = new Form($this->db);
6787 if (!empty($this->fields)) {
6788 $val = $this->fields[$key];
6791 // Validation tests and output
6792 $fieldValidationErrorMsg = '';
6793 $validationClass = '';
6794 $fieldValidationErrorMsg = $this->getFieldError($key);
6795 if (!empty($fieldValidationErrorMsg)) {
6796 $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
6798 $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
6805 $param['options'] = array();
6807 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6808 // Because we work on extrafields
6809 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6810 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6812 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6813 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6815 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6816 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6818 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6819 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6821 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6822 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6824 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6825 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6827 } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6828 $param['options'] = array();
6831 } elseif (preg_match('/varchar/', $val['type'])) {
6832 $param['options'] = array();
6835 $param['options'] = array();
6836 $type = $this->fields[$key]['type'];
6839 // Special case that force options and type ($type can be integer, varchar, ...)
6840 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6841 $param['options'] = $this->fields[$key]['arrayofkeyval'];
6845 $label = $this->fields[$key]['label'];
6846 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6847 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6848 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6849 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6850 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6851 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6853 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6854 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6855 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6857 $objectid = $this->id;
6860 if (!preg_match('/^search_/', $keyprefix)) {
6861 return '<span class="opacitymedium
">'.$langs->trans("AutomaticallyCalculated
").'</span>';
6867 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6868 if (empty($morecss) && !empty($val['css'])) {
6869 $morecss = $val['css'];
6870 } elseif (empty($morecss)) {
6871 if ($type == 'date') {
6872 $morecss = 'minwidth100imp';
6873 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6874 $morecss = 'minwidth200imp';
6875 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6876 $morecss = 'maxwidth75';
6877 } elseif ($type == 'url') {
6878 $morecss = 'minwidth400';
6879 } elseif ($type == 'boolean') {
6882 if (round($size) < 12) {
6883 $morecss = 'minwidth100';
6884 } elseif (round($size) <= 48) {
6885 $morecss = 'minwidth200';
6887 $morecss = 'minwidth400';
6892 // Add validation state class
6893 if (!empty($validationClass)) {
6894 $morecss.= $validationClass;
6897 if (in_array($type, array('date'))) {
6898 $tmp = explode(',', $size);
6902 // Do not show current date when field not required (see selectDate() method)
6903 if (!$required && $value == '') {
6907 // TODO Must also support $moreparam
6908 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6909 } elseif (in_array($type, array('datetime'))) {
6910 $tmp = explode(',', $size);
6914 // Do not show current date when field not required (see selectDate() method)
6915 if (!$required && $value == '') $value = '-1';
6917 // TODO Must also support $moreparam
6918 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6919 } elseif (in_array($type, array('duration'))) {
6920 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6921 } elseif (in_array($type, array('int', 'integer'))) {
6922 $tmp = explode(',', $size);
6924 $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' : '').'>';
6925 } elseif (in_array($type, array('real'))) {
6926 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6927 } elseif (preg_match('/varchar/', $type)) {
6928 $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' : '').'>';
6929 } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
6930 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6931 } elseif (preg_match('/^text/', $type)) {
6932 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6933 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6934 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6935 $out = $doleditor->Create(1);
6937 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6939 } elseif (preg_match('/^html/', $type)) {
6940 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6941 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6942 $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%');
6943 $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6945 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6947 } elseif ($type == 'boolean') {
6949 if (!empty($value)) {
6950 $checked = ' checked value="1
" ';
6952 $checked = ' value="1
" ';
6954 $out = '<input type="checkbox
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6955 } elseif ($type == 'price') {
6956 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6957 $value = price($value);
6959 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6960 } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6961 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6962 $value = price($value);
6964 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6965 } elseif ($type == 'select') {
6967 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6968 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6969 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6972 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6973 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6974 $out .= '<option value="0
"> </option>';
6976 foreach ($param['options'] as $keyb => $valb) {
6977 if ((string) $keyb == '') {
6980 if (strpos($valb, "|
") !== false) {
6981 list($valb, $parent) = explode('|', $valb);
6983 $out .= '<option value="'.$keyb.'"';
6984 $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6985 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6986 $out .= '>'.$valb.'</option>';
6988 $out .= '</select>';
6989 } elseif ($type == 'sellist') {
6991 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6992 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6993 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6996 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6997 if (is_array($param['options'])) {
6998 $param_list = array_keys($param['options']);
6999 $InfoFieldList = explode(":
", $param_list[0]);
7003 // 1 : label field name
7004 // 2 : key fields name (if differ of rowid)
7005 // 3 : key field parent (for dependent lists)
7006 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7007 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7009 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7010 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7011 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7013 $keyList = $InfoFieldList[2].' as rowid';
7016 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7017 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7018 $keyList .= ', '.$parentField;
7021 $fields_label = explode('|', $InfoFieldList[1]);
7022 if (is_array($fields_label)) {
7024 $keyList .= implode(', ', $fields_label);
7028 $sql = "SELECT
".$keyList;
7029 $sql .= " FROM
".$this->db->prefix().$InfoFieldList[0];
7030 if (!empty($InfoFieldList[4])) {
7031 // can use SELECT request
7032 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7033 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7036 // current object id can be use into filter
7037 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7038 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7040 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7043 //We have to join on extrafield table
7044 if (strpos($InfoFieldList[4], 'extra') !== false) {
7045 $sql .= " as main,
".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra
";
7046 $sqlwhere .= " WHERE extra.fk_object=main.
".$InfoFieldList[2]." AND
".$InfoFieldList[4];
7048 $sqlwhere .= " WHERE
".$InfoFieldList[4];
7051 $sqlwhere .= ' WHERE 1=1';
7053 // Some tables may have field, some other not. For the moment we disable it.
7054 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7055 $sqlwhere .= " AND entity =
".((int) $conf->entity);
7060 $sql .= ' ORDER BY '.implode(', ', $fields_label);
7062 dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
7063 $resql = $this->db->query($sql);
7065 $out .= '<option value="0
"> </option>';
7066 $num = $this->db->num_rows($resql);
7070 $obj = $this->db->fetch_object($resql);
7072 // Several field into label (eq table:code|libelle:rowid)
7074 $fields_label = explode('|', $InfoFieldList[1]);
7075 if (count($fields_label) > 1) {
7077 foreach ($fields_label as $field_toshow) {
7078 $labeltoshow .= $obj->$field_toshow.' ';
7081 $labeltoshow = $obj->{$InfoFieldList[1]};
7083 $labeltoshow = dol_trunc($labeltoshow, 45);
7085 if ($value == $obj->rowid) {
7086 foreach ($fields_label as $field_toshow) {
7087 $translabel = $langs->trans($obj->$field_toshow);
7088 if ($translabel != $obj->$field_toshow) {
7089 $labeltoshow = dol_trunc($translabel).' ';
7091 $labeltoshow = dol_trunc($obj->$field_toshow).' ';
7094 $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7097 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7098 if ($translabel != $obj->{$InfoFieldList[1]}) {
7099 $labeltoshow = dol_trunc($translabel, 18);
7101 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7104 if (empty($labeltoshow)) {
7105 $labeltoshow = '(not defined)';
7107 if ($value == $obj->rowid) {
7108 $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7111 if (!empty($InfoFieldList[3]) && $parentField) {
7112 $parent = $parentName.':'.$obj->{$parentField};
7116 $out .= '<option value="'.$obj->rowid.'"';
7117 $out .= ($value == $obj->rowid ? ' selected' : '');
7118 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7119 $out .= '>'.$labeltoshow.'</option>';
7124 $this->db->free($resql);
7126 print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7129 $out .= '</select>';
7130 } elseif ($type == 'checkbox') {
7131 $value_arr = explode(',', $value);
7132 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7133 } elseif ($type == 'radio') {
7135 foreach ($param['options'] as $keyopt => $valopt) {
7136 $out .= '<input class="flat
'.$morecss.'" type="radio
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7137 $out .= ' value="'.$keyopt.'"';
7138 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'"';
7139 $out .= ($value == $keyopt ? 'checked' : '');
7140 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'">'.$valopt.'</label><br>';
7142 } elseif ($type == 'chkbxlst') {
7143 if (is_array($value)) {
7144 $value_arr = $value;
7146 $value_arr = explode(',', $value);
7149 if (is_array($param['options'])) {
7150 $param_list = array_keys($param['options']);
7151 $InfoFieldList = explode(":
", $param_list[0]);
7155 // 1 : label field name
7156 // 2 : key fields name (if differ of rowid)
7157 // 3 : key field parent (for dependent lists)
7158 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7159 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7161 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7162 list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7163 $keyList .= ', '.$parentField;
7165 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7166 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7167 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7169 $keyList = $InfoFieldList[2].' as rowid';
7173 $fields_label = explode('|', $InfoFieldList[1]);
7174 if (is_array($fields_label)) {
7176 $keyList .= implode(', ', $fields_label);
7180 $sql = "SELECT
".$keyList;
7181 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7182 if (!empty($InfoFieldList[4])) {
7183 // can use SELECT request
7184 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7185 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7188 // current object id can be use into filter
7189 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7190 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7192 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7195 // We have to join on extrafield table
7196 if (strpos($InfoFieldList[4], 'extra') !== false) {
7197 $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
7198 $sqlwhere .= " WHERE extra.fk_object=main.
".$InfoFieldList[2]." AND
".$InfoFieldList[4];
7200 $sqlwhere .= " WHERE
".$InfoFieldList[4];
7203 $sqlwhere .= ' WHERE 1=1';
7205 // Some tables may have field, some other not. For the moment we disable it.
7206 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7207 $sqlwhere .= " AND entity =
".((int) $conf->entity);
7209 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7213 dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
7214 $resql = $this->db->query($sql);
7216 $num = $this->db->num_rows($resql);
7223 $obj = $this->db->fetch_object($resql);
7226 // Several field into label (eq table:code|libelle:rowid)
7227 $fields_label = explode('|', $InfoFieldList[1]);
7228 if (count($fields_label) > 1) {
7230 foreach ($fields_label as $field_toshow) {
7231 $labeltoshow .= $obj->$field_toshow.' ';