46 const TRIGGER_PREFIX =
'';
76 public $errors = array();
81 public $validateFieldsErrors = array();
91 public $element_for_permission;
96 public $table_element;
101 public $table_element_line =
'';
111 public $array_options = array();
116 public $array_languages = null;
121 public $contacts_ids;
126 public $linked_objects;
131 public $linkedObjectsIds;
136 public $linkedObjects;
141 public $linkedObjectsFullLoaded = array();
151 protected $table_ref_field =
'';
156 public $restrictiononfksoc = 0;
164 public $context = array();
244 public $ref_previous;
285 public $country_code;
328 public $barcode_type;
334 public $barcode_type_code;
340 public $barcode_type_label;
346 public $barcode_type_coder;
352 public $mode_reglement_id;
358 public $cond_reglement_id;
363 public $demand_reason_id;
369 public $transport_mode_id;
376 public $cond_reglement;
383 public $fk_delivery_address;
389 public $shipping_method_id;
408 public $last_main_doc;
438 public $note_private;
462 public $total_localtax1;
468 public $total_localtax2;
485 public $comments = array();
511 public $date_creation;
516 public $date_validation;
521 public $date_modification;
526 public $date_cloture;
537 public $user_creation;
541 public $user_creation_id;
552 public $user_validation;
556 public $user_validation_id;
560 public $user_closing_id;
566 public $user_modification;
570 public $user_modification_id;
573 public $next_prev_filter;
578 public $specimen = 0;
594 protected $childtables = array();
601 protected $childtablesoncascade = array();
621 $sql =
"SELECT rowid, ref, ref_ext";
622 $sql .=
" FROM ".$db->prefix().$element;
623 $sql .=
" WHERE entity IN (".getEntity($element).
")";
626 $sql .=
" AND rowid = ".((int) $id);
628 $sql .=
" AND ref = '".$db->escape($ref).
"'";
629 } elseif ($ref_ext) {
630 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
632 $error =
'ErrorWrongParameters';
636 if ($ref || $ref_ext) {
637 $sql .=
" AND entity = ".((int) $conf->entity);
640 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
641 $resql = $db->query($sql);
643 $num = $db->num_rows(
$resql);
661 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
675 $parameters = array(
'objref'=>$objref);
677 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
679 return $hookmanager->resArray[
'objref'];
681 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
694 $parameters = array(
'objref'=>$objref);
696 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
698 return $hookmanager->resArray[
'objref'];
700 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
712 public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
715 $lastname = $this->lastname;
716 $firstname = $this->firstname;
717 if (empty($lastname)) {
718 $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->
name) ? $this->
name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company :
'')))));
722 if (!empty($option) && !empty($this->civility_code)) {
723 if ($langs->transnoentitiesnoconv(
"Civility".$this->civility_code) !=
"Civility".$this->civility_code) {
724 $ret .= $langs->transnoentitiesnoconv(
"Civility".$this->civility_code).
' ';
726 $ret .= $this->civility_code.
' ';
743 if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
749 if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
754 if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
768 $return =
'<div class="box-flex-item box-flex-grow-zero">';
769 $return .=
'<div class="info-box info-box-sm">';
770 $return .=
'<span class="info-box-icon bg-infobox-action">';
773 $return .=
'</span>';
774 $return .=
'<div class="info-box-content">';
775 $return .=
'<span class="info-box-ref">'.(method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref).
'</span>';
776 if (property_exists($this,
'label')) {
777 $return .=
'<br><span class="info-box-label opacitymedium">'.$this->label.
'</span>';
779 if (method_exists($this,
'getLibStatut')) {
780 $return .=
'<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).
'</div>';
798 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
800 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
801 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
802 $tmparray =
getCountry($this->country_id,
'all');
803 $this->country_code = $tmparray[
'code'];
804 $this->country = $tmparray[
'label'];
807 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
808 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
809 $tmparray =
getState($this->state_id,
'all', 0, 1);
810 $this->state_code = $tmparray[
'code'];
811 $this->state = $tmparray[
'label'];
812 $this->region_code = $tmparray[
'region_code'];
813 $this->region = $tmparray[
'region'];
829 global $conf, $langs,
$form, $extralanguages;
831 $countriesusingstate = array(
'AU',
'US',
'IN',
'GB',
'ES',
'UK',
'TR');
835 $elementforaltlanguage = $this->element;
836 if ($this->element ==
'societe') {
837 $thirdpartyid = $this->id;
839 if ($this->element ==
'contact') {
840 $contactid = $this->id;
841 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
843 if ($this->element ==
'user') {
844 $contactid = $this->contact_id;
845 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
851 $coords = $this->
getFullAddress(1,
', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
853 if (!empty($conf->use_javascript_ajax)) {
856 if ($this->element ==
'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
857 $namecoords .= $object->name.
'<br>';
859 $namecoords .= $this->
getFullName($langs, 1).
'<br>'.$coords;
861 $out .=
'<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).
'\',\
''.dol_escape_js($langs->trans(
"HelpCopyToClipboard")).
'\');
">';
862 $out .= img_picto($langs->trans("Address
"), 'map-marker-alt');
865 $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
869 // List of extra languages
870 $arrayoflangcode = array();
871 if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
872 $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
875 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
876 if (!is_object($extralanguages)) {
877 include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
878 $extralanguages = new ExtraLanguages($this->db);
880 $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
882 if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
883 $out .= "<!-- alternatelanguage
for '".$elementforaltlanguage."' set to fields
'".join(',
', $extralanguages->attributes[$elementforaltlanguage])."' -->\n
";
884 $this->fetchValuesForExtraLanguages();
885 if (!is_object($form)) {
886 $form = new Form($this->db);
889 // If there is extra languages
890 foreach ($arrayoflangcode as $extralangcode) {
891 $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright
"');
892 $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
893 $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
895 $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
900 if (!in_array($this->country_code, $countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
901 && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
902 if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
903 $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
905 $out .= ($outdone ? ' - ' : '').$this->state;
910 if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) {
911 $out .= ($outdone ? '<br>' : '');
913 if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
914 $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
917 if (!empty($this->phone_pro)) {
918 $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
921 if (!empty($this->phone_mobile)) {
922 $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
925 if (!empty($this->phone_perso)) {
926 $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso
"));
929 if (!empty($this->office_phone)) {
930 $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
933 if (!empty($this->user_mobile)) {
934 $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
937 if (!empty($this->fax)) {
938 $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
941 if (!empty($this->office_fax)) {
942 $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
947 $out .= '<div style="clear: both;
"></div>';
950 if (!empty($this->email)) {
951 $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
954 if (!empty($this->url)) {
955 //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
956 $out .= dol_print_url($this->url, '_blank', 0, 1);
960 if (!empty($conf->socialnetworks->enabled)) {
961 $outsocialnetwork = '';
963 if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
964 $socialnetworksdict = getArrayOfSocialNetworks();
965 foreach ($this->socialnetworks as $key => $value) {
967 $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
971 } else { // Old code to remove
972 if (!empty($this->skype)) {
973 $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
976 if (!empty($this->jabberid)) {
977 $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
980 if (!empty($this->twitter)) {
981 $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
984 if (!empty($this->facebook)) {
985 $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
988 if (!empty($this->linkedin)) {
989 $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
994 if ($outsocialnetwork) {
995 $out .= '<div style="clear: both;
">'.$outsocialnetwork.'</div>';
1000 return '<!-- BEGIN part to show address block -->'."\n
".$out.'<!-- END Part to show address block -->'."\n
";
1014 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1016 global $user, $dolibarr_main_url_root;
1018 if (empty($this->last_main_doc)) {
1019 return ''; // No way to known which document name to use
1022 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1023 $ecmfile = new EcmFiles($this->db);
1024 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1026 $this->error = $ecmfile->error;
1027 $this->errors = $ecmfile->errors;
1031 if (empty($ecmfile->id)) {
1032 // Add entry into index
1033 if ($initsharekey) {
1034 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1036 // TODO We can't, we dont' have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
1038 $ecmfile->filepath = $rel_dir;
1039 $ecmfile->filename = $filename;
1040 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1041 $ecmfile->fullpath_orig = '';
1042 $ecmfile->gen_or_uploaded = 'generated';
1043 $ecmfile->description = ''; // indexed content
1044 $ecmfile->keywords = ''; // keyword content
1045 $ecmfile->share = getRandomPassword(true);
1046 $result = $ecmfile->create($user);
1049 $this->error = $ecmfile->error;
1050 $this->errors = $ecmfile->errors;
1056 } elseif (empty($ecmfile->share)) {
1057 // Add entry into index
1058 if ($initsharekey) {
1059 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1060 $ecmfile->share = getRandomPassword(true);
1061 $ecmfile->update($user);
1066 // Define $urlwithroot
1067 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1068 // This is to use external domain name found into config file
1069 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1071 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1072 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1077 //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1078 //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1079 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1080 if (!empty($ecmfile->share)) {
1081 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1083 if ($forcedownload) {
1084 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1087 if ($relativelink) {
1088 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1090 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1093 // Here $ecmfile->share is defined
1094 return $linktoreturn;
1098 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1108 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1111 global $user, $langs;
1114 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger
");
1117 if ($fk_socpeople <= 0) {
1118 $langs->load("errors
");
1119 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "1
");
1120 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1123 if (!$type_contact) {
1124 $langs->load("errors
");
1125 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "2
");
1126 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1130 $id_type_contact = 0;
1131 if (is_numeric($type_contact)) {
1132 $id_type_contact = $type_contact;
1134 // We look for id type_contact
1135 $sql = "SELECT tc.rowid
";
1136 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1137 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1138 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1139 $sql .= " AND tc.code=
'".$this->db->escape($type_contact)."' AND tc.active=1
";
1141 $resql = $this->db->query($sql);
1143 $obj = $this->db->fetch_object($resql);
1145 $id_type_contact = $obj->rowid;
1150 if ($id_type_contact == 0) {
1151 $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1152 dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code
type of contact
'".$type_contact."' does not exists or is not active
for element
".$this->element.", we can ignore it
");
1156 $datecreate = dol_now();
1158 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1159 $TListeContacts = $this->liste_contact(-1, $source);
1160 $already_added = false;
1161 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1162 foreach ($TListeContacts as $array_contact) {
1163 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1164 $already_added = true;
1170 if (!$already_added) {
1173 // Insert into database
1174 $sql = "INSERT INTO
".$this->db->prefix()."element_contact
";
1175 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact)
";
1176 $sql .= " VALUES (
".$this->id.",
".((int) $fk_socpeople)." ,
";
1177 $sql .= "'".$this->db->idate($datecreate)."'";
1178 $sql .= ", 4,
".((int) $id_type_contact);
1181 $resql = $this->db->query($sql);
1184 $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1186 $this->db->rollback();
1191 $this->db->commit();
1194 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1195 $this->error = $this->db->errno();
1196 $this->db->rollback();
1199 $this->error = $this->db->lasterror();
1200 $this->db->rollback();
1209 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217 public function copy_linked_contact($objFrom, $source = 'internal')
1220 $contacts = $objFrom->liste_contact(-1, $source);
1221 foreach ($contacts as $contact) {
1222 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1229 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1239 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1242 // Insert into database
1243 $sql = "UPDATE
".$this->db->prefix()."element_contact set
";
1244 $sql .= " statut =
".$statut;
1245 if ($type_contact_id) {
1246 $sql .= ", fk_c_type_contact =
".((int) $type_contact_id);
1248 if ($fk_socpeople) {
1249 $sql .= ", fk_socpeople =
".((int) $fk_socpeople);
1251 $sql .= " where
rowid =
".((int) $rowid);
1252 $resql = $this->db->query($sql);
1256 $this->error = $this->db->lasterror();
1261 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1269 public function delete_contact($rowid, $notrigger = 0)
1277 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1278 $sql .= " WHERE rowid =
".((int) $rowid);
1281 if ($this->db->query($sql)) {
1283 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1285 $this->db->rollback();
1290 $this->db->commit();
1293 $this->error = $this->db->lasterror();
1294 $this->db->rollback();
1299 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1307 public function delete_linked_contact($source = '', $code = '')
1312 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1314 if (!empty($typeContact)) {
1315 foreach ($typeContact as $key => $value) {
1316 array_push($temp, $key);
1318 $listId = implode(",
", $temp);
1321 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1322 $sql .= " WHERE element_id =
".((int) $this->id);
1323 if (!empty($listId)) {
1324 $sql .= " AND fk_c_type_contact IN (
".$this->db->sanitize($listId).")
";
1328 if ($this->db->query($sql)) {
1331 $this->error = $this->db->lasterror();
1336 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1346 public function liste_contact($status = -1, $source = 'external', $list = 0, $code = '')
1353 $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
1354 if ($source == 'internal') {
1355 $sql .= ",
'-1' as socid, t.statut as statuscontact, t.login, t.photo
";
1357 if ($source == 'external' || $source == 'thirdparty') {
1358 $sql .= ", t.fk_soc as socid, t.statut as statuscontact
";
1360 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email
";
1361 $sql .= ", tc.source, tc.element, tc.code, tc.libelle
";
1362 $sql .= " FROM
".$this->db->prefix()."c_type_contact tc
";
1363 $sql .= ",
".$this->db->prefix()."element_contact ec
";
1364 if ($source == 'internal') {
1365 $sql .= " LEFT JOIN
".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid
";
1367 if ($source == 'external' || $source == 'thirdparty') {
1368 $sql .= " LEFT JOIN
".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid
";
1370 $sql .= " WHERE ec.element_id =
".((int) $this->id);
1371 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1372 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1374 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1376 if ($source == 'internal') {
1377 $sql .= " AND tc.source =
'internal'";
1379 if ($source == 'external' || $source == 'thirdparty') {
1380 $sql .= " AND tc.source =
'external'";
1382 $sql .= " AND tc.active=1
";
1384 $sql .= " AND ec.statut =
".((int) $status);
1386 $sql .= " ORDER BY t.lastname ASC
";
1389 $resql = $this->db->query($sql);
1391 $num = $this->db->num_rows($resql);
1394 $obj = $this->db->fetch_object($resql);
1397 $transkey = "TypeContact_
".$obj->element."_
".$obj->source."_
".$obj->code;
1398 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1400 'source' => $obj->source,
1401 'socid' => $obj->socid,
1403 'nom' => $obj->lastname, // For backward compatibility
1404 'civility' => $obj->civility,
1405 'lastname' => $obj->lastname,
1406 'firstname' => $obj->firstname,
1407 'email'=>$obj->email,
1408 'login'=> (empty($obj->login) ? '' : $obj->login),
1409 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1410 'statuscontact' => $obj->statuscontact,
1411 'rowid' => $obj->rowid,
1412 'code' => $obj->code,
1413 'libelle' => $libelle_type,
1414 'status' => $obj->statuslink,
1415 'fk_c_type_contact' => $obj->fk_c_type_contact
1418 $tab[$i] = $obj->id;
1426 $this->error = $this->db->lasterror();
1427 dol_print_error($this->db);
1439 public function swapContactStatus($rowid)
1441 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,
";
1442 $sql .= " tc.code, tc.libelle
";
1443 $sql .= " FROM (
".$this->db->prefix()."element_contact as ec,
".$this->db->prefix()."c_type_contact as tc)
";
1444 $sql .= " WHERE ec.rowid =
".((int) $rowid);
1445 $sql .= " AND ec.fk_c_type_contact=tc.rowid
";
1446 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1449 $resql = $this->db->query($sql);
1451 $obj = $this->db->fetch_object($resql);
1452 $newstatut = ($obj->statut == 4) ? 5 : 4;
1453 $result = $this->update_contact($rowid, $newstatut);
1454 $this->db->free($resql);
1457 $this->error = $this->db->error();
1458 dol_print_error($this->db);
1463 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1474 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1479 if (empty($order)) {
1480 $order = 'position';
1482 if ($order == 'position') {
1487 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position
";
1488 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1489 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1490 if ($activeonly == 1) {
1491 $sql .= " AND tc.active=1
"; // only the active types
1493 if (!empty($source) && $source != 'all') {
1494 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1496 if (!empty($code)) {
1497 $sql .= " AND tc.code=
'".$this->db->escape($code)."'";
1499 $sql .= $this->db->order($order, 'ASC');
1501 //print "sql=
".$sql;
1502 $resql = $this->db->query($sql);
1504 $num = $this->db->num_rows($resql);
1507 $obj = $this->db->fetch_object($resql);
1509 $transkey = "TypeContact_
".$this->element."_
".$source."_
".$obj->code;
1510 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1511 if (empty($option)) {
1512 $tab[$obj->rowid] = $libelle_type;
1514 $tab[$obj->code] = $libelle_type;
1520 $this->error = $this->db->lasterror();
1521 //dol_print_error($this->db);
1526 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1538 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1541 global $langs, $conf;
1543 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1547 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element
";
1548 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1550 $sqlWhere = array();
1551 if (!empty($element)) {
1552 $sqlWhere[] = " tc.element=
'".$this->db->escape($element)."'";
1554 if (!empty($excludeelement)) {
1555 $sqlWhere[] = " tc.element <>
'".$this->db->escape($excludeelement)."'";
1558 if ($activeonly == 1) {
1559 $sqlWhere[] = " tc.active=1
"; // only the active types
1562 if (!empty($source) && $source != 'all') {
1563 $sqlWhere[] = " tc.source=
'".$this->db->escape($source)."'";
1566 if (!empty($code)) {
1567 $sqlWhere[] = " tc.code=
'".$this->db->escape($code)."'";
1570 if (count($sqlWhere) > 0) {
1571 $sql .= " WHERE
".implode(' AND ', $sqlWhere);
1574 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1576 dol_syslog(__METHOD__, LOG_DEBUG);
1577 $resql = $this->db->query($sql);
1579 $num = $this->db->num_rows($resql);
1581 $langs->loadLangs(array("propal
", "orders
", "bills
", "suppliers
", "contracts
", "supplier_proposal
"));
1583 while ($obj = $this->db->fetch_object($resql)) {
1584 $modulename = $obj->element;
1585 if (strpos($obj->element, 'project') !== false) {
1586 $modulename = 'projet';
1587 } elseif ($obj->element == 'contrat') {
1588 $element = 'contract';
1589 } elseif ($obj->element == 'action') {
1590 $modulename = 'agenda';
1591 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1592 $modulename = 'fournisseur';
1593 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1594 $modulename = 'fournisseur';
1596 if (!empty($conf->{$modulename}->enabled)) {
1597 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1598 $tmpelement = $obj->element;
1599 $transkey = "TypeContact_
".$tmpelement."_
".$source."_
".$obj->code;
1600 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1601 if (empty($option)) {
1602 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1604 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1611 $this->error = $this->db->lasterror();
1627 public function getIdContact($source, $code, $status = 0)
1633 //cas particulier pour les expeditions
1634 if ($this->element == 'shipping' && $this->origin_id != 0) {
1635 $id = $this->origin_id;
1636 $element = 'commande';
1637 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1638 $id = $this->origin_id;
1639 $element = 'order_supplier';
1642 $element = $this->element;
1645 $sql = "SELECT ec.fk_socpeople
";
1646 $sql .= " FROM
".$this->db->prefix()."element_contact as ec,
";
1647 if ($source == 'internal') {
1648 $sql .= " ".$this->db->prefix()."user as c,
";
1650 if ($source == 'external') {
1651 $sql .= " ".$this->db->prefix()."socpeople as c,
";
1653 $sql .= " ".$this->db->prefix()."c_type_contact as tc
";
1654 $sql .= " WHERE ec.element_id =
".((int) $id);
1655 $sql .= " AND ec.fk_socpeople = c.rowid
";
1656 if ($source == 'internal') {
1657 $sql .= " AND c.entity IN (
".getEntity('user').")
";
1659 if ($source == 'external') {
1660 $sql .= " AND c.entity IN (
".getEntity('societe').")
";
1662 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1663 $sql .= " AND tc.element =
'".$this->db->escape($element)."'";
1664 $sql .= " AND tc.source =
'".$this->db->escape($source)."'";
1666 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1668 $sql .= " AND tc.active = 1
";
1670 $sql .= " AND ec.statut =
".((int) $status);
1674 $resql = $this->db->query($sql);
1676 while ($obj = $this->db->fetch_object($resql)) {
1677 $result[$i] = $obj->fk_socpeople;
1681 $this->error = $this->db->error();
1688 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1695 public function fetch_contact($contactid = null)
1698 if (empty($contactid)) {
1699 $contactid = $this->contact_id;
1702 if (empty($contactid)) {
1706 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1707 $contact = new Contact($this->db);
1708 $result = $contact->fetch($contactid);
1709 $this->contact = $contact;
1713 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1720 public function fetch_thirdparty($force_thirdparty_id = 0)
1725 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1729 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1731 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1732 if ($force_thirdparty_id) {
1733 $idtofetch = $force_thirdparty_id;
1737 $thirdparty = new Societe($this->db);
1738 $result = $thirdparty->fetch($idtofetch);
1740 $this->errors=array_merge($this->errors, $thirdparty->errors);
1742 $this->thirdparty = $thirdparty;
1744 // Use first price level if level not defined for third party
1745 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1746 $this->thirdparty->price_level = 1;
1763 public function fetchOneLike($ref)
1765 if (!$this->table_ref_field) {
1769 $sql = "SELECT rowid FROM
".$this->db->prefix().$this->table_element." WHERE
".$this->table_ref_field." LIKE
'".$this->db->escape($ref)."' LIMIT 1
";
1771 $query = $this->db->query($sql);
1773 if (!$this->db->num_rows($query)) {
1777 $result = $this->db->fetch_object($query);
1779 return $this->fetch($result->rowid);
1782 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1790 public function fetch_barcode()
1795 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1797 $idtype = $this->barcode_type;
1798 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
1799 if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1800 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1801 } elseif ($this->element == 'societe') {
1802 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1804 dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1809 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
1810 $sql = "SELECT
rowid,
code, libelle as label, coder
";
1811 $sql .= " FROM
".$this->db->prefix()."c_barcode_type
";
1812 $sql .= " WHERE rowid =
".((int) $idtype);
1813 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1814 $resql = $this->db->query($sql);
1816 $obj = $this->db->fetch_object($resql);
1817 $this->barcode_type = $obj->rowid;
1818 $this->barcode_type_code = $obj->code;
1819 $this->barcode_type_label = $obj->label;
1820 $this->barcode_type_coder = $obj->coder;
1823 dol_print_error($this->db);
1831 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1837 public function fetch_project()
1840 return $this->fetch_projet();
1843 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1849 public function fetch_projet()
1852 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1854 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1855 $this->fk_project = $this->fk_projet; // For backward compatibility
1857 if (empty($this->fk_project)) {
1861 $project = new Project($this->db);
1862 $result = $project->fetch($this->fk_project);
1864 $this->projet = $project; // deprecated
1865 $this->project = $project;
1869 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1875 public function fetch_product()
1878 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1880 if (empty($this->fk_product)) {
1884 $product = new Product($this->db);
1885 $result = $product->fetch($this->fk_product);
1887 $this->product = $product;
1891 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1898 public function fetch_user($userid)
1901 $user = new User($this->db);
1902 $result = $user->fetch($userid);
1903 $this->user = $user;
1907 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1913 public function fetch_origin()
1916 if ($this->origin == 'shipping') {
1917 $this->origin = 'expedition';
1919 if ($this->origin == 'delivery') {
1920 $this->origin = 'livraison';
1922 if ($this->origin == 'order_supplier') {
1923 $this->origin = 'commandeFournisseur';
1926 $origin = $this->origin;
1928 $classname = ucfirst($origin);
1929 $this->$origin = new $classname($this->db);
1930 $this->$origin->fetch($this->origin_id);
1942 public function fetchObjectFrom($table, $field, $key, $element = null)
1948 $sql = "SELECT rowid FROM
".$this->db->prefix().$table;
1949 $sql .= " WHERE
".$field." =
'".$this->db->escape($key)."'";
1950 if (!empty($element)) {
1951 $sql .= " AND entity IN (
".getEntity($element).")
";
1953 $sql .= " AND entity =
".((int) $conf->entity);
1956 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1957 $resql = $this->db->query($sql);
1959 $row = $this->db->fetch_row($resql);
1960 // Test for avoid error -1
1962 $result = $this->fetch($row[0]);
1977 public function getValueFrom($table, $id, $field)
1980 if (!empty($id) && !empty($field) && !empty($table)) {
1981 $sql = "SELECT
".$field." FROM
".$this->db->prefix().$table;
1982 $sql .= " WHERE rowid =
".((int) $id);
1984 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
1985 $resql = $this->db->query($sql);
1987 $row = $this->db->fetch_row($resql);
2010 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2012 global $user, $langs, $conf;
2014 if (empty($table)) {
2015 $table = $this->table_element;
2020 if (empty($format)) {
2023 if (empty($id_field)) {
2024 $id_field = 'rowid';
2032 if ($table == 'product' && $field == 'note_private') {
2035 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2036 $fk_user_field = 'fk_user_mod';
2039 $sql = "UPDATE
".$this->db->prefix().$table." SET
";
2041 if ($format == 'text') {
2042 $sql .= $field." =
'".$this->db->escape($value)."'";
2043 } elseif ($format == 'int') {
2044 $sql .= $field." =
".((int) $value);
2045 } elseif ($format == 'date') {
2046 $sql .= $field." =
".($value ? "'".$this->db->idate($value)."'" : "null
");
2049 if ($fk_user_field) {
2050 if (!empty($fuser) && is_object($fuser)) {
2051 $sql .= ",
".$fk_user_field." =
".((int) $fuser->id);
2052 } elseif (empty($fuser) || $fuser != 'none') {
2053 $sql .= ",
".$fk_user_field." =
".((int) $user->id);
2057 $sql .= " WHERE
".$id_field." =
".((int) $id);
2059 dol_syslog(__METHOD__."", LOG_DEBUG);
2060 $resql = $this->db->query($sql);
2063 // call trigger with updated object values
2064 if (empty($this->fields) && method_exists($this, 'fetch')) {
2065 $result = $this->fetch($id);
2067 $result = $this->fetchCommon($id);
2070 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2078 if (property_exists($this, $field)) {
2079 $this->$field = $value;
2081 $this->db->commit();
2084 $this->db->rollback();
2088 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2089 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2091 $this->error = $this->db->lasterror();
2093 $this->db->rollback();
2098 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2107 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2110 global $conf, $user;
2112 if (!$this->table_element) {
2113 dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with
property table_element not defined
");
2116 if ($fieldid == 'none') {
2120 // For backward compatibility
2121 if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2125 // Security on socid
2127 if ($user->socid > 0) {
2128 $socid = $user->socid;
2131 // this->ismultientitymanaged contains
2132 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2133 $aliastablesociete = 's';
2134 if ($this->element == 'societe') {
2135 $aliastablesociete = 'te'; // te as table_element
2137 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2138 $sql = "SELECT MAX(te.
".$fieldid.")
";
2139 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2140 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2141 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2143 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2144 $tmparray = explode('@', $this->ismultientitymanaged);
2145 $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
2146 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2147 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2148 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2149 $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
2151 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2152 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2154 $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)
2155 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2156 $sql .= " AND sc.fk_user =
".((int) $user->id);
2158 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2159 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2161 if (!empty($filter)) {
2162 if (!preg_match('/^\s*AND/i', $filter)) {
2163 $sql .= " AND
"; // For backward compatibility
2167 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2168 $tmparray = explode('@', $this->ismultientitymanaged);
2169 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2170 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2171 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2173 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2174 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2175 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2176 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2178 $sql .= " AND ug.fk_user = te.rowid
";
2179 $sql .= " AND ug.entity IN (
".getEntity($this->element).")
";
2182 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2185 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2186 $tmparray = explode('@', $this->ismultientitymanaged);
2187 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2189 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2190 $sql .= ' AND te.fk_soc = '.((int) $socid);
2192 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2193 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2195 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2196 $sql .= ' AND te.rowid = '.((int) $socid);
2198 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2200 $result = $this->db->query($sql);
2202 $this->error = $this->db->lasterror();
2205 $row = $this->db->fetch_row($result);
2206 $this->ref_previous = $row[0];
2208 $sql = "SELECT MIN(te.
".$fieldid.")
";
2209 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2210 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2211 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2213 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2214 $tmparray = explode('@', $this->ismultientitymanaged);
2215 $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
2216 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2217 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2218 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2219 $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
2221 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2222 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2224 $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)
2225 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2226 $sql .= " AND sc.fk_user =
".((int) $user->id);
2228 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2229 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2231 if (!empty($filter)) {
2232 if (!preg_match('/^\s*AND/i', $filter)) {
2233 $sql .= " AND
"; // For backward compatibility
2237 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2238 $tmparray = explode('@', $this->ismultientitymanaged);
2239 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2240 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2241 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2243 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2244 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2245 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2246 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2248 $sql .= " AND ug.fk_user = te.rowid
";
2249 $sql .= " AND ug.entity IN (
".getEntity($this->element).")
";
2252 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2255 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2256 $tmparray = explode('@', $this->ismultientitymanaged);
2257 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2259 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2260 $sql .= ' AND te.fk_soc = '.((int) $socid);
2262 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2263 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2265 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2266 $sql .= ' AND te.rowid = '.((int) $socid);
2268 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2269 // 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
2271 $result = $this->db->query($sql);
2273 $this->error = $this->db->lasterror();
2276 $row = $this->db->fetch_row($result);
2277 $this->ref_next = $row[0];
2290 public function getListContactId($source = 'external')
2292 $contactAlreadySelected = array();
2293 $tab = $this->liste_contact(-1, $source);
2297 if ($source == 'thirdparty') {
2298 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2300 $contactAlreadySelected[$i] = $tab[$i]['id'];
2304 return $contactAlreadySelected;
2315 public function setProject($projectid, $notrigger = 0)
2320 if (!$this->table_element) {
2321 dol_syslog(get_class($this)."::
setProject was called on objet with property table_element not defined
", LOG_ERR);
2325 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2326 if (!empty($this->fields['fk_project'])) { // Common case
2328 $sql .= " SET fk_project =
".((int) $projectid);
2330 $sql .= " SET fk_project = NULL
";
2332 $sql .= ' WHERE rowid = '.((int) $this->id);
2333 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2335 $sql .= " SET fk_project =
".((int) $projectid);
2337 $sql .= " SET fk_project = NULL
";
2339 $sql .= ' WHERE id = '.((int) $this->id);
2340 } else // Special case for old architecture objects
2343 $sql .= ' SET fk_projet = '.((int) $projectid);
2345 $sql .= ' SET fk_projet = NULL';
2347 $sql .= " WHERE rowid =
".((int) $this->id);
2352 dol_syslog(get_class($this)."::
setProject", LOG_DEBUG);
2353 if ($this->db->query($sql)) {
2354 $this->fk_project = ((int) $projectid);
2356 dol_print_error($this->db);
2361 if (!$error && !$notrigger) {
2363 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2366 } //Do also here what you must do to rollback action if trigger fail
2367 // End call triggers
2370 // Commit or rollback
2372 $this->db->rollback();
2375 $this->db->commit();
2386 public function setPaymentMethods($id)
2390 $error = 0; $notrigger = 0;
2392 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2394 if ($this->statut >= 0 || $this->element == 'societe') {
2395 // TODO uniformize field name
2396 $fieldname = 'fk_mode_reglement';
2397 if ($this->element == 'societe') {
2398 $fieldname = 'mode_reglement';
2400 if (get_class($this) == 'Fournisseur') {
2401 $fieldname = 'mode_reglement_supplier';
2403 if (get_class($this) == 'Tva') {
2404 $fieldname = 'fk_typepayment';
2406 if (get_class($this) == 'Salary') {
2407 $fieldname = 'fk_typepayment';
2410 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2411 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2412 $sql .= ' WHERE rowid='.((int) $this->id);
2414 if ($this->db->query($sql)) {
2415 $this->mode_reglement_id = $id;
2417 if (get_class($this) == 'Fournisseur') {
2418 $this->mode_reglement_supplier_id = $id;
2421 if (!$error && !$notrigger) {
2423 if (get_class($this) == 'Commande') {
2424 $result = $this->call_trigger('ORDER_MODIFY', $user);
2426 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2431 // End call triggers
2435 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2436 $this->error = $this->db->error();
2440 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2441 $this->error = 'Status of the object is incompatible '.$this->statut;
2452 public function setMulticurrencyCode($code)
2454 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2455 if ($this->statut >= 0 || $this->element == 'societe') {
2456 $fieldname = 'multicurrency_code';
2458 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2459 $sql .= " SET
".$fieldname." =
'".$this->db->escape($code)."'";
2460 $sql .= ' WHERE rowid='.((int) $this->id);
2462 if ($this->db->query($sql)) {
2463 $this->multicurrency_code = $code;
2465 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2467 $this->setMulticurrencyRate($rate, 2);
2472 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2473 $this->error = $this->db->error();
2477 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2478 $this->error = 'Status of the object is incompatible '.$this->statut;
2490 public function setMulticurrencyRate($rate, $mode = 1)
2492 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2493 if ($this->statut >= 0 || $this->element == 'societe') {
2494 $fieldname = 'multicurrency_tx';
2496 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2497 $sql .= " SET
".$fieldname." =
".((float) $rate);
2498 $sql .= ' WHERE rowid='.((int) $this->id);
2500 if ($this->db->query($sql)) {
2501 $this->multicurrency_tx = $rate;
2503 // Update line price
2504 if (!empty($this->lines)) {
2505 foreach ($this->lines as &$line) {
2506 // Amounts in company currency will be recalculated
2508 $line->subprice = 0;
2511 // Amounts in foreign currency will be recalculated
2513 $line->multicurrency_subprice = 0;
2516 switch ($this->element) {
2522 $line->remise_percent,
2524 $line->localtax1_tx,
2525 $line->localtax2_tx,
2526 ($line->description ? $line->description : $line->desc),
2529 $line->special_code,
2530 $line->fk_parent_line,
2531 $line->skip_update_total,
2532 $line->fk_fournprice,
2535 $line->product_type,
2538 $line->array_options,
2540 $line->multicurrency_subprice
2546 ($line->description ? $line->description : $line->desc),
2549 $line->remise_percent,
2551 $line->localtax1_tx,
2552 $line->localtax2_tx,
2557 $line->product_type,
2558 $line->fk_parent_line,
2559 $line->skip_update_total,
2560 $line->fk_fournprice,
2563 $line->special_code,
2564 $line->array_options,
2566 $line->multicurrency_subprice
2572 ($line->description ? $line->description : $line->desc),
2575 $line->remise_percent,
2579 $line->localtax1_tx,
2580 $line->localtax2_tx,
2583 $line->product_type,
2584 $line->fk_parent_line,
2585 $line->skip_update_total,
2586 $line->fk_fournprice,
2589 $line->special_code,
2590 $line->array_options,
2591 $line->situation_percent,
2593 $line->multicurrency_subprice
2596 case 'supplier_proposal':
2601 $line->remise_percent,
2603 $line->localtax1_tx,
2604 $line->localtax2_tx,
2605 ($line->description ? $line->description : $line->desc),
2608 $line->special_code,
2609 $line->fk_parent_line,
2610 $line->skip_update_total,
2611 $line->fk_fournprice,
2614 $line->product_type,
2615 $line->array_options,
2617 $line->multicurrency_subprice
2620 case 'order_supplier':
2623 ($line->description ? $line->description : $line->desc),
2626 $line->remise_percent,
2628 $line->localtax1_tx,
2629 $line->localtax2_tx,
2632 $line->product_type,
2636 $line->array_options,
2638 $line->multicurrency_subprice,
2642 case 'invoice_supplier':
2645 ($line->description ? $line->description : $line->desc),
2648 $line->localtax1_tx,
2649 $line->localtax2_tx,
2654 $line->product_type,
2655 $line->remise_percent,
2659 $line->array_options,
2661 $line->multicurrency_subprice,
2666 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2674 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2675 $this->error = $this->db->error();
2679 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2680 $this->error = 'Status of the object is incompatible '.$this->statut;
2692 public function setPaymentTerms($id, $deposit_percent = null)
2694 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2695 if ($this->statut >= 0 || $this->element == 'societe') {
2696 // TODO uniformize field name
2697 $fieldname = 'fk_cond_reglement';
2698 if ($this->element == 'societe') {
2699 $fieldname = 'cond_reglement';
2701 if (get_class($this) == 'Fournisseur') {
2702 $fieldname = 'cond_reglement_supplier';
2705 if (empty($deposit_percent) || $deposit_percent < 0) {
2706 $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2709 if ($deposit_percent > 100) {
2710 $deposit_percent = 100;
2713 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2714 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2715 if (in_array($this->table_element, array('propal', 'commande'))) {
2716 $sql .= " , deposit_percent =
" . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2718 $sql .= ' WHERE rowid='.((int) $this->id);
2720 if ($this->db->query($sql)) {
2721 $this->cond_reglement_id = $id;
2723 if (get_class($this) == 'Fournisseur') {
2724 $this->cond_reglement_supplier_id = $id;
2726 $this->cond_reglement = $id; // for compatibility
2727 $this->deposit_percent = $deposit_percent;
2730 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2731 $this->error = $this->db->error();
2735 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2736 $this->error = 'Status of the object is incompatible '.$this->statut;
2747 public function setTransportMode($id)
2749 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2750 if ($this->statut >= 0 || $this->element == 'societe') {
2751 $fieldname = 'fk_transport_mode';
2752 if ($this->element == 'societe') {
2753 $fieldname = 'transport_mode';
2755 if (get_class($this) == 'Fournisseur') {
2756 $fieldname = 'transport_mode_supplier';
2759 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2760 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2761 $sql .= ' WHERE rowid='.((int) $this->id);
2763 if ($this->db->query($sql)) {
2764 $this->transport_mode_id = $id;
2766 if (get_class($this) == 'Fournisseur') {
2767 $this->transport_mode_supplier_id = $id;
2771 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2772 $this->error = $this->db->error();
2776 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2777 $this->error = 'Status of the object is incompatible '.$this->statut;
2788 public function setRetainedWarrantyPaymentTerms($id)
2790 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2791 if ($this->statut >= 0 || $this->element == 'societe') {
2792 $fieldname = 'retained_warranty_fk_cond_reglement';
2794 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2795 $sql .= " SET
".$fieldname." =
".((int) $id);
2796 $sql .= ' WHERE rowid='.((int) $this->id);
2798 if ($this->db->query($sql)) {
2799 $this->retained_warranty_fk_cond_reglement = $id;
2802 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2803 $this->error = $this->db->error();
2807 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2808 $this->error = 'Status of the object is incompatible '.$this->statut;
2820 public function setDeliveryAddress($id)
2822 $fieldname = 'fk_delivery_address';
2823 if ($this->element == 'delivery' || $this->element == 'shipping') {
2824 $fieldname = 'fk_address';
2827 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET
".$fieldname." =
".((int) $id);
2828 $sql .= " WHERE rowid =
".((int) $this->id)." AND fk_statut = 0
";
2830 if ($this->db->query($sql)) {
2831 $this->fk_delivery_address = $id;
2834 $this->error = $this->db->error();
2835 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2850 public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2854 if (empty($userused)) {
2860 if (!$this->table_element) {
2861 dol_syslog(get_class($this)."::
setShippingMethod was called on objet with property table_element not defined
", LOG_ERR);
2867 if ($shipping_method_id < 0) {
2868 $shipping_method_id = 'NULL';
2870 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2872 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2873 $sql .= " SET fk_shipping_method =
".((int) $shipping_method_id);
2874 $sql .= " WHERE rowid=
".((int) $this->id);
2875 $resql = $this->db->query($sql);
2877 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2878 $this->error = $this->db->lasterror();
2883 $this->context = array('shippingmethodupdate'=>1);
2884 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2892 $this->db->rollback();
2895 $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2896 $this->db->commit();
2908 public function setWarehouse($warehouse_id)
2910 if (!$this->table_element) {
2911 dol_syslog(get_class($this)."::
setWarehouse was called on objet with property table_element not defined
", LOG_ERR);
2914 if ($warehouse_id < 0) {
2915 $warehouse_id = 'NULL';
2917 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2919 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2920 $sql .= " SET fk_warehouse =
".((int) $warehouse_id);
2921 $sql .= " WHERE rowid=
".((int) $this->id);
2923 if ($this->db->query($sql)) {
2924 $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2927 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2928 $this->error = $this->db->error();
2941 public function setDocModel($user, $modelpdf)
2943 if (!$this->table_element) {
2944 dol_syslog(get_class($this)."::
setDocModel was called on objet with property table_element not defined
", LOG_ERR);
2948 $newmodelpdf = dol_trunc($modelpdf, 255);
2950 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2951 $sql .= " SET model_pdf =
'".$this->db->escape($newmodelpdf)."'";
2952 $sql .= " WHERE rowid =
".((int) $this->id);
2954 dol_syslog(get_class($this)."::
setDocModel", LOG_DEBUG);
2955 $resql = $this->db->query($sql);
2957 $this->model_pdf = $modelpdf;
2958 $this->modelpdf = $modelpdf; // For bakward compatibility
2961 dol_print_error($this->db);
2975 public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2979 if (empty($userused)) {
2985 if (!$this->table_element) {
2986 dol_syslog(get_class($this)."::
setBankAccount was called on objet with property table_element not defined
", LOG_ERR);
2991 if ($fk_account < 0) {
2992 $fk_account = 'NULL';
2994 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2996 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2997 $sql .= " SET fk_account =
".((int) $fk_account);
2998 $sql .= " WHERE rowid=
".((int) $this->id);
3000 $resql = $this->db->query($sql);
3002 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3003 $this->error = $this->db->lasterror();
3008 $this->context = array('bankaccountupdate'=>1);
3009 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3017 $this->db->rollback();
3020 $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3021 $this->db->commit();
3027 // TODO: Move line related operations to CommonObjectLine?
3029 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3039 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3042 if (!$this->table_element_line) {
3043 dol_syslog(get_class($this)."::
line_order was called on objet with property table_element_line not defined
", LOG_ERR);
3046 if (!$this->fk_element) {
3047 dol_syslog(get_class($this)."::
line_order was called on objet with property fk_element not defined
", LOG_ERR);
3051 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3052 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3053 $fieldposition = 'position';
3056 // Count number of lines to reorder (according to choice $renum)
3058 $sql = "SELECT count(rowid) FROM
".$this->db->prefix().$this->table_element_line;
3059 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3061 $sql .= " AND
" . $fieldposition . " = 0
";
3064 $sql .= " AND
" . $fieldposition . " <> 0
";
3067 dol_syslog(get_class($this)."::
line_order", LOG_DEBUG);
3068 $resql = $this->db->query($sql);
3070 $row = $this->db->fetch_row($resql);
3073 dol_print_error($this->db);
3076 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3079 // We first search all lines that are parent lines (for multilevel details lines)
3080 $sql = "SELECT rowid FROM
".$this->db->prefix().$this->table_element_line;
3081 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3082 if ($fk_parent_line) {
3083 $sql .= ' AND fk_parent_line IS NULL';
3085 $sql .= " ORDER BY
" . $fieldposition . " ASC, rowid
" . $rowidorder;
3087 dol_syslog(get_class($this)."::
line_order search all parent lines
", LOG_DEBUG);
3088 $resql = $this->db->query($sql);
3091 $num = $this->db->num_rows($resql);
3093 $row = $this->db->fetch_row($resql);
3094 $rows[] = $row[0]; // Add parent line into array rows
3095 $childrens = $this->getChildrenOfLine($row[0]);
3096 if (!empty($childrens)) {
3097 foreach ($childrens as $child) {
3098 array_push($rows, $child);
3104 // Now we set a new number for each lines (parent and children with children included into parent tree)
3105 if (!empty($rows)) {
3106 foreach ($rows as $key => $row) {
3107 $this->updateRangOfLine($row, ($key + 1));
3111 dol_print_error($this->db);
3124 public function getChildrenOfLine($id, $includealltree = 0)
3126 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3127 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3128 $fieldposition = 'position';
3133 $sql = "SELECT rowid FROM
".$this->db->prefix().$this->table_element_line;
3134 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3135 $sql .= ' AND fk_parent_line = '.((int) $id);
3136 $sql .= " ORDER BY
" . $fieldposition . " ASC
";
3138 dol_syslog(get_class($this)."::
getChildrenOfLine search children lines
for line
".$id, LOG_DEBUG);
3139 $resql = $this->db->query($sql);
3141 if ($this->db->num_rows($resql) > 0) {
3142 while ($row = $this->db->fetch_row($resql)) {
3144 if (!empty($includealltree)) {
3145 $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3153 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3161 public function line_up($rowid, $fk_parent_line = true)
3164 $this->line_order(false, 'ASC', $fk_parent_line);
3167 $rang = $this->getRangOfLine($rowid);
3169 // Update position of line
3170 $this->updateLineUp($rowid, $rang);
3173 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3181 public function line_down($rowid, $fk_parent_line = true)
3184 $this->line_order(false, 'ASC', $fk_parent_line);
3187 $rang = $this->getRangOfLine($rowid);
3189 // Get max value for rang
3190 $max = $this->line_max();
3192 // Update position of line
3193 $this->updateLineDown($rowid, $rang, $max);
3203 public function updateRangOfLine($rowid, $rang)
3205 global $hookmanager;
3206 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3207 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3208 $fieldposition = 'position';
3211 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3212 $sql .= ' WHERE rowid = '.((int) $rowid);
3215 if (!$this->db->query($sql)) {
3216 dol_print_error($this->db);
3219 $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3221 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3226 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3233 public function line_ajaxorder($rows)
3236 $num = count($rows);
3237 for ($i = 0; $i < $num; $i++) {
3238 $this->updateRangOfLine($rows[$i], ($i + 1));
3249 public function updateLineUp($rowid, $rang)
3252 $fieldposition = 'rang';
3253 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3254 $fieldposition = 'position';
3257 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3258 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3259 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang - 1));
3260 if ($this->db->query($sql)) {
3261 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang - 1));
3262 $sql .= ' WHERE rowid = '.((int) $rowid);
3263 if (!$this->db->query($sql)) {
3264 dol_print_error($this->db);
3267 dol_print_error($this->db);
3280 public function updateLineDown($rowid, $rang, $max)
3283 $fieldposition = 'rang';
3284 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3285 $fieldposition = 'position';
3288 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3289 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3290 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang + 1));
3291 if ($this->db->query($sql)) {
3292 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang + 1));
3293 $sql .= ' WHERE rowid = '.((int) $rowid);
3294 if (!$this->db->query($sql)) {
3295 dol_print_error($this->db);
3298 dol_print_error($this->db);
3309 public function getRangOfLine($rowid)
3311 $fieldposition = 'rang';
3312 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3313 $fieldposition = 'position';
3316 $sql = "SELECT
" . $fieldposition . " FROM
".$this->db->prefix().$this->table_element_line;
3317 $sql .= " WHERE rowid =
".((int) $rowid);
3320 $resql = $this->db->query($sql);
3322 $row = $this->db->fetch_row($resql);
3333 public function getIdOfLine($rang)
3335 $fieldposition = 'rang';
3336 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3337 $fieldposition = 'position';
3340 $sql = "SELECT rowid FROM
".$this->db->prefix().$this->table_element_line;
3341 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3342 $sql .= " AND
" . $fieldposition . " =
".((int) $rang);
3343 $resql = $this->db->query($sql);
3345 $row = $this->db->fetch_row($resql);
3350 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3357 public function line_max($fk_parent_line = 0)
3360 $positionfield = 'rang';
3361 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3362 $positionfield = 'position';
3365 // Search the last rang with fk_parent_line
3366 if ($fk_parent_line) {
3367 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3368 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3369 $sql .= " AND fk_parent_line =
".((int) $fk_parent_line);
3371 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3372 $resql = $this->db->query($sql);
3374 $row = $this->db->fetch_row($resql);
3375 if (!empty($row[0])) {
3378 return $this->getRangOfLine($fk_parent_line);
3382 // If not, search the last rang of element
3383 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3384 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3386 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3387 $resql = $this->db->query($sql);
3389 $row = $this->db->fetch_row($resql);
3395 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3402 public function update_ref_ext($ref_ext)
3405 if (!$this->table_element) {
3406 dol_syslog(get_class($this)."::
update_ref_ext was called on objet with property table_element not defined
", LOG_ERR);
3410 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3411 $sql .= " SET ref_ext =
'".$this->db->escape($ref_ext)."'";
3412 $sql .= " WHERE
".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." =
".((int) $this->id);
3415 if ($this->db->query($sql)) {
3416 $this->ref_ext = $ref_ext;
3419 $this->error = $this->db->error();
3424 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3432 public function update_note($note, $suffix = '')
3437 if (!$this->table_element) {
3438 $this->error = 'update_note was called on objet with property table_element not defined';
3439 dol_syslog(get_class($this)."::
update_note was called on objet with property table_element not defined
", LOG_ERR);
3442 if (!in_array($suffix, array('', '_public', '_private'))) {
3443 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3444 dol_syslog(get_class($this)."::
update_note Parameter suffix must be empty,
'_private' or
'_public'", LOG_ERR);
3448 $newsuffix = $suffix;
3451 if ($this->table_element == 'product' && $newsuffix == '_private') {
3454 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3455 $fieldusermod = "fk_user_mod
";
3456 } elseif ($this->table_element == 'ecm_files') {
3457 $fieldusermod = "fk_user_m
";
3459 $fieldusermod = "fk_user_modif
";
3461 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3462 $sql .= " SET note
".$newsuffix." =
".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL
");
3463 $sql .= ",
".$fieldusermod." =
".((int) $user->id);
3464 $sql .= " WHERE rowid =
".((int) $this->id);
3466 dol_syslog(get_class($this)."::
update_note", LOG_DEBUG);
3467 if ($this->db->query($sql)) {
3468 if ($suffix == '_public') {
3469 $this->note_public = $note;
3470 } elseif ($suffix == '_private') {
3471 $this->note_private = $note;
3473 $this->note = $note; // deprecated
3474 $this->note_private = $note;
3478 $this->error = $this->db->lasterror();
3483 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3492 public function update_note_public($note)
3495 return $this->update_note($note, '_public');
3498 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3509 public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3512 global $conf, $hookmanager, $action;
3514 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3515 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3517 return 1; // replacement code
3518 } elseif ($reshook < 0) {
3519 return -1; // failure
3520 } // reshook = 0 => execute normal code
3522 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3524 if ($this->element == 'propal') {
3525 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL
";
3526 } elseif ($this->element == 'commande' || $this->element == 'order') {
3527 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER
";
3528 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3529 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE
";
3530 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3531 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE
";
3532 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3533 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER
";
3534 } elseif ($this->element == 'supplier_proposal') {
3535 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL
";
3538 if (!empty($MODULE)) {
3539 if (!empty($conf->global->$MODULE)) {
3540 $modsactivated = explode(',', $conf->global->$MODULE);
3541 foreach ($modsactivated as $mod) {
3542 if ($conf->$mod->enabled) {
3543 return 1; // update was disabled by specific setup
3549 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3551 if ($roundingadjust == '-1') {
3552 $roundingadjust = 'auto'; // For backward compatibility
3555 $forcedroundingmode = $roundingadjust;
3556 if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3557 $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3558 } elseif ($forcedroundingmode == 'auto') {
3559 $forcedroundingmode = '0';
3564 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3566 // Define constants to find lines to sum
3567 $fieldtva = 'total_tva';
3568 $fieldlocaltax1 = 'total_localtax1';
3569 $fieldlocaltax2 = 'total_localtax2';
3570 $fieldup = 'subprice';
3571 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3575 if ($this->element == 'invoice_supplier_rec') {
3578 if ($this->element == 'expensereport') {
3579 $fieldup = 'value_unit';
3582 $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,
";
3583 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3584 if ($this->table_element_line == 'facturedet') {
3585 $sql .= ', situation_percent';
3587 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3588 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
3589 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3591 $product_field = 'product_type';
3592 if ($this->table_element_line == 'contratdet') {
3593 $product_field = ''; // contratdet table has no product_type field
3595 if ($product_field) {
3596 $sql .= " AND
".$product_field." <> 9
";
3599 $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
3601 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3602 $resql = $this->db->query($sql);
3604 $this->total_ht = 0;
3605 $this->total_tva = 0;
3606 $this->total_localtax1 = 0;
3607 $this->total_localtax2 = 0;
3608 $this->total_ttc = 0;
3609 $total_ht_by_vats = array();
3610 $total_tva_by_vats = array();
3611 $total_ttc_by_vats = array();
3612 $this->multicurrency_total_ht = 0;
3613 $this->multicurrency_total_tva = 0;
3614 $this->multicurrency_total_ttc = 0;
3616 $num = $this->db->num_rows($resql);
3619 $obj = $this->db->fetch_object($resql);
3621 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3622 $parameters = array('fk_element' => $obj->rowid);
3623 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3625 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'
3626 // This part of code is to fix data. We should not call it too often.
3627 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3628 $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);
3630 $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.
3631 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3632 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' =? '.$obj->total_ttc);
3633 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3635 if ($diff_when_using_price_ht && $diff_on_current_total) {
3636 $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);
3637 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);
3638 $resqlfix = $this->db->query($sqlfix);
3640 dol_print_error($this->db, 'Failed to update line');
3642 $obj->total_tva = $tmpcal[1];
3643 $obj->total_ttc = $tmpcal[2];
3647 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3648 $this->total_tva += $obj->total_tva;
3649 $this->total_localtax1 += $obj->total_localtax1;
3650 $this->total_localtax2 += $obj->total_localtax2;
3651 $this->total_ttc += $obj->total_ttc;
3652 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3653 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3654 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3656 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3657 $total_ht_by_vats[$obj->vatrate] = 0;
3659 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3660 $total_tva_by_vats[$obj->vatrate] = 0;
3662 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3663 $total_ttc_by_vats[$obj->vatrate] = 0;
3665 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3666 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3667 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3669 if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3670 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3671 $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3672 //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
";
3674 if (abs($diff) > 0.1) {
3675 $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.';
3676 dol_syslog($errmsg, LOG_WARNING);
3677 dol_print_error('', $errmsg);
3680 $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);
3681 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);
3683 $resqlfix = $this->db->query($sqlfix);
3686 dol_print_error($this->db, 'Failed to update line');
3689 $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3690 $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3691 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3692 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3699 // Add revenue stamp to total
3700 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3701 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3703 // Situations totals
3704 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3705 $prev_sits = $this->get_prev_sits();
3707 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3708 $this->total_ht -= $sit->total_ht;
3709 $this->total_tva -= $sit->total_tva;
3710 $this->total_localtax1 -= $sit->total_localtax1;
3711 $this->total_localtax2 -= $sit->total_localtax2;
3712 $this->total_ttc -= $sit->total_ttc;
3713 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3714 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3715 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3720 $this->total_ht = (float) price2num($this->total_ht);
3721 $this->total_tva = (float) price2num($this->total_tva);
3722 $this->total_localtax1 = (float) price2num($this->total_localtax1);
3723 $this->total_localtax2 = (float) price2num($this->total_localtax2);
3724 $this->total_ttc = (float) price2num($this->total_ttc);
3726 $this->db->free($resql);
3728 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_*
3729 $fieldht = 'total_ht';
3731 $fieldlocaltax1 = 'localtax1';
3732 $fieldlocaltax2 = 'localtax2';
3733 $fieldttc = 'total_ttc';
3734 // Specific code for backward compatibility with old field names
3735 if ($this->element == 'facture' || $this->element == 'facturerec') {
3736 $fieldtva = 'total_tva';
3738 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3739 $fieldtva = 'total_tva';
3741 if ($this->element == 'propal') {
3742 $fieldtva = 'total_tva';
3744 if ($this->element == 'expensereport') {
3745 $fieldtva = 'total_tva';
3747 if ($this->element == 'supplier_proposal') {
3748 $fieldtva = 'total_tva';
3750 if ($this->element == 'commande') {
3751 $fieldtva = 'total_tva';
3753 if ($this->element == 'order_supplier') {
3754 $fieldtva = 'total_tva';
3757 if (empty($nodatabaseupdate)) {
3758 $sql = "UPDATE
".$this->db->prefix().$this->table_element.' SET';
3759 $sql .= " ".$fieldht." =
".((float) price2num($this->total_ht, 'MT', 1)).",
";
3760 $sql .= " ".$fieldtva." =
".((float) price2num($this->total_tva, 'MT', 1)).",
";
3761 $sql .= " ".$fieldlocaltax1." =
".((float) price2num($this->total_localtax1, 'MT', 1)).",
";
3762 $sql .= " ".$fieldlocaltax2." =
".((float) price2num($this->total_localtax2, 'MT', 1)).",
";
3763 $sql .= " ".$fieldttc." =
".((float) price2num($this->total_ttc, 'MT', 1));
3764 $sql .= ", multicurrency_total_ht =
".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3765 $sql .= ", multicurrency_total_tva =
".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3766 $sql .= ", multicurrency_total_ttc =
".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3767 $sql .= " WHERE rowid =
".((int) $this->id);
3769 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3770 $resql = $this->db->query($sql);
3774 $this->error = $this->db->lasterror();
3775 $this->errors[] = $this->db->lasterror();
3785 dol_print_error($this->db, 'Bad request in update_price');
3790 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3801 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3804 global $user, $hookmanager, $action;
3805 $origin = (!empty($origin) ? $origin : $this->origin);
3806 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3807 $f_user = isset($f_user) ? $f_user : $user;
3810 if ($origin == 'order') {
3811 $origin = 'commande';
3813 if ($origin == 'invoice') {
3814 $origin = 'facture';
3816 if ($origin == 'invoice_template') {
3817 $origin = 'facturerec';
3819 if ($origin == 'supplierorder') {
3820 $origin = 'order_supplier';
3823 // 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.
3824 // 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.
3825 $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3826 // Add module part to target type if object has $module property and isn't in core modules.
3827 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3829 $parameters = array('targettype'=>$targettype);
3830 // Hook for explicitly set the targettype if it must be differtent than $this->element
3831 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3833 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3839 $sql = "INSERT INTO
" . $this->db->prefix() . "element_element (
";
3840 $sql .= "fk_source
";
3841 $sql .= ", sourcetype
";
3842 $sql .= ", fk_target
";
3843 $sql .= ", targettype
";
3844 $sql .= ") VALUES (
";
3845 $sql .= ((int) $origin_id);
3846 $sql .= ",
'" . $this->db->escape($origin) . "'";
3847 $sql .= ",
" . ((int) $this->id);
3848 $sql .= ",
'" . $this->db->escape($targettype) . "'";
3852 if ($this->db->query($sql)) {
3855 $this->context['link_origin'] = $origin;
3856 $this->context['link_origin_id'] = $origin_id;
3857 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3861 // End call triggers
3864 $this->error = $this->db->lasterror();
3869 $this->db->commit();
3872 $this->db->rollback();
3899 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3901 global $conf, $hookmanager, $action;
3903 // Important for pdf generation time reduction
3904 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3905 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3909 $this->linkedObjectsIds = array();
3910 $this->linkedObjects = array();
3912 $justsource = false;
3913 $justtarget = false;
3914 $withtargettype = false;
3915 $withsourcetype = false;
3917 $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3918 // Hook for explicitly set the targettype if it must be differtent than $this->element
3919 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3921 if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3922 if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3923 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3924 if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3927 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3928 $justsource = true; // the source (id and type) is a search criteria
3929 if (!empty($targettype)) {
3930 $withtargettype = true;
3933 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3934 $justtarget = true; // the target (id and type) is a search criteria
3935 if (!empty($sourcetype)) {
3936 $withsourcetype = true;
3940 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3941 $targetid = (!empty($targetid) ? $targetid : $this->id);
3942 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3943 $targettype = (!empty($targettype) ? $targettype : $this->element);
3945 /*if (empty($sourceid) && empty($targetid))
3947 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3951 // Links between objects are stored in table element_element
3952 $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype
";
3953 $sql .= " FROM
".$this->db->prefix()."element_element
";
3955 if ($justsource || $justtarget) {
3957 $sql .= "fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3958 if ($withtargettype) {
3959 $sql .= " AND targettype =
'".$this->db->escape($targettype)."'";
3961 } elseif ($justtarget) {
3962 $sql .= "fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."'";
3963 if ($withsourcetype) {
3964 $sql .= " AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3968 $sql .= "(fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."')
";
3969 $sql .= " ".$clause." (fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."')
";
3970 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3971 $this->linkedObjectsFullLoaded[$this->id] = true;
3974 $sql .= " ORDER BY
".$orderby;
3976 dol_syslog(get_class($this)."::fetchObjectLink
", LOG_DEBUG);
3977 $resql = $this->db->query($sql);
3979 $num = $this->db->num_rows($resql);
3982 $obj = $this->db->fetch_object($resql);
3983 if ($justsource || $justtarget) {
3985 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3986 } elseif ($justtarget) {
3987 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3990 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
3991 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3993 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
3994 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4000 if (!empty($this->linkedObjectsIds)) {
4001 $tmparray = $this->linkedObjectsIds;
4002 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4003 // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4004 $module = $element = $subelement = $objecttype;
4006 if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4007 && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4008 $module = $element = $regs[1];
4009 $subelement = $regs[2];
4012 $classpath = $element.'/class';
4013 // To work with non standard classpath or module name
4014 if ($objecttype == 'facture') {
4015 $classpath = 'compta/facture/class';
4016 } elseif ($objecttype == 'facturerec') {
4017 $classpath = 'compta/facture/class';
4018 $module = 'facture';
4019 } elseif ($objecttype == 'propal') {
4020 $classpath = 'comm/propal/class';
4021 } elseif ($objecttype == 'supplier_proposal') {
4022 $classpath = 'supplier_proposal/class';
4023 } elseif ($objecttype == 'shipping') {
4024 $classpath = 'expedition/class';
4025 $subelement = 'expedition';
4026 $module = 'expedition_bon';
4027 } elseif ($objecttype == 'delivery') {
4028 $classpath = 'delivery/class';
4029 $subelement = 'delivery';
4030 $module = 'delivery_note';
4031 } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4032 $classpath = 'fourn/class';
4033 $module = 'fournisseur';
4034 } elseif ($objecttype == 'fichinter') {
4035 $classpath = 'fichinter/class';
4036 $subelement = 'fichinter';
4037 $module = 'ficheinter';
4038 } elseif ($objecttype == 'subscription') {
4039 $classpath = 'adherents/class';
4040 $module = 'adherent';
4041 } elseif ($objecttype == 'contact') {
4042 $module = 'societe';
4045 $classfile = strtolower($subelement);
4046 $classname = ucfirst($subelement);
4048 if ($objecttype == 'order') {
4049 $classfile = 'commande';
4050 $classname = 'Commande';
4051 } elseif ($objecttype == 'invoice_supplier') {
4052 $classfile = 'fournisseur.facture';
4053 $classname = 'FactureFournisseur';
4054 } elseif ($objecttype == 'order_supplier') {
4055 $classfile = 'fournisseur.commande';
4056 $classname = 'CommandeFournisseur';
4057 } elseif ($objecttype == 'supplier_proposal') {
4058 $classfile = 'supplier_proposal';
4059 $classname = 'SupplierProposal';
4060 } elseif ($objecttype == 'facturerec') {
4061 $classfile = 'facture-rec';
4062 $classname = 'FactureRec';
4063 } elseif ($objecttype == 'subscription') {
4064 $classfile = 'subscription';
4065 $classname = 'Subscription';
4066 } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4067 $classpath = 'projet/class';
4068 $classfile = 'project';
4069 $classname = 'Project';
4070 } elseif ($objecttype == 'conferenceorboothattendee') {
4071 $classpath = 'eventorganization/class';
4072 $classfile = 'conferenceorboothattendee';
4073 $classname = 'ConferenceOrBoothAttendee';
4074 $module = 'eventorganization';
4075 } elseif ($objecttype == 'conferenceorbooth') {
4076 $classpath = 'eventorganization/class';
4077 $classfile = 'conferenceorbooth';
4078 $classname = 'ConferenceOrBooth';
4079 $module = 'eventorganization';
4080 } elseif ($objecttype == 'mo') {
4081 $classpath = 'mrp/class';
4087 // Here $module, $classfile and $classname are set, we can use them.
4088 if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
4089 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4090 dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4091 //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4092 if (class_exists($classname)) {
4093 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4094 $object = new $classname($this->db);
4095 $ret = $object->fetch($objectid);
4097 $this->linkedObjects[$objecttype][$i] = $object;
4103 unset($this->linkedObjectsIds[$objecttype]);
4109 dol_print_error($this->db);
4126 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4129 $updatesource = false;
4130 $updatetarget = false;
4131 $f_user = isset($f_user) ? $f_user : $user;
4133 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4134 $updatesource = true;
4135 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4136 $updatetarget = true;
4142 $sql = "UPDATE
" . $this->db->prefix() . "element_element SET
";
4143 if ($updatesource) {
4144 $sql .= "fk_source =
" . ((int) $sourceid);
4145 $sql .= ", sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4146 $sql .= " WHERE fk_target =
" . ((int) $this->id);
4147 $sql .= " AND targettype =
'" . $this->db->escape($this->element) . "'";
4148 } elseif ($updatetarget) {
4149 $sql .= "fk_target =
" . ((int) $targetid);
4150 $sql .= ", targettype =
'" . $this->db->escape($targettype) . "'";
4151 $sql .= " WHERE fk_source =
" . ((int) $this->id);
4152 $sql .= " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4156 if ($this->db->query($sql)) {
4159 $this->context['link_source_id'] = $sourceid;
4160 $this->context['link_source_type'] = $sourcetype;
4161 $this->context['link_target_id'] = $targetid;
4162 $this->context['link_target_type'] = $targettype;
4163 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4167 // End call triggers
4170 $this->error = $this->db->lasterror();
4175 $this->db->commit();
4178 $this->db->rollback();
4196 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4199 $deletesource = false;
4200 $deletetarget = false;
4201 $f_user = isset($f_user) ? $f_user : $user;
4203 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4204 $deletesource = true;
4205 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4206 $deletetarget = true;
4209 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4210 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4211 $targetid = (!empty($targetid) ? $targetid : $this->id);
4212 $targettype = (!empty($targettype) ? $targettype : $this->element);
4218 $this->context['link_id'] = $rowid;
4219 $this->context['link_source_id'] = $sourceid;
4220 $this->context['link_source_type'] = $sourcetype;
4221 $this->context['link_target_id'] = $targetid;
4222 $this->context['link_target_type'] = $targettype;
4223 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4227 // End call triggers
4231 $sql = "DELETE FROM
" . $this->db->prefix() . "element_element
";
4234 $sql .= " rowid =
" . ((int) $rowid);
4236 if ($deletesource) {
4237 $sql .= " fk_source =
" . ((int) $sourceid) . " AND sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4238 $sql .= " AND fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "'";
4239 } elseif ($deletetarget) {
4240 $sql .= " fk_target =
" . ((int) $targetid) . " AND targettype =
'" . $this->db->escape($targettype) . "'";
4241 $sql .= " AND fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4243 $sql .= " (fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "')
";
4245 $sql .= " (fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "')
";
4250 if (!$this->db->query($sql)) {
4251 $this->error = $this->db->lasterror();
4252 $this->errors[] = $this->error;
4258 $this->db->commit();
4261 $this->db->rollback();
4275 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4277 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4283 $sql = "SELECT
".$field_select." FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4284 $resql = $db->query($sql);
4287 if (!empty($resql)) {
4288 while ($res = $db->fetch_object($resql)) {
4289 $TRes[] = $res->{$field_select};
4304 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4306 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4312 $sql = "DELETE FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4313 $resql = $db->query($sql);
4315 if (empty($resql)) {
4332 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4334 global $user, $langs, $conf;
4336 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4338 $elementId = (!empty($elementId) ? $elementId : $this->id);
4339 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4343 if ($elementTable == 'facture_rec') {
4344 $fieldstatus = "suspended
";
4346 if ($elementTable == 'mailing') {
4347 $fieldstatus = "statut
";
4349 if ($elementTable == 'cronjob') {
4350 $fieldstatus = "status
";
4352 if ($elementTable == 'user') {
4353 $fieldstatus = "statut
";
4355 if ($elementTable == 'expensereport') {
4356 $fieldstatus = "fk_statut
";
4358 if ($elementTable == 'commande_fournisseur_dispatch') {
4359 $fieldstatus = "status
";
4361 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4362 $fieldstatus = 'status';
4365 $sql = "UPDATE
".$this->db->prefix().$elementTable;
4366 $sql .= " SET
".$fieldstatus." =
".((int) $status);
4367 // If status = 1 = validated, update also fk_user_valid
4368 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4369 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4370 $sql .= ", fk_user_valid =
".((int) $user->id);
4372 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4373 $sql .= ", date_valid =
'".$this->db->idate(dol_now())."'";
4375 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4376 $sql .= ", date_validation =
'".$this->db->idate(dol_now())."'";
4378 $sql .= " WHERE rowid =
".((int) $elementId);
4379 $sql .= " AND
".$fieldstatus." <>
".((int) $status); // We avoid update if status already correct
4381 dol_syslog(get_class($this)."::
setStatut", LOG_DEBUG);
4382 $resql = $this->db->query($sql);
4386 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4388 if ($nb_rows_affected >= 0) {
4389 if (empty($trigkey)) {
4390 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4391 if ($this->element == 'supplier_proposal' && $status == 2) {
4392 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4394 if ($this->element == 'supplier_proposal' && $status == 3) {
4395 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4397 if ($this->element == 'supplier_proposal' && $status == 4) {
4398 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4400 if ($this->element == 'fichinter' && $status == 3) {
4401 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4403 if ($this->element == 'fichinter' && $status == 2) {
4404 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4406 if ($this->element == 'fichinter' && $status == 1) {
4407 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4413 $result = $this->call_trigger($trigkey, $user);
4417 // End call triggers
4420 // The status was probably already good. We do nothing more, no triggers.
4424 $this->db->commit();
4426 if (empty($savElementId)) {
4427 // If the element we update is $this (so $elementId was provided as null)
4428 if ($fieldstatus == 'tosell') {
4429 $this->status = $status;
4430 } elseif ($fieldstatus == 'tobuy') {
4431 $this->status_buy = $status;
4433 $this->statut = $status;
4434 $this->status = $status;
4440 $this->db->rollback();
4441 dol_syslog(get_class($this)."::
setStatut ".$this->error, LOG_ERR);
4445 $this->error = $this->db->lasterror();
4446 $this->db->rollback();
4459 public function getCanvas($id = 0, $ref = '')
4463 if (empty($id) && empty($ref)) {
4466 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4467 return 0; // To increase speed. Not enabled by default.
4473 $sql = "SELECT rowid, canvas
";
4474 $sql .= " FROM
".$this->db->prefix().$this->table_element;
4475 $sql .= " WHERE entity IN (
".getEntity($this->element).")
";
4477 $sql .= " AND rowid =
".((int) $id);
4480 $sql .= " AND
ref =
'".$this->db->escape($ref)."'";
4483 $resql = $this->db->query($sql);
4485 $obj = $this->db->fetch_object($resql);
4487 $this->canvas = $obj->canvas;
4493 dol_print_error($this->db);
4505 public function getSpecialCode($lineid)
4507 $sql = "SELECT special_code FROM
".$this->db->prefix().$this->table_element_line;
4508 $sql .= " WHERE rowid =
".((int) $lineid);
4509 $resql = $this->db->query($sql);
4511 $row = $this->db->fetch_row($resql);
4524 public function isObjectUsed($id = 0, $entity = 0)
4533 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4534 dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4538 $arraytoscan = $this->childtables;
4539 // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4540 $tmparray = array_keys($this->childtables);
4541 if (is_numeric($tmparray[0])) {
4542 $arraytoscan = array_flip($this->childtables);
4545 // Test if child exists
4547 foreach ($arraytoscan as $table => $element) {
4548 //print $id.'-'.$table.'-'.$elementname.'<br>';
4549 // Check if element can be deleted
4550 $sql = "SELECT COUNT(*) as nb
";
4551 $sql.= " FROM
".$this->db->prefix().$table." as c
";
4552 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4553 $sql.= ",
".$this->db->prefix().$element['parent']." as p
";
4555 $sql.= " WHERE c.
".$this->fk_element." =
".((int) $id);
4556 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4557 $sql.= " AND c.
".$element['parentkey']." = p.rowid
";
4559 if (!empty($entity)) {
4560 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4561 $sql.= " AND p.entity =
".((int) $entity);
4563 $sql.= " AND c.entity =
".((int) $entity);
4566 $resql = $this->db->query($sql);
4568 $obj = $this->db->fetch_object($resql);
4570 $langs->load("errors
");
4571 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4572 $haschild += $obj->nb;
4573 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4574 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4575 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4576 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4577 } else { // new usage: $element['name']=Translation key
4578 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4580 break; // We found at least one, we stop here
4583 $this->errors[] = $this->db->lasterror();
4587 if ($haschild > 0) {
4588 $this->errors[] = "ErrorRecordHasChildren
";
4601 public function hasProductsOrServices($predefined = -1)
4605 foreach ($this->lines as $key => $val) {
4607 if ($predefined == -1) {
4610 if ($predefined == 1 && $val->fk_product > 0) {
4613 if ($predefined == 0 && $val->fk_product <= 0) {
4616 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4619 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4626 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4635 public function getTotalDiscount()
4637 if (!empty($this->table_element_line) ) {
4638 $total_discount = 0.00;
4640 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht
";
4641 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
4642 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
4644 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4645 $resql = $this->db->query($sql);
4647 $num = $this->db->num_rows($resql);
4650 $obj = $this->db->fetch_object($resql);
4652 $pu_ht = $obj->pu_ht;
4654 $total_ht = $obj->total_ht;
4656 $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4657 $total_discount += $total_discount_line;
4663 //print $total_discount; exit;
4664 return price2num($total_discount);
4677 public function getTotalWeightVolume()
4681 // defined for shipment only
4683 // defined for shipment only
4686 foreach ($this->lines as $line) {
4687 if (isset($line->qty_asked)) {
4688 if (empty($totalOrdered)) {
4689 $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4691 $totalOrdered += $line->qty_asked; // defined for shipment only
4693 if (isset($line->qty_shipped)) {
4694 if (empty($totalToShip)) {
4695 $totalToShip = 0; // Avoid warning because $totalToShip is ''
4697 $totalToShip += $line->qty_shipped; // defined for shipment only
4698 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4699 if (empty($totalToShip)) {
4702 $totalToShip += $line->qty; // defined for reception only
4705 // Define qty, weight, volume, weight_units, volume_units
4706 if ($this->element == 'shipping') {
4708 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4710 $qty = $line->qty ? $line->qty : 0;
4713 $weight = !empty($line->weight) ? $line->weight : 0;
4714 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4715 $volume = !empty($line->volume) ? $line->volume : 0;
4716 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4718 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4719 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4720 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4721 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4725 if (!empty($weight_units)) {
4726 $weightUnit = $weight_units;
4728 if (!empty($volume_units)) {
4729 $volumeUnit = $volume_units;
4732 if (empty($totalWeight)) {
4733 $totalWeight = 0; // Avoid warning because $totalWeight is ''
4735 if (empty($totalVolume)) {
4736 $totalVolume = 0; // Avoid warning because $totalVolume is ''
4739 //var_dump($line->volume_units);
4740 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4741 $trueWeightUnit = pow(10, $weightUnit);
4742 $totalWeight += $weight * $qty * $trueWeightUnit;
4744 if ($weight_units == 99) {
4745 // conversion 1 Pound = 0.45359237 KG
4746 $trueWeightUnit = 0.45359237;
4747 $totalWeight += $weight * $qty * $trueWeightUnit;
4748 } elseif ($weight_units == 98) {
4749 // conversion 1 Ounce = 0.0283495 KG
4750 $trueWeightUnit = 0.0283495;
4751 $totalWeight += $weight * $qty * $trueWeightUnit;
4753 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4756 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4757 //print $line->volume."x
".$line->volume_units."x
".($line->volume_units < 50)."x
".$volumeUnit;
4758 $trueVolumeUnit = pow(10, $volumeUnit);
4759 //print $line->volume;
4760 $totalVolume += $volume * $qty * $trueVolumeUnit;
4762 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4766 return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4775 public function setExtraParameters()
4779 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4781 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
4782 $sql .= " SET extraparams =
".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null
");
4783 $sql .= " WHERE rowid =
".((int) $this->id);
4786 $resql = $this->db->query($sql);
4788 $this->error = $this->db->lasterror();
4789 $this->db->rollback();
4792 $this->db->commit();
4798 // --------------------
4799 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4800 // --------------------
4802 /* This is to show add lines */
4813 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4815 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4819 if (!is_object($extrafields)) {
4820 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4821 $extrafields = new ExtraFields($this->db);
4823 $extrafields->fetch_name_optionals_label($this->table_element_line);
4825 // Output template part (modules that overwrite templates must declare this into descriptor)
4826 // Use global variables + $dateSelector + $seller and $buyer
4827 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4828 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4829 foreach ($dirtpls as $module => $reldir) {
4830 if (!empty($module)) {
4831 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4833 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4836 if (empty($conf->file->strict_mode)) {
4837 $res = @include $tpl;
4839 $res = include $tpl; // for debug
4849 /* This is to show array of line of details */
4866 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4868 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4869 // TODO We should not use global var for this
4870 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4872 // Define usemargins
4874 if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4878 $num = count($this->lines);
4881 if (!is_object($extrafields)) {
4882 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4883 $extrafields = new ExtraFields($this->db);
4885 $extrafields->fetch_name_optionals_label($this->table_element_line);
4887 $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4888 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4889 if (empty($reshook)) {
4890 // Output template part (modules that overwrite templates must declare this into descriptor)
4891 // Use global variables + $dateSelector + $seller and $buyer
4892 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4893 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4894 foreach ($dirtpls as $module => $reldir) {
4895 if (!empty($module)) {
4896 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4898 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4900 if (empty($conf->file->strict_mode)) {
4901 $res = @include $tpl;
4903 $res = include $tpl; // for debug
4914 foreach ($this->lines as $line) {
4916 $line->fetch_optionals();
4918 //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4919 if (is_object($hookmanager)) { // Old code is commented on preceding line.
4920 if (empty($line->fk_parent_line)) {
4921 $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4922 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4924 $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);
4925 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4928 if (empty($reshook)) {
4929 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4954 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4956 global $conf, $langs, $user, $object, $hookmanager;
4958 global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4960 $object_rights = $this->getRights();
4962 $element = $this->element;
4967 // Line in view mode
4968 if ($action != 'editline' || $selected != $line->id) {
4970 if ($line->fk_product > 0) {
4971 $product_static = new Product($this->db);
4972 $product_static->fetch($line->fk_product);
4974 $product_static->ref = $line->ref; //can change ref in hook
4975 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
4977 $text = $product_static->getNomUrl(1);
4979 // Define output language and label
4980 if (!empty($conf->global->MAIN_MULTILANGS)) {
4981 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
4982 dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4986 $prod = new Product($this->db);
4987 $prod->fetch($line->fk_product);
4989 $outputlangs = $langs;
4991 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
4992 $newlang = GETPOST('lang_id', 'aZ09');
4994 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
4995 $newlang = $this->thirdparty->default_lang; // To use language of customer
4997 if (!empty($newlang)) {
4998 $outputlangs = new Translate("", $conf);
4999 $outputlangs->setDefaultLang($newlang);
5002 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label
"])) ? $prod->multilangs[$outputlangs->defaultlang]["label
"] : $line->product_label;
5004 $label = $line->product_label;
5007 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5008 $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.
5011 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5013 // Output template part (modules that overwrite templates must declare this into descriptor)
5014 // Use global variables + $dateSelector + $seller and $buyer
5015 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5016 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5017 foreach ($dirtpls as $module => $reldir) {
5018 if (!empty($module)) {
5019 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5021 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5024 if (empty($conf->file->strict_mode)) {
5025 $res = @include $tpl;
5027 $res = include $tpl; // for debug
5035 // Line in update mode
5036 if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5037 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5039 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5041 // Output template part (modules that overwrite templates must declare this into descriptor)
5042 // Use global variables + $dateSelector + $seller and $buyer
5043 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5044 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5045 foreach ($dirtpls as $module => $reldir) {
5046 if (!empty($module)) {
5047 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5049 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5052 if (empty($conf->file->strict_mode)) {
5053 $res = @include $tpl;
5055 $res = include $tpl; // for debug
5065 /* This is to show array of line of details of source object */
5078 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5080 global $langs, $hookmanager, $conf, $form, $action;
5082 print '<tr class="liste_titre
">';
5083 print '<td class="linecolref
">'.$langs->trans('Ref').'</td>';
5084 print '<td class="linecoldescription
">'.$langs->trans('Description').'</td>';
5085 print '<td class="linecolvat right
">'.$langs->trans('VATRate').'</td>';
5086 print '<td class="linecoluht right
">'.$langs->trans('PriceUHT').'</td>';
5087 if (!empty($conf->multicurrency->enabled)) {
5088 print '<td class="linecoluht_currency right
">'.$langs->trans('PriceUHTCurrency').'</td>';
5090 print '<td class="linecolqty right
">'.$langs->trans('Qty').'</td>';
5091 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5092 print '<td class="linecoluseunit left
">'.$langs->trans('Unit').'</td>';
5094 print '<td class="linecoldiscount right
">'.$langs->trans('ReductionShort').'</td>';
5095 print '<td class="linecolht right
">'.$langs->trans('TotalHT').'</td>';
5096 print '<td class="center
">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5100 if (!empty($this->lines)) {
5101 foreach ($this->lines as $line) {
5103 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5104 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5105 $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5106 if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5107 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5109 if (empty($reshook)) {
5110 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5131 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5133 global $langs, $conf;
5136 if (!empty($line->date_start)) {
5137 $date_start = $line->date_start;
5139 $date_start = $line->date_debut_prevue;
5140 if ($line->date_debut_reel) {
5141 $date_start = $line->date_debut_reel;
5144 if (!empty($line->date_end)) {
5145 $date_end = $line->date_end;
5147 $date_end = $line->date_fin_prevue;
5148 if ($line->date_fin_reel) {
5149 $date_end = $line->date_fin_reel;
5153 $this->tpl['id'] = $line->id;
5155 $this->tpl['label'] = '';
5156 if (!empty($line->fk_parent_line)) {
5157 $this->tpl['label'] .= img_picto('', 'rightarrow');
5160 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5161 $discount = new DiscountAbsolute($this->db);
5162 $discount->fk_soc = $this->socid;
5163 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5164 } elseif (!empty($line->fk_product)) {
5165 $productstatic = new Product($this->db);
5166 $productstatic->id = $line->fk_product;
5167 $productstatic->ref = $line->ref;
5168 $productstatic->type = $line->fk_product_type;
5169 if (empty($productstatic->ref)) {
5170 $line->fetch_product();
5171 $productstatic = $line->product;
5174 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5175 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5177 if ($line->product_type == 1 && ($date_start || $date_end)) {
5178 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5181 $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5182 if (!empty($line->desc)) {
5183 $this->tpl['label'] .= $line->desc;
5185 $this->tpl['label'] .= ($line->label ? ' '.$line->label : '');
5189 if ($line->product_type == 1 && ($date_start || $date_end)) {
5190 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5194 if (!empty($line->desc)) {
5195 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5196 $discount = new DiscountAbsolute($this->db);
5197 $discount->fetch($line->fk_remise_except);
5198 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote
", $discount->getNomUrl(0));
5199 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5200 $discount = new DiscountAbsolute($this->db);
5201 $discount->fetch($line->fk_remise_except);
5202 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit
", $discount->getNomUrl(0));
5203 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5204 $discount = new DiscountAbsolute($this->db);
5205 $discount->fetch($line->fk_remise_except);
5206 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived
", $discount->getNomUrl(0));
5207 } elseif ($line->desc == '(EXCESS PAID)') {
5208 $discount = new DiscountAbsolute($this->db);
5209 $discount->fetch($line->fk_remise_except);
5210 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid
", $discount->getNomUrl(0));
5212 $this->tpl['description'] = dol_trunc($line->desc, 60);
5215 $this->tpl['description'] = ' ';
5219 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5220 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5221 if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5222 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5225 $this->tpl['price'] = price($line->subprice);
5226 $this->tpl['total_ht'] = price($line->total_ht);
5227 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5228 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' ';
5229 if (!empty($conf->global->PRODUCT_USE_UNITS)) {
5230 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5232 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' ';
5234 // Is the line strike or not
5235 $this->tpl['strike'] = 0;
5236 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5237 $this->tpl['strike'] = 1;
5240 // Output template part (modules that overwrite templates must declare this into descriptor)
5241 // Use global variables + $dateSelector + $seller and $buyer
5242 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5243 foreach ($dirtpls as $module => $reldir) {
5244 if (!empty($module)) {
5245 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5247 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5250 if (empty($conf->file->strict_mode)) {
5251 $res = @include $tpl;
5253 $res = include $tpl; // for debug
5262 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5273 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5278 $sql = "INSERT INTO
".$this->db->prefix()."element_resources (
";
5279 $sql .= "resource_id
";
5280 $sql .= ", resource_type
";
5281 $sql .= ", element_id
";
5282 $sql .= ", element_type
";
5284 $sql .= ", mandatory
";
5285 $sql .= ") VALUES (
";
5286 $sql .= $resource_id;
5287 $sql .= ",
'".$this->db->escape($resource_type)."'";
5288 $sql .= ",
'".$this->db->escape($this->id)."'";
5289 $sql .= ",
'".$this->db->escape($this->element)."'";
5290 $sql .= ",
'".$this->db->escape($busy)."'";
5291 $sql .= ",
'".$this->db->escape($mandatory)."'";
5295 if ($this->db->query($sql)) {
5296 $this->db->commit();
5299 $this->error = $this->db->lasterror();
5300 $this->db->rollback();
5305 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5314 public function delete_resource($rowid, $element, $notrigger = 0)
5321 $sql = "DELETE FROM
".$this->db->prefix()."element_resources
";
5322 $sql .= " WHERE rowid =
".((int) $rowid);
5326 $resql = $this->db->query($sql);
5328 $this->error = $this->db->lasterror();
5329 $this->db->rollback();
5333 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5335 $this->db->rollback();
5339 $this->db->commit();
5350 public function __clone()
5352 // Force a copy of this->lines, otherwise it will point to same object.
5353 if (isset($this->lines) && is_array($this->lines)) {
5354 $nboflines = count($this->lines);
5355 for ($i = 0; $i < $nboflines; $i++) {
5356 $this->lines[$i] = clone $this->lines[$i];
5374 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5376 global $conf, $langs, $user, $hookmanager, $action;
5378 $srctemplatepath = '';
5380 $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5381 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5383 if (empty($reshook)) {
5384 dol_syslog("commonGenerateDocument modele=
".$modele." outputlangs->defaultlang=
".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5386 if (empty($modele)) {
5387 $this->error = 'BadValueForParameterModele';
5391 // Increase limit for PDF build
5392 $err = error_reporting();
5394 @set_time_limit(120);
5395 error_reporting($err);
5397 // If selected model is a filename template (then $modele="modelname
" or "modelname:filename
")
5398 $tmp = explode(':', $modele, 2);
5399 if (!empty($tmp[1])) {
5401 $srctemplatepath = $tmp[1];
5404 // Search template files
5408 $dirmodels = array('/');
5409 if (is_array($conf->modules_parts['models'])) {
5410 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5412 foreach ($dirmodels as $reldir) {
5413 foreach (array('doc', 'pdf') as $prefix) {
5414 if (in_array(get_class($this), array('Adherent'))) {
5415 // Member module use prefix_modele.class.php
5416 $file = $prefix."_
".$modele.".class.php
";
5418 // Other module use prefix_modele.modules.php
5419 $file = $prefix."_
".$modele.".modules.php
";
5422 // On verifie l'emplacement du modele
5423 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5424 if (file_exists($file)) {
5426 $classname = $prefix.'_'.$modele;
5435 // If generator was found
5437 global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5441 $obj = new $classname($this->db);
5443 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5444 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5445 $varfortemplatedir = $obj->scandir;
5446 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5447 $dirtoscan = $conf->global->$varfortemplatedir;
5449 $listoffiles = array();
5451 // Now we add first model found in directories scanned
5452 $listofdir = explode(',', $dirtoscan);
5453 foreach ($listofdir as $key => $tmpdir) {
5454 $tmpdir = trim($tmpdir);
5455 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5457 unset($listofdir[$key]);
5460 if (is_dir($tmpdir)) {
5461 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5462 if (count($tmpfiles)) {
5463 $listoffiles = array_merge($listoffiles, $tmpfiles);
5468 if (count($listoffiles)) {
5469 foreach ($listoffiles as $record) {
5470 $srctemplatepath = $record['fullname'];
5476 if (empty($srctemplatepath)) {
5477 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5482 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5483 if (!dol_is_file($srctemplatepath)) {
5484 dol_syslog("Failed to locate
template file
".$srctemplatepath, LOG_WARNING);
5485 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5490 // We save charset_output to restore it because write_file can change it if needed for
5491 // output format that does not support UTF8.
5492 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5494 if (in_array(get_class($this), array('Adherent'))) {
5495 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5497 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5499 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5501 if ($resultwritefile > 0) {
5502 $outputlangs->charset_output = $sav_charset_output;
5504 // We delete old preview
5505 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5506 dol_delete_preview($this);
5508 // Index file in database
5509 if (!empty($obj->result['fullpath'])) {
5510 $destfull = $obj->result['fullpath'];
5512 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5513 $update_main_doc_field = 0;
5514 if (!empty($obj->update_main_doc_field)) {
5515 $update_main_doc_field = 1;
5518 $this->indexFile($destfull, $update_main_doc_field);
5520 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);
5523 // Success in building document. We build meta file.
5524 dol_meta_create($this);
5528 $outputlangs->charset_output = $sav_charset_output;
5529 $this->error = $obj->error;
5530 $this->errors = $obj->errors;
5531 dol_syslog("Error generating document
for ".__CLASS__.". Error:
".$obj->error, LOG_ERR);
5536 $this->error = $langs->trans("Error
").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5537 $this->errors[] = $this->error;
5538 dol_syslog($this->error, LOG_ERR);
5540 $this->error = $langs->trans("Error
")." ".$langs->trans("ErrorFileDoesNotExists
", $filefound);
5541 $this->errors[] = $this->error;
5542 dol_syslog($this->error, LOG_ERR);
5560 public function indexFile($destfull, $update_main_doc_field)
5562 global $conf, $user;
5564 $upload_dir = dirname($destfull);
5565 $destfile = basename($destfull);
5566 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5568 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5569 $filename = basename($destfile);
5570 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5571 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5573 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5574 $ecmfile = new EcmFiles($this->db);
5575 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5577 // Set the public "share
" key
5578 $setsharekey = false;
5579 if ($this->element == 'propal' || $this->element == 'proposal') {
5580 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5581 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5583 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5584 $setsharekey = true;
5587 if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5588 $setsharekey = true;
5590 if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5591 $setsharekey = true;
5593 if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5594 $setsharekey = true;
5596 if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5597 $setsharekey = true;
5599 if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5600 $setsharekey = true;
5604 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5605 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5606 $ecmfile->share = getRandomPassword(true);
5611 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5612 $ecmfile->fullpath_orig = '';
5613 $ecmfile->gen_or_uploaded = 'generated';
5614 $ecmfile->description = ''; // indexed content
5615 $ecmfile->keywords = ''; // keyword content
5616 $result = $ecmfile->update($user);
5618 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5622 $ecmfile->entity = $conf->entity;
5623 $ecmfile->filepath = $rel_dir;
5624 $ecmfile->filename = $filename;
5625 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5626 $ecmfile->fullpath_orig = '';
5627 $ecmfile->gen_or_uploaded = 'generated';
5628 $ecmfile->description = ''; // indexed content
5629 $ecmfile->keywords = ''; // keyword content
5630 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5631 $ecmfile->src_object_id = $this->id;
5633 $result = $ecmfile->create($user);
5635 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5640 /*$this->result['fullname']=$destfull;
5641 $this->result['filepath']=$ecmfile->filepath;
5642 $this->result['filename']=$ecmfile->filename;*/
5643 //var_dump($obj->update_main_doc_field);exit;
5645 if ($update_main_doc_field && !empty($this->table_element)) {
5646 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET last_main_doc =
'".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5647 $sql .= " WHERE rowid =
".((int) $this->id);
5649 $resql = $this->db->query($sql);
5651 dol_print_error($this->db);
5654 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5669 public function addThumbs($file)
5671 global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
5673 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
5675 $file_osencoded = dol_osencode($file);
5676 if (file_exists($file_osencoded)) {
5677 // Create small thumbs for company (Ratio is near 16/9)
5678 // Used on logon for example
5679 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5681 // Create mini thumbs for company (Ratio is near 16/9)
5682 // Used on menu or for setup page for example
5683 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5688 /* Functions common to commonobject and commonobjectline */
5690 /* For default values */
5704 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5706 global $conf, $_POST;
5708 // If param here has been posted, we use this value first.
5709 if (GETPOSTISSET($fieldname)) {
5710 return GETPOST($fieldname, 'alphanohtml', 3);
5713 if (isset($alternatevalue)) {
5714 return $alternatevalue;
5717 $newelement = $this->element;
5718 if ($newelement == 'facture') {
5719 $newelement = 'invoice';
5721 if ($newelement == 'commande') {
5722 $newelement = 'order';
5724 if (empty($newelement)) {
5725 dol_syslog("Ask a
default value
using common method getDefaultCreateValueForField on an
object with no property ->element defined. Return empty
string.
", LOG_WARNING);
5729 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5730 //var_dump($keyforfieldname);
5731 if (isset($conf->global->$keyforfieldname)) {
5732 return $conf->global->$keyforfieldname;
5735 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5753 public function call_trigger($triggerName, $user)
5756 global $langs, $conf;
5757 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5758 dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_
" as required.');
5761 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5762 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5763 $langs = new Translate('', $conf);
5766 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5767 $interface = new Interfaces($this->db);
5768 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5771 if (!empty($this->errors)) {
5772 $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.
5774 $this->errors = $interface->errors;
5781 /* Functions for data in other language */
5791 public function fetchValuesForExtraLanguages()
5793 // To avoid SQL errors. Probably not the better solution though
5794 if (!$this->element) {
5797 if (!($this->id > 0)) {
5800 if (is_array($this->array_languages)) {
5804 $this->array_languages = array();
5806 $element = $this->element;
5807 if ($element == 'categorie') {
5808 $element = 'categories'; // For compatibility
5811 // Request to get translation values for object
5812 $sql = "SELECT rowid, property, lang , value
";
5813 $sql .= " FROM
".$this->db->prefix()."object_lang
";
5814 $sql .= " WHERE type_object =
'".$this->db->escape($element)."'";
5815 $sql .= " AND fk_object =
".((int) $this->id);
5817 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
5818 $resql = $this->db->query($sql);
5820 $numrows = $this->db->num_rows($resql);
5823 while ($i < $numrows) {
5824 $obj = $this->db->fetch_object($resql);
5825 $key = $obj->property;
5826 $value = $obj->value;
5827 $codelang = $obj->lang;
5828 $type = $this->fields[$key]['type'];
5830 // we can add this attribute to object
5831 if (preg_match('/date/', $type)) {
5832 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5834 $this->array_languages[$key][$codelang] = $value;
5841 $this->db->free($resql);
5849 dol_print_error($this->db);
5860 public function setValuesForExtraLanguages($onlykey = '')
5862 global $_POST, $langs;
5865 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5866 $tmparray = explode('-', $postfieldkey);
5867 if ($tmparray[0] != 'field') {
5871 $element = $tmparray[1];
5872 $key = $tmparray[2];
5873 $codelang = $tmparray[3];
5874 //var_dump("postfieldkey=
".$postfieldkey." element=
".$element." key=
".$key." codelang=
".$codelang);
5876 if (!empty($onlykey) && $key != $onlykey) {
5879 if ($element != $this->element) {
5883 $key_type = $this->fields[$key]['type'];
5886 if (isset($this->fields[$key]['enabled'])) {
5887 $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5890 if (isset($this->fields[$key]['perms']))
5892 $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5894 if (empty($enabled)) {
5897 //if (empty($perms)) continue;
5899 if (in_array($key_type, array('date'))) {
5901 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5902 $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month
", 'int'), GETPOST($postfieldkey."day
", 'int'), GETPOST($postfieldkey."year
", 'int'));
5903 } elseif (in_array($key_type, array('datetime'))) {
5905 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5906 $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'));
5907 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5908 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5909 if (!empty($value_arr)) {
5910 $value_key = implode(',', $value_arr);
5914 } elseif (in_array($key_type, array('price', 'double'))) {
5915 $value_arr = GETPOST($postfieldkey, 'alpha');
5916 $value_key = price2num($value_arr);
5918 $value_key = GETPOST($postfieldkey);
5919 if (in_array($key_type, array('link')) && $value_key == '-1') {
5924 $this->array_languages[$key][$codelang] = $value_key;
5926 /*if ($nofillrequired) {
5927 $langs->load('errors');
5928 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5937 /* Functions for extrafields */
5945 public function fetchNoCompute($id)
5949 $savDisableCompute = $conf->disable_compute;
5950 $conf->disable_compute = 1;
5952 $ret = $this->fetch($id);
5954 $conf->disable_compute = $savDisableCompute;
5959 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5969 public function fetch_optionals($rowid = null, $optionsArray = null)
5972 global $conf, $extrafields;
5974 if (empty($rowid)) {
5977 if (empty($rowid) && isset($this->rowid)) {
5978 $rowid = $this->rowid; // deprecated
5981 // To avoid SQL errors. Probably not the better solution though
5982 if (!$this->table_element) {
5986 $this->array_options = array();
5988 if (!is_array($optionsArray)) {
5989 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
5990 if (!isset($extrafields) || !is_object($extrafields)) {
5991 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5992 $extrafields = new ExtraFields($this->db);
5995 // Load array of extrafields for elementype = $this->table_element
5996 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
5997 $extrafields->fetch_name_optionals_label($this->table_element);
5999 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6001 global $extrafields;
6002 dol_syslog("Warning:
fetch_optionals was called with param optionsArray defined when you should pass null now
", LOG_WARNING);
6005 $table_element = $this->table_element;
6006 if ($table_element == 'categorie') {
6007 $table_element = 'categories'; // For compatibility
6010 // Request to get complementary values
6011 if (is_array($optionsArray) && count($optionsArray) > 0) {
6012 $sql = "SELECT rowid
";
6013 foreach ($optionsArray as $name => $label) {
6014 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6018 $sql .= " FROM
".$this->db->prefix().$table_element."_extrafields
";
6019 $sql .= " WHERE fk_object =
".((int) $rowid);
6021 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
6022 $resql = $this->db->query($sql);
6024 $numrows = $this->db->num_rows($resql);
6026 $tab = $this->db->fetch_array($resql);
6028 foreach ($tab as $key => $value) {
6029 // 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)
6030 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6031 // we can add this attribute to object
6032 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6033 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6034 $this->array_options["options_
".$key] = $this->db->jdate($value);
6036 $this->array_options["options_
".$key] = $value;
6039 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_
".$key]);
6043 // If field is a computed field, value must become result of compute
6044 foreach ($tab as $key => $value) {
6045 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6046 //var_dump($conf->disable_compute);
6047 if (empty($conf->disable_compute)) {
6048 $this->array_options["options_
".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6054 $this->db->free($resql);
6062 $this->errors[]=$this->db->lasterror;
6075 public function deleteExtraFields()
6079 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6085 $table_element = $this->table_element;
6086 if ($table_element == 'categorie') {
6087 $table_element = 'categories'; // For compatibility
6092 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6094 $resql = $this->db->query($sql_del);
6096 $this->error = $this->db->lasterror();
6097 $this->db->rollback();
6100 $this->db->commit();
6115 public function insertExtraFields($trigger = '', $userused = null)
6117 global $conf, $langs, $user;
6119 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6123 if (empty($userused)) {
6129 if (!empty($this->array_options)) {
6131 $langs->load('admin');
6132 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6133 $extrafields = new ExtraFields($this->db);
6134 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6136 // Eliminate copied source object extra fields that do not exist in target object
6137 $new_array_options = array();
6138 foreach ($this->array_options as $key => $value) {
6139 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6140 $new_array_options[$key] = $value;
6141 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6142 $new_array_options['options_'.$key] = $value;
6146 foreach ($new_array_options as $key => $value) {
6147 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6148 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6149 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6150 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6151 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6152 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6153 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6155 // If we clone, we have to clean unique extrafields to prevent duplicates.
6156 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6157 if (! empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && ! empty($attributeUnique)) {
6158 $new_array_options[$key] = null;
6161 // Similar code than into insertExtraFields
6162 if ($attributeRequired) {
6163 $mandatorypb = false;
6164 if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6165 $mandatorypb = true;
6167 if ($this->array_options[$key] === '') {
6168 $mandatorypb = true;
6170 if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6171 $mandatorypb = true;
6174 $langs->load("errors
");
6175 dol_syslog("Mandatory field
'".$key."' is empty during create and set to required into definition of extrafields
");
6176 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6181 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6182 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6184 if (!empty($attrfieldcomputed)) {
6185 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6186 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6187 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6188 $new_array_options[$key] = $value;
6190 $new_array_options[$key] = null;
6194 switch ($attributeType) {
6196 if (!is_numeric($value) && $value != '') {
6197 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6199 } elseif ($value == '') {
6200 $new_array_options[$key] = null;
6205 $value = price2num($value);
6206 if (!is_numeric($value) && $value != '') {
6207 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." for ".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6208 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6210 } elseif ($value == '') {
6213 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6214 $new_array_options[$key] = $value;
6216 /*case 'select': // Not required, we chosed value='0' for undefined values
6219 $this->array_options[$key] = null;
6224 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6225 // If there is an encryption choice, we use it to crypt data before insert
6226 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6227 $algo = reset($tmparrays);
6229 //global $action; // $action may be 'create', 'update', 'update_extras'...
6230 //var_dump($action);
6231 //var_dump($this->oldcopy);exit;
6232 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
6233 //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6234 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.
6235 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6238 $newvalue = dol_hash($this->array_options[$key], $algo);
6239 $new_array_options[$key] = $newvalue;
6242 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6245 } else // Common usage
6247 $new_array_options[$key] = $this->array_options[$key];
6252 // If data is a string instead of a timestamp, we convert it
6253 if (!is_int($this->array_options[$key])) {
6254 $this->array_options[$key] = strtotime($this->array_options[$key]);
6256 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6259 $param_list = array_keys($attributeParam['options']);
6262 $InfoFieldList = explode(":
", $param_list[0]);
6263 dol_include_once($InfoFieldList[1]);
6264 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6265 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6266 $new_array_options[$key] = '';
6268 $object = new $InfoFieldList[0]($this->db);
6269 if (is_numeric($value)) {
6270 $res = $object->fetch($value); // Common case
6272 $res = $object->fetch('', $value); // For compatibility
6276 $new_array_options[$key] = $object->id;
6278 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6279 $this->db->rollback();
6284 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6292 $table_element = $this->table_element;
6293 if ($table_element == 'categorie') {
6294 $table_element = 'categories'; // For compatibility
6297 dol_syslog(get_class($this)."::
insertExtraFields delete then insert
", LOG_DEBUG);
6299 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6300 $this->db->query($sql_del);
6302 $sql = "INSERT INTO
".$this->db->prefix().$table_element."_extrafields (fk_object
";
6303 foreach ($new_array_options as $key => $value) {
6304 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6305 // Add field of attribut
6306 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6307 $sql .= ",
".$attributeKey;
6310 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6311 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6312 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6313 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6314 $sql .= ",
".$tmpkey;
6318 $sql .= ") VALUES (
".$this->id;
6320 foreach ($new_array_options as $key => $value) {
6321 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6322 // Add field of attribute
6323 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6324 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6325 $sql .= ",
'".$this->db->escape($new_array_options[$key])."'";
6331 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6332 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6333 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6334 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6335 if (in_array($tmpval, array('int', 'double', 'price'))) {
6346 $resql = $this->db->query($sql);
6348 $this->error = $this->db->lasterror();
6352 if (!$error && $trigger) {
6354 $this->context = array('extrafieldaddupdate'=>1);
6355 $result = $this->call_trigger($trigger, $userused);
6363 $this->db->rollback();
6366 $this->db->commit();
6384 public function insertExtraLanguages($trigger = '', $userused = null)
6386 global $conf, $langs, $user;
6388 if (empty($userused)) {
6394 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6395 return 0; // For avoid conflicts if trigger used
6398 if (is_array($this->array_languages)) {
6399 $new_array_languages = $this->array_languages;
6401 foreach ($new_array_languages as $key => $value) {
6402 $attributeKey = $key;
6403 $attributeType = $this->fields[$attributeKey]['type'];
6404 $attributeLabel = $this->fields[$attributeKey]['label'];
6406 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6407 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6409 switch ($attributeType) {
6411 if (!is_numeric($value) && $value != '') {
6412 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6414 } elseif ($value == '') {
6415 $new_array_languages[$key] = null;
6419 $value = price2num($value);
6420 if (!is_numeric($value) && $value != '') {
6421 dol_syslog($langs->trans("ExtraLanguageHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6422 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6424 } elseif ($value == '') {
6425 $new_array_languages[$key] = null;
6427 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6428 $new_array_languages[$key] = $value;
6430 /*case 'select': // Not required, we chosed value='0' for undefined values
6433 $this->array_options[$key] = null;
6441 $table_element = $this->table_element;
6442 if ($table_element == 'categorie') {
6443 $table_element = 'categories'; // For compatibility
6448 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6449 foreach ($langcodearray as $langcode => $value) {
6450 $sql_del = "DELETE FROM
".$this->db->prefix()."object_lang
";
6451 $sql_del .= " WHERE fk_object =
".((int) $this->id)." AND property =
'".$this->db->escape($key)."' AND type_object =
'".$this->db->escape($table_element)."'";
6452 $sql_del .= " AND lang =
'".$this->db->escape($langcode)."'";
6453 $this->db->query($sql_del);
6455 if ($value !== '') {
6456 $sql = "INSERT INTO
".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value
";
6457 $sql .= ") VALUES (
".$this->id.",
'".$this->db->escape($key)."',
'".$this->db->escape($table_element)."',
'".$this->db->escape($langcode)."',
'".$this->db->escape($value)."'";
6460 $resql = $this->db->query($sql);
6462 $this->error = $this->db->lasterror();
6470 if (!$error && $trigger) {
6472 $this->context = array('extralanguagesaddupdate'=>1);
6473 $result = $this->call_trigger($trigger, $userused);
6481 $this->db->rollback();
6484 $this->db->commit();
6502 public function updateExtraField($key, $trigger = null, $userused = null)
6504 global $conf, $langs, $user;
6506 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6510 if (empty($userused)) {
6516 if (!empty($this->array_options) && isset($this->array_options["options_
".$key])) {
6518 $langs->load('admin');
6519 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6520 $extrafields = new ExtraFields($this->db);
6521 $extrafields->fetch_name_optionals_label($this->table_element);
6523 $value = $this->array_options["options_
".$key];
6525 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6526 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6527 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6528 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6529 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6531 // Similar code than into insertExtraFields
6532 if ($attributeRequired) {
6533 $mandatorypb = false;
6534 if ($attributeType == 'link' && $this->array_options["options_
".$key] == '-1') {
6535 $mandatorypb = true;
6537 if ($this->array_options["options_
".$key] === '') {
6538 $mandatorypb = true;
6541 $langs->load("errors
");
6542 dol_syslog("Mandatory field
'options_".$key."' is empty during update and set to required into definition of extrafields
");
6543 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6548 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6549 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6551 if (!empty($attrfieldcomputed)) {
6552 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6553 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6554 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6555 $this->array_options["options_
".$key] = $value;
6557 $this->array_options["options_
".$key] = null;
6561 switch ($attributeType) {
6563 if (!is_numeric($value) && $value != '') {
6564 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6566 } elseif ($value === '') {
6567 $this->array_options["options_
".$key] = null;
6571 $value = price2num($value);
6572 if (!is_numeric($value) && $value != '') {
6573 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6574 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6576 } elseif ($value === '') {
6579 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6580 $this->array_options["options_
".$key] = $value;
6582 /*case 'select': // Not required, we chosed value='0' for undefined values
6585 $this->array_options[$key] = null;
6589 $this->array_options["options_
".$key] = price2num($this->array_options["options_
".$key]);
6593 if (empty($this->array_options["options_
".$key])) {
6594 $this->array_options["options_
".$key] = null;
6596 $this->array_options["options_
".$key] = $this->db->idate($this->array_options["options_
".$key]);
6600 if (empty($this->array_options["options_
".$key])) {
6601 $this->array_options["options_
".$key] = null;
6606 $param_list = array_keys($attributeParam['options']);
6609 $InfoFieldList = explode(":
", $param_list[0]);
6610 dol_include_once($InfoFieldList[1]);
6611 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6613 if ($value == '-1') // -1 is key for no defined in combo list of objects
6615 $new_array_options[$key] = '';
6617 $object = new $InfoFieldList[0]($this->db);
6618 if (is_numeric($value)) $res = $object->fetch($value); // Common case
6619 else $res = $object->fetch('', $value); // For compatibility
6621 if ($res > 0) $new_array_options[$key] = $object->id;
6623 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6624 $this->db->rollback();
6629 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6637 $linealreadyfound = 0;
6639 // 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)
6640 $sql = "SELECT COUNT(rowid) as nb FROM
".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6641 $resql = $this->db->query($sql);
6643 $tmpobj = $this->db->fetch_object($resql);
6645 $linealreadyfound = $tmpobj->nb;
6649 if ($linealreadyfound) {
6650 if ($this->array_options["options_
".$key] === null) {
6651 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." = null
";
6653 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
'".$this->db->escape($this->array_options["options_".$key])."'";
6655 $sql .= " WHERE fk_object =
".((int) $this->id);
6657 $result = $this->insertExtraFields('', $user);
6663 $resql = $this->db->query($sql);
6666 $this->error = $this->db->lasterror();
6668 if (!$error && $trigger) {
6670 $this->context = array('extrafieldupdate'=>1);
6671 $result = $this->call_trigger($trigger, $userused);
6679 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6680 $this->db->rollback();
6683 $this->db->commit();
6701 public function updateExtraLanguages($key, $trigger = null, $userused = null)
6703 global $conf, $langs, $user;
6705 if (empty($userused)) {
6711 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6712 return 0; // For avoid conflicts if trigger used
6733 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6735 global $conf, $langs, $form;
6737 if (!is_object($form)) {
6738 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6739 $form = new Form($this->db);
6742 if (!empty($this->fields)) {
6743 $val = $this->fields[$key];
6746 // Validation tests and output
6747 $fieldValidationErrorMsg = '';
6748 $validationClass = '';
6749 $fieldValidationErrorMsg = $this->getFieldError($key);
6750 if (!empty($fieldValidationErrorMsg)) {
6751 $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
6753 $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
6760 $param['options'] = array();
6762 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6763 // Because we work on extrafields
6764 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6765 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6767 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6768 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6770 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6771 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6773 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6774 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6776 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6777 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6779 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6780 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6782 } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6783 $param['options'] = array();
6786 } elseif (preg_match('/varchar/', $val['type'])) {
6787 $param['options'] = array();
6790 $param['options'] = array();
6791 $type = $this->fields[$key]['type'];
6794 // Special case that force options and type ($type can be integer, varchar, ...)
6795 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6796 $param['options'] = $this->fields[$key]['arrayofkeyval'];
6800 $label = $this->fields[$key]['label'];
6801 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6802 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6803 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6804 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6805 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6806 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6808 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6809 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6810 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6812 $objectid = $this->id;
6815 if (!preg_match('/^search_/', $keyprefix)) {
6816 return '<span class="opacitymedium
">'.$langs->trans("AutomaticallyCalculated
").'</span>';
6822 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6823 if (empty($morecss) && !empty($val['css'])) {
6824 $morecss = $val['css'];
6825 } elseif (empty($morecss)) {
6826 if ($type == 'date') {
6827 $morecss = 'minwidth100imp';
6828 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6829 $morecss = 'minwidth200imp';
6830 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6831 $morecss = 'maxwidth75';
6832 } elseif ($type == 'url') {
6833 $morecss = 'minwidth400';
6834 } elseif ($type == 'boolean') {
6837 if (round($size) < 12) {
6838 $morecss = 'minwidth100';
6839 } elseif (round($size) <= 48) {
6840 $morecss = 'minwidth200';
6842 $morecss = 'minwidth400';
6847 // Add validation state class
6848 if (!empty($validationClass)) {
6849 $morecss.= $validationClass;
6852 if (in_array($type, array('date'))) {
6853 $tmp = explode(',', $size);
6857 // Do not show current date when field not required (see selectDate() method)
6858 if (!$required && $value == '') {
6862 // TODO Must also support $moreparam
6863 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6864 } elseif (in_array($type, array('datetime'))) {
6865 $tmp = explode(',', $size);
6869 // Do not show current date when field not required (see selectDate() method)
6870 if (!$required && $value == '') $value = '-1';
6872 // TODO Must also support $moreparam
6873 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6874 } elseif (in_array($type, array('duration'))) {
6875 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6876 } elseif (in_array($type, array('int', 'integer'))) {
6877 $tmp = explode(',', $size);
6879 $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' : '').'>';
6880 } elseif (in_array($type, array('real'))) {
6881 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6882 } elseif (preg_match('/varchar/', $type)) {
6883 $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' : '').'>';
6884 } elseif (in_array($type, array('email', 'mail', 'phone', 'url'))) {
6885 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6886 } elseif (preg_match('/^text/', $type)) {
6887 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6888 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6889 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6890 $out = $doleditor->Create(1);
6892 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6894 } elseif (preg_match('/^html/', $type)) {
6895 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6896 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6897 $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%');
6898 $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6900 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6902 } elseif ($type == 'boolean') {
6904 if (!empty($value)) {
6905 $checked = ' checked value="1
" ';
6907 $checked = ' value="1
" ';
6909 $out = '<input type="checkbox
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6910 } elseif ($type == 'price') {
6911 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6912 $value = price($value);
6914 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6915 } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6916 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6917 $value = price($value);
6919 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6920 } elseif ($type == 'select') {
6922 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6923 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6924 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6927 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6928 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6929 $out .= '<option value="0
"> </option>';
6931 foreach ($param['options'] as $keyb => $valb) {
6932 if ((string) $keyb == '') {
6935 if (strpos($valb, "|
") !== false) {
6936 list($valb, $parent) = explode('|', $valb);
6938 $out .= '<option value="'.$keyb.'"';
6939 $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6940 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6941 $out .= '>'.$valb.'</option>';
6943 $out .= '</select>';
6944 } elseif ($type == 'sellist') {
6946 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6947 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6948 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6951 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6952 if (is_array($param['options'])) {
6953 $param_list = array_keys($param['options']);
6954 $InfoFieldList = explode(":
", $param_list[0]);
6958 // 1 : label field name
6959 // 2 : key fields name (if differ of rowid)
6960 // 3 : key field parent (for dependent lists)
6961 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
6962 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
6964 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
6965 if (strpos($InfoFieldList[4], 'extra.') !== false) {
6966 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
6968 $keyList = $InfoFieldList[2].' as rowid';
6971 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
6972 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
6973 $keyList .= ', '.$parentField;
6976 $fields_label = explode('|', $InfoFieldList[1]);
6977 if (is_array($fields_label)) {
6979 $keyList .= implode(', ', $fields_label);
6983 $sql = "SELECT
".$keyList;
6984 $sql .= " FROM
".$this->db->prefix().$InfoFieldList[0];
6985 if (!empty($InfoFieldList[4])) {
6986 // can use SELECT request
6987 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
6988 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
6991 // current object id can be use into filter
6992 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
6993 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
6995 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
6998 //We have to join on extrafield table
6999 if (strpos($InfoFieldList[4], 'extra') !== false) {
7000 $sql .= " as main,
".$this->db->prefix().$InfoFieldList[0]."_extrafields as extra
";
7001 $sqlwhere .= " WHERE extra.fk_object=main.
".$InfoFieldList[2]." AND
".$InfoFieldList[4];
7003 $sqlwhere .= " WHERE
".$InfoFieldList[4];
7006 $sqlwhere .= ' WHERE 1=1';
7008 // Some tables may have field, some other not. For the moment we disable it.
7009 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7010 $sqlwhere .= " AND entity =
".((int) $conf->entity);
7015 $sql .= ' ORDER BY '.implode(', ', $fields_label);
7017 dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
7018 $resql = $this->db->query($sql);
7020 $out .= '<option value="0
"> </option>';
7021 $num = $this->db->num_rows($resql);
7025 $obj = $this->db->fetch_object($resql);
7027 // Several field into label (eq table:code|libelle:rowid)
7029 $fields_label = explode('|', $InfoFieldList[1]);
7030 if (count($fields_label) > 1) {
7032 foreach ($fields_label as $field_toshow) {
7033 $labeltoshow .= $obj->$field_toshow.' ';
7036 $labeltoshow = $obj->{$InfoFieldList[1]};
7038 $labeltoshow = dol_trunc($labeltoshow, 45);
7040 if ($value == $obj->rowid) {
7041 foreach ($fields_label as $field_toshow) {
7042 $translabel = $langs->trans($obj->$field_toshow);
7043 if ($translabel != $obj->$field_toshow) {
7044 $labeltoshow = dol_trunc($translabel).' ';
7046 $labeltoshow = dol_trunc($obj->$field_toshow).' ';
7049 $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7052 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7053 if ($translabel != $obj->{$InfoFieldList[1]}) {
7054 $labeltoshow = dol_trunc($translabel, 18);
7056 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7059 if (empty($labeltoshow)) {
7060 $labeltoshow = '(not defined)';
7062 if ($value == $obj->rowid) {
7063 $out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
7066 if (!empty($InfoFieldList[3]) && $parentField) {
7067 $parent = $parentName.':'.$obj->{$parentField};
7071 $out .= '<option value="'.$obj->rowid.'"';
7072 $out .= ($value == $obj->rowid ? ' selected' : '');
7073 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7074 $out .= '>'.$labeltoshow.'</option>';
7079 $this->db->free($resql);
7081 print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7084 $out .= '</select>';
7085 } elseif ($type == 'checkbox') {
7086 $value_arr = explode(',', $value);
7087 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7088 } elseif ($type == 'radio') {
7090 foreach ($param['options'] as $keyopt => $valopt) {
7091 $out .= '<input class="flat
'.$morecss.'" type="radio
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7092 $out .= ' value="'.$keyopt.'"';
7093 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'"';
7094 $out .= ($value == $keyopt ? 'checked' : '');
7095 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'">'.$valopt.'</label><br>';
7097 } elseif ($type == 'chkbxlst') {
7098 if (is_array($value)) {
7099 $value_arr = $value;
7101 $value_arr = explode(',', $value);
7104 if (is_array($param['options'])) {
7105 $param_list = array_keys($param['options']);
7106 $InfoFieldList = explode(":
", $param_list[0]);
7110 // 1 : label field name
7111 // 2 : key fields name (if differ of rowid)
7112 // 3 : key field parent (for dependent lists)
7113 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7114 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7116 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7117 list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7118 $keyList .= ', '.$parentField;
7120 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7121 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7122 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7124 $keyList = $InfoFieldList[2].' as rowid';
7128 $fields_label = explode('|', $InfoFieldList[1]);
7129 if (is_array($fields_label)) {
7131 $keyList .= implode(', ', $fields_label);
7135 $sql = "SELECT
".$keyList;
7136 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7137 if (!empty($InfoFieldList[4])) {
7138 // can use SELECT request
7139 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7140 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7143 // current object id can be use into filter
7144 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7145 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7147 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7150 // We have to join on extrafield table
7151 if (strpos($InfoFieldList[4], 'extra') !== false) {
7152 $sql .= ' as main, '.$this->db->prefix().$InfoFieldList[0].'_extrafields as extra';
7153 $sqlwhere .= " WHERE extra.fk_object=main.
".$InfoFieldList[2]." AND
".$InfoFieldList[4];
7155 $sqlwhere .= " WHERE
".$InfoFieldList[4];
7158 $sqlwhere .= ' WHERE 1=1';
7160 // Some tables may have field, some other not. For the moment we disable it.
7161 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7162 $sqlwhere .= " AND entity =
".((int) $conf->entity);
7164 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7168 dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
7169 $resql = $this->db->query($sql);
7171 $num = $this->db->num_rows($resql);
7178 $obj = $this->db->fetch_object($resql);
7181 // Several field into label (eq table:code|libelle:rowid)
7182 $fields_label = explode('|', $InfoFieldList[1]);
7183 if (count($fields_label) > 1) {
7185 foreach ($fields_label as $field_toshow) {
7186 $labeltoshow .= $obj->$field_toshow.' ';
7189 $labeltoshow = $obj->{$InfoFieldList[1]};
7191 $labeltoshow = dol_trunc($labeltoshow, 45);
7193 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7194 foreach ($fields_label as $field_toshow) {
7195 $translabel = $langs->trans($obj->$field_toshow);
7196 if ($translabel != $obj->$field_toshow) {
7197 $labeltoshow = dol_trunc($translabel, 18).' ';
7199 $labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
7203 $data[$obj->rowid] = $labeltoshow;
7206 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7207 if ($translabel != $obj->{$InfoFieldList[1]}) {
7208 $labeltoshow = dol_trunc($translabel, 18);
7210 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
7213 if (empty($labeltoshow)) {
7214 $labeltoshow = '(not defined)';
7217 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7218 $data[$obj->rowid] = $labeltoshow;
7221 if (!empty($InfoFieldList[3]) && $parentField) {
7222 $parent = $parentName.':'.$obj->{$parentField};
7226 $data[$obj->rowid] = $labeltoshow;
7231 $this->db->free($resql);
7233 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
7235 print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
7238 } elseif ($type == 'link') {
7239 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
7240 $param_list_array = explode(':', $param_list[0]);
7241 $showempty = (($required && $default != '') ? 0 : 1);
7243 if (!preg_match('/search_/', $keyprefix)) {
7244 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7245 if (!empty($this->fields[$key]['picto'])) {
7246 $morecss .= ' widthcentpercentminusxx';
7248 $morecss .= ' widthcentpercentminusx';
7251 if (!empty($this->fields[$key]['picto'])) {
7252 $morecss .= ' widthcentpercentminusx';
7257 $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
7259 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7260 if (!GETPOSTISSET('backtopage') && empty($val['disabled']) && empty($nonewbutton)) { // To avoid to open several times the 'Create Object' button and to avoid to have button if field is protected by a "disabled
".
7261 list($class, $classfile) = explode(':', $param_list[0]);
7262 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
7263 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
7265 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
7267 $paramforthenewlink = '';
7268 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
7269 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
7270 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
7271 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
7272 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
7273 // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
7274 $out .= '<a class="butActionNew
" title="'.$langs->trans("New").'" href="'.$url_path.'?action=create&backtopage=
'.urlencode($_SERVER['PHP_SELF
'].($paramforthenewlink ? '?
'.$paramforthenewlink : '')).'"><span class="fa fa-plus-circle valignmiddle
"></span></a>';
7277 } elseif ($type == 'password') {
7278 // If prefix is 'search_', field is used as a filter, we use a common text field.
7279 $out = '<input type="'.($keyprefix == 'search_
' ? 'text
' : 'password
').'" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7280 } elseif ($type == 'array') {
7282 $newval['type'] = 'varchar(256)';
7285 if (!empty($value)) {
7286 foreach ($value as $option) {
7287 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del
" href="javascript:;
"><span class="fa fa-minus-circle valignmiddle
"></span></a> ';
7288 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
7291 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add
" href="javascript:;
"><span class="fa fa-plus-circle valignmiddle
"></span></a>';
7293 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del
" href="javascript:;
"><span class="fa fa-minus-circle valignmiddle
"></span></a> ';
7294 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
7296 if (!empty($conf->use_javascript_ajax)) {
7299 $(document).ready(function() {
7300 $("a#
'.dol_escape_js($keyprefix.$key.$keysuffix).'_add
").click(function() {
7301 $("'.dol_escape_js($newInput).'").insertBefore(this);
7304 $(document).on("click
", "a.
'.dol_escape_js($keyprefix.$key.$keysuffix).'_del
", function() {
7305 $(this).parent().remove();
7311 if (!empty($hidden)) {
7312 $out = '<input type="hidden
" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
7315 if ($isDependList==1) {
7316 $out .= $this->getJSListDependancies('_common');
7319 if ($type == 'date') $out.=' (YYYY-MM-DD)';
7320 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
7323 // Display error message for field
7324 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
7325 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
7344 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
7346 global $conf, $langs, $form;
7348 if (!is_object($form)) {
7349 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7350 $form = new Form($this->db);
7353 $objectid = $this->id; // Not used ???
7355 $label = empty($val['label']) ? '' : $val['label'];
7356 $type = empty($val['type']) ? '' : $val['type'];
7357 $size = empty($val['css']) ? '' : $val['css'];
7360 // Convert var to be able to share same code than showOutputField of extrafields
7361 if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7362 $type = 'varchar'; // convert varchar(xx) int varchar
7364 } elseif (preg_match('/varchar/', $type)) {
7365 $type = 'varchar'; // convert varchar(xx) int varchar
7367 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7370 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7374 $default = empty($val['default']) ? '' : $val['default'];
7375 $computed = empty($val['computed']) ? '' : $val['computed'];
7376 $unique = empty($val['unique']) ? '' : $val['unique'];
7377 $required = empty($val['required']) ? '' : $val['required'];
7379 $param['options'] = array();
7381 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7382 $param['options'] = $val['arrayofkeyval'];
7384 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7386 $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7387 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7388 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7390 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7391 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7393 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7394 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7398 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
7399 $list = (empty($val['list']) ? '' : $val['list']);
7400 $help = (empty($val['help']) ? '' : $val['help']);
7401 $hidden = (($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
7407 // If field is a computed field, value must become result of compute
7409 // Make the eval of compute string
7410 //var_dump($computed);
7411 $value = dol_eval($computed, 1, 0, '');
7414 if (empty($morecss)) {
7415 if ($type == 'date') {
7416 $morecss = 'minwidth100imp';
7417 } elseif ($type == 'datetime' || $type == 'timestamp') {
7418 $morecss = 'minwidth200imp';
7419 } elseif (in_array($type, array('int', 'double', 'price'))) {
7420 $morecss = 'maxwidth75';
7421 } elseif ($type == 'url') {
7422 $morecss = 'minwidth400';
7423 } elseif ($type == 'boolean') {
7426 if (is_numeric($size) && round($size) < 12) {
7427 $morecss = 'minwidth100';
7428 } elseif (is_numeric($size) && round($size) <= 48) {
7429 $morecss = 'minwidth200';
7431 $morecss = 'minwidth400';
7436 // Format output value differently according to properties of field
7437 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
7438 if ($key != 'rowid' || empty($this->fields['ref'])) { // If we want ref field or if we want ID and there is no ref field, we show the link.
7439 $value = $this->getNomUrl(1, '', 0, '', 1);
7441 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
7442 $value = $this->getLibStatut(3);
7443 } elseif ($type == 'date') {
7444 if (!empty($value)) {
7445 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
7449 } elseif ($type == 'datetime' || $type == 'timestamp') {
7450 if (!empty($value)) {
7451 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
7455 } elseif ($type == 'duration') {
7456 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
7457 if (!is_null($value) && $value !== '') {
7458 $value = convertSecondToTime($value, 'allhourmin');
7460 } elseif ($type == 'double' || $type == 'real') {
7461 if (!is_null($value) && $value !== '') {
7462 $value = price($value);
7464 } elseif ($type == 'boolean') {
7466 if (!empty($value)) {
7467 $checked = ' checked ';
7469 $value = '<input type="checkbox
" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
7470 } elseif ($type == 'mail' || $type == 'email') {
7471 $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
7472 } elseif ($type == 'url') {
7473 $value = dol_print_url($value, '_blank', 32, 1);
7474 } elseif ($type == 'phone') {
7475 $value = dol_print_phone($value, '', 0, 0, '', ' ', 'phone');
7476 } elseif ($type == 'price') {
7477 if (!is_null($value) && $value !== '') {
7478 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
7480 } elseif ($type == 'select') {
7481 $value = isset($param['options'][$value])?$param['options'][$value]:'';
7482 } elseif ($type == 'sellist') {
7483 $param_list = array_keys($param['options']);
7484 $InfoFieldList = explode(":
", $param_list[0]);
7486 $selectkey = "rowid
";
7489 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7490 $selectkey = $InfoFieldList[2];
7491 $keyList = $InfoFieldList[2].' as rowid';
7494 $fields_label = explode('|', $InfoFieldList[1]);
7495 if (is_array($fields_label)) {
7497 $keyList .= implode(', ', $fields_label);
7500 $sql = "SELECT
".$keyList;
7501 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7502 if (strpos($InfoFieldList[4], 'extra') !== false) {
7505 if ($selectkey == 'rowid' && empty($value)) {
7506 $sql .= " WHERE
".$selectkey." = 0
";
7507 } elseif ($selectkey == 'rowid') {
7508 $sql .= " WHERE
".$selectkey." =
".((int) $value);
7510 $sql .= " WHERE
".$selectkey." =
'".$this->db->escape($value)."'";
7513 //$sql.= ' AND entity = '.$conf->entity;
7515 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
7516 $resql = $this->db->query($sql);
7518 $value = ''; // value was used, so now we reste it to use it to build final output
7519 $numrows = $this->db->num_rows($resql);
7521 $obj = $this->db->fetch_object($resql);
7523 // Several field into label (eq table:code|libelle:rowid)
7524 $fields_label = explode('|', $InfoFieldList[1]);
7526 if (is_array($fields_label) && count($fields_label) > 1) {
7527 foreach ($fields_label as $field_toshow) {
7529 if (!empty($obj->$field_toshow)) {
7530 $translabel = $langs->trans($obj->$field_toshow);
7532 if ($translabel != $field_toshow) {
7533 $value .= dol_trunc($translabel, 18).' ';
7535 $value .= $obj->$field_toshow.' ';
7540 if (!empty($obj->{$InfoFieldList[1]})) {
7541 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7543 if ($translabel != $obj->{$InfoFieldList[1]}) {
7544 $value = dol_trunc($translabel, 18);
7546 $value = $obj->{$InfoFieldList[1]};
7551 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7553 } elseif ($type == 'radio') {
7554 $value = $param['options'][$value];
7555 } elseif ($type == 'checkbox') {
7556 $value_arr = explode(',', $value);
7558 if (is_array($value_arr) && count($value_arr) > 0) {
7560 foreach ($value_arr as $keyval => $valueval) {
7561 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">'.$param['options'][$valueval].'</li>';
7563 $value = '<div class="select2-container-multi-dolibarr
" style="width: 90%;
"><ul class="select2-choices-dolibarr
">'.implode(' ', $toprint).'</ul></div>';
7565 } elseif ($type == 'chkbxlst') {
7566 $value_arr = explode(',', $value);
7568 $param_list = array_keys($param['options']);
7569 $InfoFieldList = explode(":
", $param_list[0]);
7571 $selectkey = "rowid
";
7574 if (count($InfoFieldList) >= 3) {
7575 $selectkey = $InfoFieldList[2];
7576 $keyList = $InfoFieldList[2].' as rowid';
7579 $fields_label = explode('|', $InfoFieldList[1]);
7580 if (is_array($fields_label)) {
7582 $keyList .= implode(', ', $fields_label);
7585 $sql = "SELECT
".$keyList;
7586 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7587 if (strpos($InfoFieldList[4], 'extra') !== false) {
7590 // $sql.= " WHERE
".$selectkey."=
'".$this->db->escape($value)."'";
7591 // $sql.= ' AND entity = '.$conf->entity;
7593 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
7594 $resql = $this->db->query($sql);
7596 $value = ''; // value was used, so now we reste it to use it to build final output
7598 while ($obj = $this->db->fetch_object($resql)) {
7599 // Several field into label (eq table:code|libelle:rowid)
7600 $fields_label = explode('|', $InfoFieldList[1]);
7601 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7602 if (is_array($fields_label) && count($fields_label) > 1) {
7603 foreach ($fields_label as $field_toshow) {
7605 if (!empty($obj->$field_toshow)) {
7606 $translabel = $langs->trans($obj->$field_toshow);
7608 if ($translabel != $field_toshow) {
7609 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">'.dol_trunc($translabel, 18).'</li>';
7611 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">'.$obj->$field_toshow.'</li>';
7616 if (!empty($obj->{$InfoFieldList[1]})) {
7617 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7619 if ($translabel != $obj->{$InfoFieldList[1]}) {
7620 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">'.dol_trunc($translabel, 18).'</li>';
7622 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">'.$obj->{$InfoFieldList[1]}.'</li>';
7627 $value = '<div class="select2-container-multi-dolibarr
" style="width: 90%;
"><ul class="select2-choices-dolibarr
">'.implode(' ', $toprint).'</ul></div>';
7629 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7631 } elseif ($type == 'link') {
7634 // only if something to display (perf)
7636 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7638 $InfoFieldList = explode(":
", $param_list[0]);
7639 $classname = $InfoFieldList[0];
7640 $classpath = $InfoFieldList[1];
7641 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7642 $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
7643 if (!empty($classpath)) {
7644 dol_include_once($InfoFieldList[1]);
7645 if ($classname && class_exists($classname)) {
7646 $object = new $classname($this->db);
7647 if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
7648 $result = $object->fetch($value, '', '', '', 0, 1, 1);
7650 $result = $object->fetch($value);
7653 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7659 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7660 return 'Error bad setup of extrafield';
7665 } elseif ($type == 'password') {
7666 $value = preg_replace('/./i', '*', $value);
7667 } elseif ($type == 'array') {
7668 $value = implode('<br>', $value);
7669 } else { // text|html|varchar
7670 $value = dol_htmlentitiesbr($value);
7673 //print $type.'-'.$size.'-'.$value;
7685 public function clearFieldError($fieldKey)
7688 unset($this->validateFieldsErrors[$fieldKey]);
7698 public function setFieldError($fieldKey, $msg = '')
7701 if (empty($msg)) { $msg = $langs->trans("UnknowError
"); }
7703 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7712 public function getFieldError($fieldKey)
7714 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7715 return $this->validateFieldsErrors[$fieldKey];
7728 public function validateField($val, $fieldKey, $fieldValue)
7732 if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
7734 $this->clearFieldError($fieldKey);
7736 if (!isset($val[$fieldKey])) {
7737 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
7742 $param['options'] = array();
7743 $type = $val[$fieldKey]['type'];
7746 if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
7747 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
7758 // Convert var to be able to share same code than showOutputField of extrafields
7759 if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7760 $type = 'varchar'; // convert varchar(xx) int varchar
7762 } elseif (preg_match('/varchar/', $type)) {
7763 $type = 'varchar'; // convert varchar(xx) int varchar
7766 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7770 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7774 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7775 $param['options'] = $val['arrayofkeyval'];
7778 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7780 $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7781 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7782 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7784 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7785 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7787 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7788 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7796 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
7797 $validate = new Validate($this->db, $langs);
7800 // little trick : to perform tests with good performances sort tests by quick to low
7806 // Required test and empty value
7807 if ($required && !$validate->isNotEmptyString($fieldValue)) {
7808 $this->setFieldError($fieldKey, $validate->error);
7810 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
7811 // if no value sent and the field is not mandatory, no need to perform tests
7816 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
7817 $this->setFieldError($fieldKey, $validate->error);
7822 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
7823 $this->setFieldError($fieldKey, $validate->error);
7831 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
7832 if (!$validate->isTimestamp($fieldValue)) {
7833 $this->setFieldError($fieldKey, $validate->error);
7835 } else { return true; }
7836 } elseif ($type == 'duration') {
7837 if (!$validate->isDuration($fieldValue)) {
7838 $this->setFieldError($fieldKey, $validate->error);
7840 } else { return true; }
7841 } elseif (in_array($type, array('double', 'real', 'price'))) {
7843 if (!$validate->isNumeric($fieldValue)) {
7844 $this->setFieldError($fieldKey, $validate->error);
7846 } else { return true; }
7847 } elseif ($type == 'boolean') {
7848 if (!$validate->isBool($fieldValue)) {
7849 $this->setFieldError($fieldKey, $validate->error);
7851 } else { return true; }
7852 } elseif ($type == 'mail') {
7853 if (!$validate->isEmail($fieldValue)) {
7854 $this->setFieldError($fieldKey, $validate->error);
7857 } elseif ($type == 'url') {
7858 if (!$validate->isUrl($fieldValue)) {
7859 $this->setFieldError($fieldKey, $validate->error);
7861 } else { return true; }
7862 } elseif ($type == 'phone') {
7863 if (!$validate->isPhone($fieldValue)) {
7864 $this->setFieldError($fieldKey, $validate->error);
7866 } else { return true; }
7867 } elseif ($type == 'select' || $type == 'radio') {
7868 if (!isset($param['options'][$fieldValue])) {
7869 $this->error = $langs->trans('RequireValidValue');
7871 } else { return true; }
7872 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
7873 $param_list = array_keys($param['options']);
7874 $InfoFieldList = explode(":
", $param_list[0]);
7875 $value_arr = explode(',', $fieldValue);
7876 $value_arr = array_map(array($this->db, 'escape'), $value_arr);
7878 $selectkey = "rowid
";
7879 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7880 $selectkey = $InfoFieldList[2];
7883 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
7884 $this->setFieldError($fieldKey, $validate->error);
7886 } else { return true; }
7887 } elseif ($type == 'link') {
7888 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7889 $InfoFieldList = explode(":
", $param_list[0]);
7890 $classname = $InfoFieldList[0];
7891 $classpath = $InfoFieldList[1];
7892 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
7893 $this->setFieldError($fieldKey, $validate->error);
7895 } else { return true; }
7898 // if no test failled all is ok
7915 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
7917 global $db, $conf, $langs, $action, $form, $hookmanager;
7919 if (!is_object($form)) {
7920 $form = new Form($db);
7922 if (!is_object($extrafields)) {
7923 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
7924 return 'Bad parameter extrafields for showOptionals';
7926 if (!is_array($extrafields->attributes[$this->table_element])) {
7927 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);
", LOG_WARNING);
7932 $parameters = array();
7933 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
7934 if (empty($reshook)) {
7935 if (is_array($extrafields->attributes[$this->table_element]) && key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
7937 $out .= '<!-- commonobject:showOptionals --> ';
7940 $extrafields_collapse_num = '';
7942 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
7943 // Show only the key field in params
7944 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
7948 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
7950 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
7951 $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
7953 if (empty($enabled)) {
7958 if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
7959 $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
7963 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
7964 $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
7967 if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
7968 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
7969 } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
7970 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
7971 } elseif ($mode == 'view' && empty($visibility)) {
7974 if (empty($perms)) {
7977 // Load language if required
7978 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
7979 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
7983 if (is_array($params) && count($params) > 0 && $display_type=='card') {
7984 if (array_key_exists('cols', $params)) {
7985 $colspan = $params['cols'];
7986 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
7988 if (preg_match('/colspan="(\d+)
"/', $params['colspan'], $reg)) {
7991 $colspan = $params['colspan'];
7995 $colspan = intval($colspan);
7999 $value = ((!empty($this->array_options) && array_key_exists("options_
".$key.$keysuffix, $this->array_options)) ? $this->array_options["options_
".$key.$keysuffix] : null); // Value may be cleaned or formated later
8003 // We get the value of property found with GETPOST so it takes into account:
8004 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
8005 $check = 'alphanohtml';
8006 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
8007 $check = 'restricthtml';
8009 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
8010 // GETPOST("options_
" . $key) can be 'abc' or array(0=>'abc')
8011 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
8012 if (is_array($getposttemp)) {
8013 // $getposttemp is an array but following code expects a comma separated string
8014 $value = implode(",
", $getposttemp);
8016 $value = $getposttemp;
8019 $value = (!empty($this->array_options["options_
".$key]) ? $this->array_options["options_
".$key] : ''); // No GET, no POST, no default value, so we take value of object.
8021 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_
".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
8025 // Output value of the current field
8026 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
8027 $extrafields_collapse_num = '';
8028 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
8029 if (!empty($extrafield_param) && is_array($extrafield_param)) {
8030 $extrafield_param_list = array_keys($extrafield_param['options']);
8032 if (count($extrafield_param_list) > 0) {
8033 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
8035 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
8036 $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
8041 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
8042 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8044 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
8046 if (is_array($params) && count($params) > 0) {
8047 if (array_key_exists('class', $params)) {
8048 $class .= $params['class'].' ';
8050 if (array_key_exists('style', $params)) {
8051 $csstyle = $params['style'];
8055 // add html5 elements
8056 $domData = ' data-element="extrafield
"';
8057 $domData .= ' data-targetelement="'.$this->element.'"';
8058 $domData .= ' data-targetid="'.$this->id.'"';
8060 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
8061 if ($display_type=='card') {
8062 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8066 if ($action == 'selectlines') {
8071 // Convert date into timestamp format (value in memory must be a timestamp)
8072 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
8073 $datenotinstring = null;
8074 if (array_key_exists('options_'.$key, $this->array_options)) {
8075 $datenotinstring = $this->array_options['options_'.$key];
8076 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8077 $datenotinstring = $this->db->jdate($datenotinstring);
8080 $datekey = $keyprefix.'options_'.$key.$keysuffix;
8081 $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
8083 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
8084 $datenotinstring = null;
8085 if (array_key_exists('options_'.$key, $this->array_options)) {
8086 $datenotinstring = $this->array_options['options_'.$key];
8087 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8088 $datenotinstring = $this->db->jdate($datenotinstring);
8091 $timekey = $keyprefix.'options_'.$key.$keysuffix;
8092 $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOST($timekey.'hour', 'int', 3), GETPOST($timekey.'min', 'int', 3), GETPOST($timekey.'sec', 'int', 3), GETPOST($timekey.'month', 'int', 3), GETPOST($timekey.'day', 'int', 3), GETPOST($timekey.'year', 'int', 3), 'tzuserrel') : $datenotinstring;
8094 // Convert float submited string into real php numeric (value in memory must be a php numeric)
8095 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
8096 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
8097 $value = price2num($value);
8098 } elseif (isset($this->array_options['options_'.$key])) {
8099 $value = $this->array_options['options_'.$key];
8103 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
8104 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
8105 if ($action == 'create') {
8106 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
8110 $labeltoshow = $langs->trans($label);
8111 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
8113 if ($display_type == 'card') {
8114 $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_
'.$key.' '.$class.$this->element.'_extras_
'.$key.' trextrafields_collapse
'.$extrafields_collapse_num.(!empty($this->id)?'_
'.$this->id:'').'" '.$domData.' >';
8115 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline')) {
8116 $out .= '<td></td>';
8118 $out .= '<td class="titlefieldcreate wordbreak
';
8119 } elseif ($display_type == 'line
') {
8120 $out .= '<div
'.($html_id ? 'id=
"'.$html_id.'" ' : '').$csstyle.' class=
"fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$extrafields_collapse_num.(!empty($this->id)?'_'.$this->id:'').'" '.$domData.' >
';
8121 $out .= '<div style=
"display: inline-block; padding-right:4px" class=
"titlefieldcreate wordbreak';
8123 //$out .= "titlefield
";
8124 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
8125 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
8126 $tpl_context = isset($params["tpl_context
"]) ? $params["tpl_context
"] : "none
";
8127 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
8128 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8129 $out .= ' fieldrequired';
8133 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
8134 if (!empty($extrafields->attributes[$this->table_element]['help
'][$key])) {
8135 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8137 $out .= $labeltoshow;
8139 if ($mode != 'view
' && !empty($extrafields->attributes[$this->table_element]['required
'][$key])) {
8140 $out .= ' <span style=
"color: red">*</span>
';
8143 if (!empty($extrafields->attributes[$this->table_element]['help
'][$key])) {
8144 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8146 $out .= $labeltoshow;
8150 $out .= ($display_type == 'card
' ? '</td>
' : '</div>
');
8152 $html_id = !empty($this->id) ? $this->element.'_extras_
'.$key.'_
'.$this->id : '';
8153 if ($display_type == 'card
') {
8154 // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one
8155 $out .= '<td
'.($html_id ? 'id=
"'.$html_id.'" ' : '').' class=
"valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan=
"'.$colspan.'"' : '').'>
';
8156 } elseif ($display_type == 'line
') {
8157 $out .= '<div
'.($html_id ? 'id=
"'.$html_id.'" ' : '').' style=
"display: inline-block" class=
"valuefieldcreate '.$this->element.'_extras_'.$key.' extra_inline_'.$extrafields->attributes[$this->table_element]['type'][$key].'">
';
8162 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
8165 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8168 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8172 $out .= ($display_type=='card
' ? '</td>
' : '</div>
');
8174 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8175 $out .= ($display_type=='card
' ? '</tr>
' : '</div>
');
8177 $out .= ($display_type=='card
' ? '</tr>
' : '</div>
');
8183 // Add code to manage list depending on others
8184 if (!empty($conf->use_javascript_ajax)) {
8185 $out .= $this->getJSListDependancies();
8192 $out .= $hookmanager->resPrint;
8201 public function getJSListDependancies($type = '_extra
')
8205 jQuery(document).ready(
function() {
8206 function showOptions
'.$type.'(child_list, parent_list, orig_select)
8208 var val = $(
"select[name=\""+parent_list+
"\"]").val();
8209 var parentVal = parent_list +
":" + val;
8210 if(typeof val ==
"string"){
8212 var options = orig_select.find(
"option[parent=\""+parentVal+
"\"]").clone();
8213 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8214 $(
"select[name=\""+child_list+
"\"]").append(options);
8216 var options = orig_select.find(
"option[parent]").clone();
8217 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8218 $(
"select[name=\""+child_list+
"\"]").append(options);
8220 }
else if(val > 0) {
8221 var options = orig_select.find(
"option[parent=\""+parentVal+
"\"]").clone();
8222 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8223 $(
"select[name=\""+child_list+
"\"]").append(options);
8225 var options = orig_select.find(
"option[parent]").clone();
8226 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8227 $(
"select[name=\""+child_list+
"\"]").append(options);
8230 function setListDependencies
'.$type.'() {
8231 jQuery(
"select option[parent]").parent().each(
function() {
8232 var orig_select = {};
8233 var child_list = $(
this).attr(
"name");
8234 orig_select[child_list] = $(
this).clone();
8235 var parent = $(
this).find(
"option[parent]:first").attr(
"parent");
8236 var infos = parent.split(
":");
8237 var parent_list = infos[0];
8240 if ($(
"#"+child_list).val() == 0 && $(
"#"+parent_list).val() == 0){
8241 $(
"#"+child_list).hide();
8243 }
else if ($(
"#"+parent_list).val() != 0){
8244 $(
"#"+parent_list).show();
8247 $(
"select[name=\""+parent_list+
"\"]").click(
function() {
8248 if ($(
this).val() != 0){
8249 $(
"#"+child_list).show()
8254 $(
"select[name=\""+parent_list+
"\"]").change(
function() {
8255 showOptions
'.$type.'(child_list, parent_list, orig_select[child_list]);
8257 $(
"#"+child_list).val(0).trigger(
"change");
8259 if ($(
this).val() == 0){
8260 $(
"#"+child_list).hide();
8266 setListDependencies
'.$type.'();
8276 public function getRights()
8280 $element = $this->element;
8281 if ($element == 'facturerec
') {
8282 $element = 'facture
';
8283 } elseif ($element == 'invoice_supplier_rec
') {
8284 return $user->rights->fournisseur->facture;
8287 return $user->rights->{$element};
8302 public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8304 foreach ($tables as $table) {
8305 $sql = 'UPDATE
'.$db->prefix().$table.' SET fk_soc =
'.((int) $dest_id).' WHERE fk_soc =
'.((int) $origin_id);
8307 if (!$db->query($sql)) {
8308 if ($ignoreerrors) {
8309 return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
8311 //$this->errors = $db->lasterror();
8331 public static function commonReplaceProduct(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8333 foreach ($tables as $table) {
8334 $sql = 'UPDATE
'.MAIN_DB_PREFIX.$table.' SET fk_product =
'.((int) $dest_id).' WHERE fk_product =
'.((int) $origin_id);
8336 if (!$db->query($sql)) {
8337 if ($ignoreerrors) {
8338 return true; // TODO Not enough. If there is A-B on kept product and B-C on old one, we must get A-B-C after merge. Not A-B.
8340 //$this->errors = $db->lasterror();
8360 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8366 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8367 // When ForceBuyingPriceIfNull is set
8368 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8370 // Get cost price for margin calculation
8371 if (!empty($fk_product) && $fk_product > 0) {
8372 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice
') {
8373 require_once DOL_DOCUMENT_ROOT.'/product/
class/product.class.php
';
8374 $product = new Product($this->db);
8375 $result = $product->fetch($fk_product);
8377 $this->errors[] = 'ErrorProductIdDoesNotExists
';
8380 if ($product->cost_price > 0) {
8381 $buyPrice = $product->cost_price;
8382 } elseif ($product->pmp > 0) {
8383 $buyPrice = $product->pmp;
8385 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp
') {
8386 require_once DOL_DOCUMENT_ROOT.'/product/
class/product.class.php
';
8387 $product = new Product($this->db);
8388 $result = $product->fetch($fk_product);
8390 $this->errors[] = 'ErrorProductIdDoesNotExists
';
8393 if ($product->pmp > 0) {
8394 $buyPrice = $product->pmp;
8398 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1
', 'pmp
', 'costprice
'))) {
8399 require_once DOL_DOCUMENT_ROOT.'/fourn/
class/fournisseur.product.class.php
';
8400 $productFournisseur = new ProductFournisseur($this->db);
8401 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8402 $buyPrice = $productFournisseur->fourn_unitprice;
8403 } elseif ($result < 0) {
8404 $this->errors[] = $productFournisseur->error;
8413 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8431 public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0)
8434 global $conf, $user, $langs;
8436 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php
';
8437 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php
';
8439 $sortfield = 'position_name
';
8445 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8446 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8448 // For backward compatibility
8449 if ($modulepart == 'product
') {
8450 if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
8451 $dir = $sdir.'/
'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8452 $pdir = '/
'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8456 // Defined relative dir to DOL_DATA_ROOT
8459 $relativedir = preg_replace('/^
'.preg_quote(DOL_DATA_ROOT, '/
').'/
', '', $dir);
8460 $relativedir = preg_replace('/^[\\/]/
', '', $relativedir);
8461 $relativedir = preg_replace('/[\\/]$/
', '', $relativedir);
8464 $dirthumb = $dir.'thumbs/
';
8465 $pdirthumb = $pdir.'thumbs/
';
8467 $return = '<!-- Photo -->
'."\n";
8470 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$
', $sortfield, (strtolower($sortorder) == 'desc
' ?SORT_DESC:SORT_ASC), 1);
8472 /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs
8474 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$
',$sortfield,(strtolower($sortorder)=='desc
'?SORT_DESC:SORT_ASC),1);
8475 $filearray=array_merge($filearray, $filearrayold);
8478 completeFileArrayWithDatabaseInfo($filearray, $relativedir);
8480 if (count($filearray)) {
8481 if ($sortfield && $sortorder) {
8482 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
8485 foreach ($filearray as $key => $val) {
8487 $file = $val['name'];
8489 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
8490 if (image_format_supported($file) >= 0) {
8493 $viewfilename = $file;
8495 if ($size == 1 || $size == 'small
') { // Format vignette
8496 // Find name of thumb file
8497 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small
'));
8498 if (!dol_is_file($dirthumb.$photo_vignette)) {
8499 $photo_vignette = '';
8502 // Get filesize of original file
8503 $imgarray = dol_getImageSize($dir.$photo);
8506 if ($nbphoto == 1) {
8507 $return .= '<table
class=
"valigntop center centpercent" style=
"border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">
';
8510 if ($nbphoto % $nbbyrow == 1) {
8511 $return .= '<tr
class=
"center valignmiddle" style=
"border: 1px">
';
8513 $return .= '<td style=
"width: '.ceil(100 / $nbbyrow).'%" class=
"photo">
';
8514 } elseif ($nbbyrow < 0) {
8515 $return .= '<div
class=
"inline-block">
';
8520 $relativefile = preg_replace('/^\
8521 if (empty($nolink)) {
8524 $return .=
'<a href="'.$urladvanced.
'">';
8526 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8532 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8533 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8538 $addphotorefcss = 1;
8540 if ($usesharelink) {
8541 if ($val[
'share']) {
8542 if (empty($maxHeight) || $photo_vignette && $imgarray[
'height'] > $maxHeight) {
8543 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8544 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?hashp='.urlencode($val[
'share']).
'" title="'.
dol_escape_htmltag($alt).
'">';
8546 $return .=
'<!-- Show original file -->';
8547 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?hashp='.urlencode($val[
'share']).
'" title="'.
dol_escape_htmltag($alt).
'">';
8550 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8551 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8554 if (empty($maxHeight) || $photo_vignette && $imgarray[
'height'] > $maxHeight) {
8555 $return .=
'<!-- Show thumb -->';
8556 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
' maxwidth150onsmartphone maxwidth200" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdirthumb.$photo_vignette).
'" title="'.
dol_escape_htmltag($alt).
'">';
8558 $return .=
'<!-- Show original file -->';
8559 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" title="'.
dol_escape_htmltag($alt).
'">';
8563 if (empty($nolink)) {
8568 if ($showfilename) {
8569 $return .=
'<br>'.$viewfilename;
8574 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8575 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8578 if ($modulepart ==
'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8580 $return .=
'<a href="'.DOL_URL_ROOT.
'/core/photos_resize.php?modulepart='.urlencode(
'produit|service').
'&id='.$this->
id.
'&file='.urlencode($pdir.$viewfilename).
'" title="'.
dol_escape_htmltag($langs->trans(
"Resize")).
'">'.
img_picto($langs->trans(
"Resize"),
'resize',
'').
'</a> ';
8583 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8591 if (($nbphoto % $nbbyrow) == 0) {
8594 } elseif ($nbbyrow < 0) {
8595 $return .=
'</div>';
8600 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8602 if ($showfilename) {
8603 $return .=
'<br>'.$viewfilename;
8607 if ($modulepart ==
'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8609 $return .=
'<a href="'.DOL_URL_ROOT.
'/core/photos_resize.php?modulepart='.urlencode(
'produit|service').
'&id='.$this->
id.
'&file='.urlencode($pdir.$viewfilename).
'" title="'.
dol_escape_htmltag($langs->trans(
"Resize")).
'">'.
img_picto($langs->trans(
"Resize"),
'resize',
'').
'</a> ';
8612 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8619 if ($nbmax && $nbphoto >= $nbmax) {
8625 if ($size == 1 || $size ==
'small') {
8628 while ($nbphoto % $nbbyrow) {
8629 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8634 $return .=
'</table>';
8640 $this->nbphoto = $nbphoto;
8654 if (is_array($info)) {
8655 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8672 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8686 if (is_array($info)) {
8687 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8705 if (is_array($info)) {
8706 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
8724 if (is_array($info)) {
8725 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
8742 if (is_array($info)) {
8743 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
8760 if (is_array($info)) {
8761 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
8778 if (is_array($info)) {
8779 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
8796 if (is_array($info)) {
8797 if (isset($info[
'index']) && $info[
'index'] ==
true) {
8818 $queryarray = array();
8819 foreach ($this->fields as $field => $info) {
8821 if ($this->isDate($info)) {
8822 if (empty($this->{$field})) {
8823 $queryarray[$field] = null;
8825 $queryarray[$field] = $this->
db->idate($this->{$field});
8827 } elseif ($this->isDuration($info)) {
8829 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
8830 if (!isset($this->{$field})) {
8831 $queryarray[$field] = 0;
8833 $queryarray[$field] = (int) $this->{$field};
8836 $queryarray[$field] = null;
8838 } elseif ($this->isInt($info) || $this->isFloat($info)) {
8839 if ($field ==
'entity' && is_null($this->{$field})) {
8840 $queryarray[$field] = $conf->entity;
8843 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
8844 if (!isset($this->{$field})) {
8845 $queryarray[$field] = 0;
8846 } elseif ($this->isInt($info)) {
8847 $queryarray[$field] = (int) $this->{$field};
8848 } elseif ($this->isFloat($info)) {
8849 $queryarray[$field] = (double) $this->{$field};
8852 $queryarray[$field] = null;
8858 $queryarray[$field] = $this->{$field};
8861 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
8862 unset($queryarray[$field]);
8864 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
8865 $queryarray[$field] = null;
8882 foreach ($this->fields as $field => $info) {
8883 if ($this->isDate($info)) {
8884 if (is_null($obj->{$field}) || $obj->{$field} ===
'' || $obj->{$field} ===
'0000-00-00 00:00:00' || $obj->{$field} ===
'1000-01-01 00:00:00') {
8885 $this->{$field} =
'';
8887 $this->{$field} = $db->jdate($obj->{$field});
8889 } elseif ($this->isInt($info)) {
8890 if ($field ==
'rowid') {
8891 $this->
id = (int) $obj->{$field};
8893 if ($this->isForcedToNullIfZero($info)) {
8894 if (empty($obj->{$field})) {
8895 $this->{$field} = null;
8897 $this->{$field} = (double) $obj->{$field};
8900 if (!is_null($obj->{$field}) || (isset($info[
'notnull']) && $info[
'notnull'] == 1)) {
8901 $this->{$field} = (int) $obj->{$field};
8903 $this->{$field} = null;
8907 } elseif ($this->isFloat($info)) {
8908 if ($this->isForcedToNullIfZero($info)) {
8909 if (empty($obj->{$field})) {
8910 $this->{$field} = null;
8912 $this->{$field} = (double) $obj->{$field};
8915 if (!is_null($obj->{$field}) || (isset($info[
'notnull']) && $info[
'notnull'] == 1)) {
8916 $this->{$field} = (double) $obj->{$field};
8918 $this->{$field} = null;
8922 $this->{$field} = isset($obj->{$field}) ? $obj->{$field} : null;
8927 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
8928 $this->
ref = $this->id;
8940 $keys = array_keys($this->fields);
8941 if (!empty($alias)) {
8942 $keys_with_alias = array();
8943 foreach ($keys as $fieldname) {
8944 $keys_with_alias[] = $alias .
'.' . $fieldname;
8946 return implode(
',', $keys_with_alias);
8948 return implode(
',', $keys);
8959 protected function quote($value, $fieldsentry)
8961 if (is_null($value)) {
8963 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
8965 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
8966 return (
int) $value;
8967 } elseif ($fieldsentry[
'type'] ==
'boolean') {
8974 return "'".$this->db->escape($value).
"'";
8989 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
8995 $fieldvalues = $this->setSaveQuery();
8997 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
8998 $fieldvalues[
'date_creation'] = $this->
db->idate($now);
9000 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9001 $fieldvalues[
'fk_user_creat'] = $user->id;
9003 unset($fieldvalues[
'rowid']);
9004 if (array_key_exists(
'ref', $fieldvalues)) {
9010 foreach ($fieldvalues as $k => $v) {
9012 $value = $this->fields[$k];
9013 $values[$k] = $this->quote($v, $value);
9017 foreach ($keys as $key) {
9019 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9022 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9026 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9028 $langs->load(
"errors");
9029 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9030 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9034 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9035 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9039 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9040 if (isset($this->fields[$key][
'default'])) {
9041 $values[$key] = ((int) $this->fields[$key][
'default']);
9043 $values[$key] =
'null';
9046 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9047 $values[$key] =
'null';
9058 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9059 $sql .=
" (".implode(
", ", $keys).
')';
9060 $sql .=
" VALUES (".implode(
", ", $values).
")";
9062 $res = $this->
db->query($sql);
9065 if ($this->
db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9066 $this->errors[] =
"ErrorRefAlreadyExists";
9068 $this->errors[] = $this->
db->lasterror();
9074 $this->
id = $this->
db->last_insert_id($this->
db->prefix().$this->table_element);
9079 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9080 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9081 $resqlupdate = $this->
db->query($sql);
9083 if ($resqlupdate ===
false) {
9085 $this->errors[] = $this->
db->lasterror();
9087 $this->
ref =
'(PROV'.$this->id.
')';
9094 $result = $this->insertExtraFields();
9101 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9102 $num = (is_array($this->lines) ? count($this->lines) : 0);
9103 for ($i = 0; $i < $num; $i++) {
9104 $line = $this->lines[$i];
9106 $keyforparent = $this->fk_element;
9107 $line->$keyforparent = $this->id;
9111 if (!is_object($line)) {
9112 $line = (object) $line;
9115 $result = $line->create($user, 1);
9117 $this->error = $line->error;
9118 $this->
db->rollback();
9125 if (!$error && !$notrigger) {
9127 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9136 $this->
db->rollback();
9139 $this->
db->commit();
9155 if (empty($id) && empty($ref) && empty($morewhere)) {
9159 $fieldlist = $this->getFieldList(
't');
9160 if (empty($fieldlist)) {
9164 $sql =
"SELECT ".$fieldlist;
9165 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9168 $sql .=
' WHERE t.rowid = '.((int) $id);
9169 } elseif (!empty($ref)) {
9170 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9172 $sql .=
' WHERE 1 = 1';
9174 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9175 $sql .=
' AND t.entity IN ('.getEntity($this->table_element).
')';
9182 $res = $this->
db->query($sql);
9184 $obj = $this->
db->fetch_object($res);
9186 $this->setVarsFromFetchObj($obj);
9190 $this->fetch_optionals();
9197 $this->error = $this->
db->lasterror();
9198 $this->errors[] = $this->error;
9211 $objectlineclassname = get_class($this).
'Line';
9212 if (!class_exists($objectlineclassname)) {
9213 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9217 $objectline =
new $objectlineclassname($this->
db);
9219 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9220 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9221 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9225 if (isset($objectline->fields[
'position'])) {
9226 $sql .= $this->
db->order(
'position',
'ASC');
9231 $num_rows = $this->
db->num_rows(
$resql);
9233 while ($i < $num_rows) {
9234 $obj = $this->
db->fetch_object(
$resql);
9236 $newline =
new $objectlineclassname($this->
db);
9237 $newline->setVarsFromFetchObj($obj);
9239 $this->lines[] = $newline;
9246 $this->error = $this->
db->lasterror();
9247 $this->errors[] = $this->error;
9261 global $conf, $langs;
9262 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9268 $fieldvalues = $this->setSaveQuery();
9270 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9271 $fieldvalues[
'date_modification'] = $this->
db->idate($now);
9273 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9274 $fieldvalues[
'fk_user_modif'] = $user->id;
9276 unset($fieldvalues[
'rowid']);
9277 if (array_key_exists(
'ref', $fieldvalues)) {
9285 foreach ($fieldvalues as $k => $v) {
9287 $value = $this->fields[$k];
9288 $values[$k] = $this->quote($v, $value);
9289 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9293 foreach ($keys as $key) {
9294 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9297 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9310 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9314 $res = $this->
db->query($sql);
9317 $this->errors[] = $this->
db->lasterror();
9323 $result = $this->insertExtraFields();
9330 if (!$error && !$notrigger) {
9332 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9341 $this->
db->rollback();
9344 $this->
db->commit();
9359 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9365 if ($forcechilddeletion) {
9366 foreach ($this->childtables as $table) {
9367 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9370 $this->error = $this->
db->lasterror();
9371 $this->errors[] = $this->error;
9372 $this->
db->rollback();
9376 } elseif (!empty($this->fk_element) && !empty($this->childtables)) {
9377 $objectisused = $this->isObjectUsed($this->
id);
9378 if (!empty($objectisused)) {
9379 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9380 $this->error =
'ErrorRecordHasChildren';
9381 $this->errors[] = $this->error;
9382 $this->
db->rollback();
9388 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9389 foreach ($this->childtablesoncascade as $table) {
9390 $deleteFromObject = explode(
':', $table);
9391 if (count($deleteFromObject) >= 2) {
9392 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9393 $filePath = $deleteFromObject[1];
9394 $columnName = $deleteFromObject[2];
9395 $TMoreSQL = array();
9396 $more_sql = $deleteFromObject[3];
9397 if (!empty($more_sql)) {
9398 $TMoreSQL[
'customsql'] = $more_sql;
9401 $childObject =
new $className($this->
db);
9402 if (method_exists($childObject,
'deleteByParentField')) {
9403 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9406 $this->errors[] = $childObject->error;
9411 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9416 $this->errors[] =
'Cannot include child class file '.$filePath;
9421 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9426 $this->error = $this->
db->lasterror();
9427 $this->errors[] = $this->error;
9437 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9447 $res = $this->deleteEcmFiles(1);
9453 if (!$error && !empty($this->isextrafieldmanaged)) {
9454 $result = $this->deleteExtraFields();
9461 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9466 $this->errors[] = $this->
db->lasterror();
9472 $this->
db->rollback();
9475 $this->
db->commit();
9497 if (!empty($parentId) && !empty($parentField)) {
9500 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9501 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9504 $sqlwhere = array();
9505 if (count($filter) > 0) {
9506 foreach ($filter as $key => $value) {
9507 if ($key ==
'customsql') {
9508 $sqlwhere[] = $value;
9509 } elseif (strpos($value,
'%') ===
false) {
9510 $sqlwhere[] = $key.
" IN (".$this->
db->sanitize($this->
db->escape($value)).
")";
9512 $sqlwhere[] = $key.
" LIKE '%".$this->
db->escape($value).
"%'";
9516 if (count($sqlwhere) > 0) {
9517 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9522 $this->errors[] = $this->
db->lasterror();
9525 while ($obj = $this->
db->fetch_object(
$resql)) {
9526 $result = $this->fetch($obj->rowid);
9529 $this->errors[] = $this->error;
9531 if (get_class($this) ==
'Contact') {
9532 $result = $this->
delete();
9534 $result = $this->
delete($user);
9538 $this->errors[] = $this->error;
9546 if (empty($error)) {
9547 $this->
db->commit();
9550 $this->error = implode(
', ', $this->errors);
9551 $this->
db->rollback();
9573 $tmpforobjectclass = get_class($this);
9574 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9577 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9585 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9586 $sql .=
" WHERE rowid = ".((int) $idline);
9588 dol_syslog(get_class($this).
"::deleteLineCommon", LOG_DEBUG);
9591 $this->error =
"Error ".$this->db->lasterror();
9595 if (empty($error)) {
9597 $tmpobjectline =
new $tmpforobjectlineclass($this->
db);
9598 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9599 $tmpobjectline->id = $idline;
9600 $result = $tmpobjectline->deleteExtraFields();
9603 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9608 if (empty($error)) {
9609 $this->
db->commit();
9612 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9613 $this->
db->rollback();
9634 $statusfield =
'status';
9635 if ($this->element ==
'don' || $this->element ==
'donation') {
9636 $statusfield =
'fk_statut';
9639 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9640 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9641 $sql .=
" WHERE rowid = ".((int) $this->
id);
9643 if ($this->
db->query($sql)) {
9645 $this->oldcopy = clone $this;
9648 if (!$error && !$notrigger) {
9650 $result = $this->call_trigger($triggercode, $user);
9657 $this->status = $status;
9658 $this->
db->commit();
9661 $this->
db->rollback();
9665 $this->error = $this->
db->error();
9666 $this->
db->rollback();
9683 $this->specimen = 1;
9685 'label' =>
'This is label',
9686 'ref' =>
'ABCD1234',
9687 'description' =>
'This is a description',
9689 'note_public' =>
'Public note',
9690 'note_private' =>
'Private note',
9691 'date_creation' => (
dol_now() - 3600 * 48),
9692 'date_modification' => (
dol_now() - 3600 * 24),
9693 'fk_user_creat' => $user->id,
9694 'fk_user_modif' => $user->id,
9697 foreach ($fields as $key => $value) {
9698 if (array_key_exists($key, $this->fields)) {
9699 $this->{$key} = $value;
9714 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
9717 $result = $comment->fetchAllFor($this->element, $this->
id);
9719 $this->errors = array_merge($this->errors, $comment->errors);
9722 $this->comments = $comment->comments;
9724 return count($this->comments);
9734 return count($this->comments);
9745 if (!is_array($parameters)) {
9748 foreach ($parameters as $parameter) {
9749 if (isset($this->$parameter)) {
9750 $this->$parameter = trim($this->$parameter);
9769 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
9773 $existing = $c->containing($this->
id, $type_categ,
'id');
9793 if (!is_array($categories)) {
9794 $categories = array($categories);
9797 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
9799 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
9801 if (empty($type_categ)) {
9802 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
9808 $existing = $c->containing($this->
id, $type_categ,
'id');
9809 if ($remove_existing) {
9811 if (is_array($existing)) {
9812 $to_del = array_diff($existing, $categories);
9813 $to_add = array_diff($categories, $existing);
9816 $to_add = $categories;
9820 $to_add = array_diff($categories, $existing);
9827 foreach ($to_del as $del) {
9828 if ($c->fetch($del) > 0) {
9829 $result=$c->del_type($this, $type_categ);
9832 $this->error = $c->error;
9833 $this->errors = $c->errors;
9840 foreach ($to_add as $add) {
9841 if ($c->fetch($add) > 0) {
9842 $result = $c->add_type($this, $type_categ);
9845 $this->error = $c->error;
9846 $this->errors = $c->errors;
9854 return $error ? -1 * $error : $ok;
9870 $type = $this->table_element;
9873 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
9876 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
9877 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
9878 $sql .=
" WHERE fk_product = ".((int) $fromId);
9880 if (!$this->
db->query($sql)) {
9881 $this->error = $this->
db->lasterror();
9882 $this->
db->rollback();
9886 $this->
db->commit();
9904 switch ($this->element) {
9906 $element =
'propale';
9909 $element =
'produit';
9911 case 'order_supplier':
9912 $element =
'fournisseur/commande';
9914 case 'invoice_supplier':
9915 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
9918 $element =
'expedition/sending';
9921 $element = $this->element;
9925 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
9926 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->
db->escape($this->
ref).
"%'";
9927 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->
db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
9930 if (!$this->
db->query($sql)) {
9931 $this->error = $this->
db->lasterror();
9932 $this->
db->rollback();
9937 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
9938 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
9939 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->
db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
9941 if (!$this->
db->query($sql)) {
9942 $this->error = $this->
db->lasterror();
9943 $this->
db->rollback();
9950 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
9951 $sql .=
" WHERE fk_object IN (SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE src_object_type = '".$this->
db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id).
")";
9954 $this->error = $this->
db->lasterror();
9955 $this->
db->rollback();
9959 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
9960 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
9963 $this->error = $this->
db->lasterror();
9964 $this->
db->rollback();
9969 $this->
db->commit();
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
setProject($projectid, $notrigger=0)
Link element with a project.
getCategoriesCommon($type_categ)
Sets object to given categories.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
setExtraParameters()
Set extra parameters.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode= '')
Return full address of contact.
getKanbanView($option= '')
Return clicable link of object (with eventually picto)
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
if($cancel &&!$id) if($action== 'add'&&!$cancel) if($action== 'delete') if($id) $form
Actions.
static isExistingObject($element, $id, $ref= '', $ref_ext= '')
Check an object id/ref exists If you don't need/want to instantiate object and just need to know if o...
isFloat($info)
Function test if type is float.
isInt($info)
Function test if type is integer.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir= '/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline.class.php) If lines are into a template, title must also be into a template But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs= '', $mode=0, $extralangcode= '')
Return a formated address (part address/zip/town/state) according to country rules.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
fetchLinesCommon($morewhere= '')
Load object in memory from the database.
isText($info)
Function test if type is text.
$conf db
API class for accounts.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
setCategoriesCommon($categories, $type_categ= '', $remove_existing=true)
Sets object to given categories.
cloneCategories($fromId, $toId, $type= '')
Copy related categories to another object.
dol_now($mode= 'auto')
Return date for now.
line_order($renum=false, $rowidorder= 'ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $rowid= '', $f_user=null, $notrigger=0)
Delete all links between an object $this.
delete_linked_contact($source= '', $code= '')
Delete all links between an object $this and all its contacts.
Class to manage Dolibarr users.
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
add_contact($fk_socpeople, $type_contact, $source= 'external', $notrigger=0)
Add a link between element $this->element and a contact.
swapContactStatus($rowid)
Update status of a contact linked to object.
updateObjectLinked($sourceid=null, $sourcetype= '', $targetid=null, $targettype= '', $f_user=null, $notrigger=0)
Update object linked of a current object.
isDate($info)
Function test if type is date.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
deleteByParentField($parentId=0, $parentField= '', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
quote($value, $fieldsentry)
Add quote to field value if necessary.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
createCommon(User $user, $notrigger=false)
Create object into database.
dol_string_nospecial($str, $newstr= '_', $badcharstoreplace= '', $badcharstoremove= '')
Clean a string from all punctuation characters to use it as a ref or login.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
isArray($info)
Function test if type is array.
$conf db name
Only used if Module[ID]Name translation string is not found.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
canBeNull($info)
Function test if field can be null.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this. ...
getRangOfLine($rowid)
Get position of line (rang)
fetchComments()
Load comments linked with current task.
Class to manage categories.
update_note($note, $suffix= '')
Update note of element.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
print *****$script_file(".$version.") pid code
! Closing after partial payment: discount_vat, badcustomer or badsupplier, bankcharge, other ! Closing when no payment: replaced, abandoned
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
getFieldList($alias= '')
Function to concat keys of fields.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is '...
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
deleteEcmFiles($mode=0)
Delete related files of object in database.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
getBannerAddress($htmlkey, $object)
Return full address for banner.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
getChildrenOfLine($id, $includealltree=0)
Get children of line.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
setWarehouse($warehouse_id)
Change the warehouse.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
deleteExtraFields()
Delete all extra fields values for the current object.
updateCommon(User $user, $notrigger=false)
Update object into database.
getState($id, $withcode= '', $dbtouse=0, $withregion=0, $outputlangs= '', $entconv=1)
Return state translated from an id.
setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
Change the shipping method.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
setDocModel($user, $modelpdf)
Set last model used by doc generator.
dol_ucwords($string, $encoding="UTF-8")
Convert first character of all the words of a string to upper.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add objects linked in llx_element_element.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
setStatusCommon($user, $status, $notrigger=0, $triggercode= '')
Set to a status.
dol_trunc($string, $size=40, $trunc= 'right', $stringencoding= 'UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length. ...
liste_contact($status=-1, $source= 'external', $list=0, $code= '')
Get array of all contacts for an object.
update_ref_ext($ref_ext)
Update external ref of element.
getNbComments()
Return nb comments already posted.
isIndex($info)
Function test if is indexed.
errorsToString()
Method to output saved errors.
update_price($exclspec=0, $roundingadjust= 'none', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines)...
img_delete($titlealt= 'default', $other= 'class="pictodelete"', $morecss= '')
Show delete logo.
setStatut($status, $elementId=null, $elementType= '', $trigkey= '', $fieldstatus= 'fk_statut')
Set status of an object.
setSaveQuery()
Function to prepare a part of the query for insert.
isDuration($info)
Function test if type is duration.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param= '')
Return URL we can use for advanced preview links.
showOptionals($extrafields, $mode= 'view', $params=null, $keysuffix= '', $keyprefix= '', $onetrtd=0, $display_type= 'card')
Function to show lines of extrafields with output datas.
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
getCountry($searchkey, $withcode= '', $dbtouse=0, $outputlangs= '', $entconv=1, $searchlabel= '')
Return country label, code or id from an id, code or label.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
fetchCommon($id, $ref=null, $morewhere= '')
Load object in memory from the database.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
trimParameters($parameters)
Trim object parameters.
insertExtraLanguages($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid