46 const TRIGGER_PREFIX =
'';
76 public $errors = array();
81 private $validateFieldsErrors = array();
92 public $element_for_permission;
97 public $table_element;
102 public $table_element_line =
'';
112 public $array_options = array();
117 public $array_languages =
null;
122 public $contacts_ids;
127 public $linked_objects;
132 public $linkedObjectsIds;
137 public $linkedObjects;
142 private $linkedObjectsFullLoaded = array();
152 protected $table_ref_field =
'';
157 public $restrictiononfksoc = 0;
165 public $context = array();
245 public $ref_previous;
286 public $country_code;
329 public $barcode_type;
335 public $barcode_type_code;
341 public $barcode_type_label;
347 public $barcode_type_coder;
353 public $mode_reglement_id;
359 public $cond_reglement_id;
364 public $demand_reason_id;
370 public $transport_mode_id;
377 public $cond_reglement;
384 public $fk_delivery_address;
390 public $shipping_method_id;
409 public $last_main_doc;
439 public $note_private;
463 public $total_localtax1;
469 public $total_localtax2;
486 public $comments = array();
512 public $date_creation;
517 public $date_validation;
522 public $date_modification;
527 public $date_cloture;
538 public $user_creation;
542 public $user_creation_id;
553 public $user_validation;
557 public $user_validation_id;
561 public $user_closing_id;
567 public $user_modification;
571 public $user_modification_id;
574 public $next_prev_filter;
579 public $specimen = 0;
592 protected $labelStatus;
593 protected $labelStatusShort;
599 protected $childtables = array();
606 protected $childtablesoncascade = array();
626 $sql =
"SELECT rowid, ref, ref_ext";
627 $sql .=
" FROM ".$db->prefix().$element;
628 $sql .=
" WHERE entity IN (".getEntity($element).
")";
631 $sql .=
" AND rowid = ".((int) $id);
633 $sql .=
" AND ref = '".$db->escape($ref).
"'";
634 } elseif ($ref_ext) {
635 $sql .=
" AND ref_ext = '".$db->escape($ref_ext).
"'";
637 $error =
'ErrorWrongParameters';
641 if ($ref || $ref_ext) {
642 $sql .=
" AND entity = ".((int) $conf->entity);
645 dol_syslog(get_class().
"::isExistingObject", LOG_DEBUG);
646 $resql = $db->query($sql);
648 $num = $db->num_rows(
$resql);
666 return $this->error.(is_array($this->errors) ? (($this->error !=
'' ?
', ' :
'').join(
', ', $this->errors)) :
'');
680 $parameters = array(
'objref'=>$objref);
682 $reshook = $hookmanager->executeHooks(
'getFormatedCustomerRef', $parameters, $this, $action);
684 return $hookmanager->resArray[
'objref'];
686 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
699 $parameters = array(
'objref'=>$objref);
701 $reshook = $hookmanager->executeHooks(
'getFormatedSupplierRef', $parameters, $this, $action);
703 return $hookmanager->resArray[
'objref'];
705 return $objref.(isset($hookmanager->resArray[
'objref']) ? $hookmanager->resArray[
'objref'] :
'');
717 public function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
720 $lastname = $this->lastname;
721 $firstname = $this->firstname;
722 if (empty($lastname)) {
723 $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->
name) ? $this->
name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company :
'')))));
727 if (!empty($option) && !empty($this->civility_code)) {
728 if ($langs->transnoentitiesnoconv(
"Civility".$this->civility_code) !=
"Civility".$this->civility_code) {
729 $ret .= $langs->transnoentitiesnoconv(
"Civility".$this->civility_code).
' ';
731 $ret .= $this->civility_code.
' ';
749 if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
755 if (!empty($conf->global->MAIN_ALL_TO_UPPER)) {
760 if (!empty($conf->global->MAIN_ALL_TOWN_TO_UPPER)) {
764 if (isset($this->email)) {
767 if (isset($this->personal_email)) {
780 $return =
'<div class="box-flex-item box-flex-grow-zero">';
781 $return .=
'<div class="info-box info-box-sm">';
782 $return .=
'<span class="info-box-icon bg-infobox-action">';
784 $return .=
'</span>';
785 $return .=
'<div class="info-box-content">';
786 $return .=
'<span class="info-box-ref">'.(method_exists($this,
'getNomUrl') ? $this->getNomUrl() : $this->ref).
'</span>';
787 if (property_exists($this,
'label')) {
788 $return .=
'<br><span class="info-box-label opacitymedium">'.$this->label.
'</span>';
790 if (method_exists($this,
'getLibStatut')) {
791 $return .=
'<br><div class="info-box-status margintoponly">'.$this->getLibStatut(5).
'</div>';
809 public function getFullAddress($withcountry = 0, $sep =
"\n", $withregion = 0, $extralangcode =
'')
811 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
812 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
813 $tmparray =
getCountry($this->country_id,
'all');
814 $this->country_code = $tmparray[
'code'];
815 $this->country = $tmparray[
'label'];
818 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
819 require_once DOL_DOCUMENT_ROOT.
'/core/lib/company.lib.php';
820 $tmparray =
getState($this->state_id,
'all', 0, 1);
821 $this->state_code = $tmparray[
'code'];
822 $this->state = $tmparray[
'label'];
823 $this->region_code = $tmparray[
'region_code'];
824 $this->region = $tmparray[
'region'];
840 global $conf, $langs,
$form, $extralanguages;
842 $countriesusingstate = array(
'AU',
'US',
'IN',
'GB',
'ES',
'UK',
'TR');
846 $elementforaltlanguage = $this->element;
847 if ($this->element ==
'societe') {
848 $thirdpartyid = $this->id;
850 if ($this->element ==
'contact') {
851 $contactid = $this->id;
852 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
854 if ($this->element ==
'user') {
855 $contactid = $this->contact_id;
856 $thirdpartyid = empty($object->fk_soc) ? 0 : $object->fk_soc;
862 $coords = $this->
getFullAddress(1,
', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0));
864 if (!empty($conf->use_javascript_ajax)) {
867 if ($this->element ==
'contact' && !empty($conf->global->MAIN_SHOW_COMPANY_NAME_IN_BANNER_ADDRESS)) {
868 $namecoords .= $object->name.
'<br>';
870 $namecoords .= $this->
getFullName($langs, 1).
'<br>'.$coords;
872 $out .=
'<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).
'\',\
''.dol_escape_js($langs->trans(
"HelpCopyToClipboard")).
'\');
">';
873 $out .= img_picto($langs->trans("Address
"), 'map-marker-alt');
876 $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
880 // List of extra languages
881 $arrayoflangcode = array();
882 if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
883 $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
886 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
887 if (!is_object($extralanguages)) {
888 include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
889 $extralanguages = new ExtraLanguages($this->db);
891 $extralanguages->fetch_name_extralanguages($elementforaltlanguage);
893 if (!empty($extralanguages->attributes[$elementforaltlanguage]['address']) || !empty($extralanguages->attributes[$elementforaltlanguage]['town'])) {
894 $out .= "<!-- alternatelanguage
for '".$elementforaltlanguage."' set to fields
'".join(',
', $extralanguages->attributes[$elementforaltlanguage])."' -->\n
";
895 $this->fetchValuesForExtraLanguages();
896 if (!is_object($form)) {
897 $form = new Form($this->db);
900 // If there is extra languages
901 foreach ($arrayoflangcode as $extralangcode) {
902 $s = picto_from_langcode($extralangcode, 'class="pictoforlang paddingright
"');
903 $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT, $extralangcode);
904 $htmltext .= $s.dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', ');
906 $out .= $form->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
911 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
912 && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
913 if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
914 $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
916 $out .= ($outdone ? ' - ' : '').$this->state;
921 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)) {
922 $out .= ($outdone ? '<br>' : '');
924 if (!empty($this->phone) && empty($this->phone_pro)) { // For objects that store pro phone into ->phone
925 $out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
928 if (!empty($this->phone_pro)) {
929 $out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
932 if (!empty($this->phone_mobile)) {
933 $out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
936 if (!empty($this->phone_perso)) {
937 $out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePerso
"));
940 if (!empty($this->office_phone)) {
941 $out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'phone', $langs->trans("PhonePro
"));
944 if (!empty($this->user_mobile)) {
945 $out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', ' ', 'mobile', $langs->trans("PhoneMobile
"));
948 if (!empty($this->fax)) {
949 $out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
952 if (!empty($this->office_fax)) {
953 $out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', ' ', 'fax', $langs->trans("Fax
"));
958 $out .= '<div style="clear: both;
"></div>';
961 if (!empty($this->email)) {
962 $out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
965 if (!empty($this->url)) {
966 //$out.=dol_print_url($this->url,'_goout',0,1);//steve changed to blank
967 $out .= dol_print_url($this->url, '_blank', 0, 1);
971 if (isModEnabled('socialnetworks')) {
972 $outsocialnetwork = '';
974 if (!empty($this->socialnetworks) && is_array($this->socialnetworks) && count($this->socialnetworks) > 0) {
975 $socialnetworksdict = getArrayOfSocialNetworks();
976 foreach ($this->socialnetworks as $key => $value) {
978 $outsocialnetwork .= dol_print_socialnetworks($value, $this->id, $object->id, $key, $socialnetworksdict);
982 } else { // Old code to remove
983 if (!empty($this->skype)) {
984 $outsocialnetwork .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
987 if (!empty($this->jabberid)) {
988 $outsocialnetwork .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
991 if (!empty($this->twitter)) {
992 $outsocialnetwork .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
995 if (!empty($this->facebook)) {
996 $outsocialnetwork .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
999 if (!empty($this->linkedin)) {
1000 $outsocialnetwork .= dol_print_socialnetworks($this->linkedin, $this->id, $object->id, 'linkedin');
1005 if ($outsocialnetwork) {
1006 $out .= '<div style="clear: both;
">'.$outsocialnetwork.'</div>';
1011 return '<!-- BEGIN part to show address block -->'."\n
".$out.'<!-- END Part to show address block -->'."\n
";
1025 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1027 global $user, $dolibarr_main_url_root;
1029 if (empty($this->last_main_doc)) {
1030 return ''; // No way to known which document name to use
1033 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1034 $ecmfile = new EcmFiles($this->db);
1035 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1037 $this->error = $ecmfile->error;
1038 $this->errors = $ecmfile->errors;
1042 if (empty($ecmfile->id)) {
1043 // Add entry into index
1044 if ($initsharekey) {
1045 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1047 // 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
1049 $ecmfile->filepath = $rel_dir;
1050 $ecmfile->filename = $filename;
1051 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1052 $ecmfile->fullpath_orig = '';
1053 $ecmfile->gen_or_uploaded = 'generated';
1054 $ecmfile->description = ''; // indexed content
1055 $ecmfile->keywords = ''; // keyword content
1056 $ecmfile->share = getRandomPassword(true);
1057 $result = $ecmfile->create($user);
1060 $this->error = $ecmfile->error;
1061 $this->errors = $ecmfile->errors;
1067 } elseif (empty($ecmfile->share)) {
1068 // Add entry into index
1069 if ($initsharekey) {
1070 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1071 $ecmfile->share = getRandomPassword(true);
1072 $ecmfile->update($user);
1077 // Define $urlwithroot
1078 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1079 // This is to use external domain name found into config file
1080 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1082 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1083 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1088 //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1089 //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1090 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1091 if (!empty($ecmfile->share)) {
1092 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1094 if ($forcedownload) {
1095 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1098 if ($relativelink) {
1099 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1101 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1104 // Here $ecmfile->share is defined
1105 return $linktoreturn;
1109 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1119 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1122 global $user, $langs;
1125 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger
");
1128 if ($fk_socpeople <= 0) {
1129 $langs->load("errors
");
1130 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "1
");
1131 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1134 if (!$type_contact) {
1135 $langs->load("errors
");
1136 $this->error = $langs->trans("ErrorWrongValueForParameterX
", "2
");
1137 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1141 $id_type_contact = 0;
1142 if (is_numeric($type_contact)) {
1143 $id_type_contact = $type_contact;
1145 // We look for id type_contact
1146 $sql = "SELECT tc.rowid
";
1147 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1148 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1149 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1150 $sql .= " AND tc.code=
'".$this->db->escape($type_contact)."' AND tc.active=1
";
1152 $resql = $this->db->query($sql);
1154 $obj = $this->db->fetch_object($resql);
1156 $id_type_contact = $obj->rowid;
1161 if ($id_type_contact == 0) {
1162 $this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
1163 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
");
1167 $datecreate = dol_now();
1169 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1170 $TListeContacts = $this->liste_contact(-1, $source);
1171 $already_added = false;
1172 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1173 foreach ($TListeContacts as $array_contact) {
1174 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1175 $already_added = true;
1181 if (!$already_added) {
1184 // Insert into database
1185 $sql = "INSERT INTO
".$this->db->prefix()."element_contact
";
1186 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact)
";
1187 $sql .= " VALUES (
".$this->id.",
".((int) $fk_socpeople)." ,
";
1188 $sql .= "'".$this->db->idate($datecreate)."'";
1189 $sql .= ", 4,
".((int) $id_type_contact);
1192 $resql = $this->db->query($sql);
1195 $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1197 $this->db->rollback();
1202 $this->db->commit();
1205 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1206 $this->error = $this->db->errno();
1207 $this->db->rollback();
1210 $this->error = $this->db->lasterror();
1211 $this->db->rollback();
1220 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1228 public function copy_linked_contact($objFrom, $source = 'internal')
1231 $contacts = $objFrom->liste_contact(-1, $source);
1232 foreach ($contacts as $contact) {
1233 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1240 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1250 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1253 // Insert into database
1254 $sql = "UPDATE
".$this->db->prefix()."element_contact
set";
1255 $sql .= " statut =
".$statut;
1256 if ($type_contact_id) {
1257 $sql .= ", fk_c_type_contact =
".((int) $type_contact_id);
1259 if ($fk_socpeople) {
1260 $sql .= ", fk_socpeople =
".((int) $fk_socpeople);
1262 $sql .= " where
rowid =
".((int) $rowid);
1263 $resql = $this->db->query($sql);
1267 $this->error = $this->db->lasterror();
1272 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1280 public function delete_contact($rowid, $notrigger = 0)
1288 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1289 $sql .= " WHERE
rowid =
".((int) $rowid);
1292 if ($this->db->query($sql)) {
1294 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1296 $this->db->rollback();
1301 $this->db->commit();
1304 $this->error = $this->db->lasterror();
1305 $this->db->rollback();
1310 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1318 public function delete_linked_contact($source = '', $code = '')
1323 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1325 if (!empty($typeContact)) {
1326 foreach ($typeContact as $key => $value) {
1327 array_push($temp, $key);
1329 $listId = implode(",
", $temp);
1332 $sql = "DELETE FROM
".$this->db->prefix()."element_contact
";
1333 $sql .= " WHERE element_id =
".((int) $this->id);
1334 if (!empty($listId)) {
1335 $sql .= " AND fk_c_type_contact IN (
".$this->db->sanitize($listId).")
";
1339 if ($this->db->query($sql)) {
1342 $this->error = $this->db->lasterror();
1347 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1358 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1)
1365 $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
1366 if ($source == 'internal') {
1367 $sql .= ",
'-1' as socid, t.statut as statuscontact, t.login, t.photo
";
1369 if ($source == 'external' || $source == 'thirdparty') {
1370 $sql .= ", t.fk_soc as socid, t.statut as statuscontact
";
1372 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email
";
1373 $sql .= ", tc.source, tc.element, tc.code, tc.libelle
";
1374 $sql .= " FROM
".$this->db->prefix()."c_type_contact tc
";
1375 $sql .= ",
".$this->db->prefix()."element_contact ec
";
1376 if ($source == 'internal') { // internal contact (user)
1377 $sql .= " LEFT JOIN
".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid
";
1379 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1380 $sql .= " LEFT JOIN
".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid
";
1382 $sql .= " WHERE ec.element_id =
".((int) $this->id);
1383 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1384 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1386 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1388 if ($source == 'internal') {
1389 $sql .= " AND tc.source =
'internal'";
1391 $sql .= " AND t.statut =
".((int) $status);
1394 if ($source == 'external' || $source == 'thirdparty') {
1395 $sql .= " AND tc.source =
'external'";
1397 $sql .= " AND t.statut =
".((int) $status); // t is llx_socpeople
1400 $sql .= " AND tc.active=1
";
1401 if ($statusoflink >= 0) {
1402 $sql .= " AND ec.statut =
".((int) $statusoflink);
1404 $sql .= " ORDER BY t.lastname ASC
";
1407 $resql = $this->db->query($sql);
1409 $num = $this->db->num_rows($resql);
1412 $obj = $this->db->fetch_object($resql);
1415 $transkey = "TypeContact_
".$obj->element."_
".$obj->source."_
".$obj->code;
1416 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1418 'source' => $obj->source,
1419 'socid' => $obj->socid,
1421 'nom' => $obj->lastname, // For backward compatibility
1422 'civility' => $obj->civility,
1423 'lastname' => $obj->lastname,
1424 'firstname' => $obj->firstname,
1425 'email'=>$obj->email,
1426 'login'=> (empty($obj->login) ? '' : $obj->login),
1427 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1428 'statuscontact' => $obj->statuscontact,
1429 'rowid' => $obj->rowid,
1430 'code' => $obj->code,
1431 'libelle' => $libelle_type,
1432 'status' => $obj->statuslink,
1433 'fk_c_type_contact' => $obj->fk_c_type_contact
1436 $tab[$i] = $obj->id;
1444 $this->error = $this->db->lasterror();
1445 dol_print_error($this->db);
1457 public function swapContactStatus($rowid)
1459 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,
";
1460 $sql .= " tc.code, tc.libelle
";
1461 $sql .= " FROM (
".$this->db->prefix()."element_contact as ec,
".$this->db->prefix()."c_type_contact as tc)
";
1462 $sql .= " WHERE ec.rowid =
".((int) $rowid);
1463 $sql .= " AND ec.fk_c_type_contact=tc.rowid
";
1464 $sql .= " AND tc.element =
'".$this->db->escape($this->element)."'";
1467 $resql = $this->db->query($sql);
1469 $obj = $this->db->fetch_object($resql);
1470 $newstatut = ($obj->statut == 4) ? 5 : 4;
1471 $result = $this->update_contact($rowid, $newstatut);
1472 $this->db->free($resql);
1475 $this->error = $this->db->error();
1476 dol_print_error($this->db);
1481 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1492 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1497 if (empty($order)) {
1498 $order = 'position';
1500 if ($order == 'position') {
1505 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position
";
1506 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1507 $sql .= " WHERE tc.element=
'".$this->db->escape($this->element)."'";
1508 if ($activeonly == 1) {
1509 $sql .= " AND tc.active=1
"; // only the active types
1511 if (!empty($source) && $source != 'all') {
1512 $sql .= " AND tc.source=
'".$this->db->escape($source)."'";
1514 if (!empty($code)) {
1515 $sql .= " AND tc.code=
'".$this->db->escape($code)."'";
1517 $sql .= $this->db->order($order, 'ASC');
1519 //print "sql=
".$sql;
1520 $resql = $this->db->query($sql);
1522 $num = $this->db->num_rows($resql);
1525 $obj = $this->db->fetch_object($resql);
1527 $transkey = "TypeContact_
".$this->element."_
".$source."_
".$obj->code;
1528 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1529 if (empty($option)) {
1530 $tab[$obj->rowid] = $libelle_type;
1532 $tab[$obj->code] = $libelle_type;
1538 $this->error = $this->db->lasterror();
1539 //dol_print_error($this->db);
1555 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1557 global $langs, $conf;
1559 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1563 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position, tc.element
";
1564 $sql .= " FROM
".$this->db->prefix()."c_type_contact as tc
";
1566 $sqlWhere = array();
1567 if (!empty($element)) {
1568 $sqlWhere[] = " tc.element=
'".$this->db->escape($element)."'";
1570 if (!empty($excludeelement)) {
1571 $sqlWhere[] = " tc.element <>
'".$this->db->escape($excludeelement)."'";
1574 if ($activeonly == 1) {
1575 $sqlWhere[] = " tc.active=1
"; // only the active types
1578 if (!empty($source) && $source != 'all') {
1579 $sqlWhere[] = " tc.source=
'".$this->db->escape($source)."'";
1582 if (!empty($code)) {
1583 $sqlWhere[] = " tc.code=
'".$this->db->escape($code)."'";
1586 if (count($sqlWhere) > 0) {
1587 $sql .= " WHERE
".implode(' AND ', $sqlWhere);
1590 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1592 dol_syslog(__METHOD__, LOG_DEBUG);
1593 $resql = $this->db->query($sql);
1595 $num = $this->db->num_rows($resql);
1597 $langs->loadLangs(array("propal
", "orders
", "bills
", "suppliers
", "contracts
", "supplier_proposal
"));
1599 while ($obj = $this->db->fetch_object($resql)) {
1600 $modulename = $obj->element;
1601 if (strpos($obj->element, 'project') !== false) {
1602 $modulename = 'projet';
1603 } elseif ($obj->element == 'contrat') {
1604 $element = 'contract';
1605 } elseif ($obj->element == 'action') {
1606 $modulename = 'agenda';
1607 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1608 $modulename = 'fournisseur';
1609 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1610 $modulename = 'fournisseur';
1612 if (!empty($conf->{$modulename}->enabled)) {
1613 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1614 $tmpelement = $obj->element;
1615 $transkey = "TypeContact_
".$tmpelement."_
".$source."_
".$obj->code;
1616 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1617 if (empty($option)) {
1618 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1620 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1627 $this->error = $this->db->lasterror();
1643 public function getIdContact($source, $code, $status = 0)
1649 //cas particulier pour les expeditions
1650 if ($this->element == 'shipping' && $this->origin_id != 0) {
1651 $id = $this->origin_id;
1652 $element = 'commande';
1653 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1654 $id = $this->origin_id;
1655 $element = 'order_supplier';
1658 $element = $this->element;
1661 $sql = "SELECT ec.fk_socpeople
";
1662 $sql .= " FROM
".$this->db->prefix()."element_contact as ec,
";
1663 if ($source == 'internal') {
1664 $sql .= " ".$this->db->prefix()."user as c,
";
1666 if ($source == 'external') {
1667 $sql .= " ".$this->db->prefix()."socpeople as c,
";
1669 $sql .= " ".$this->db->prefix()."c_type_contact as tc
";
1670 $sql .= " WHERE ec.element_id =
".((int) $id);
1671 $sql .= " AND ec.fk_socpeople = c.rowid
";
1672 if ($source == 'internal') {
1673 $sql .= " AND c.entity IN (
".getEntity('user').")
";
1675 if ($source == 'external') {
1676 $sql .= " AND c.entity IN (
".getEntity('societe').")
";
1678 $sql .= " AND ec.fk_c_type_contact = tc.rowid
";
1679 $sql .= " AND tc.element =
'".$this->db->escape($element)."'";
1680 $sql .= " AND tc.source =
'".$this->db->escape($source)."'";
1682 $sql .= " AND tc.code =
'".$this->db->escape($code)."'";
1684 $sql .= " AND tc.active = 1
";
1686 $sql .= " AND ec.statut =
".((int) $status);
1690 $resql = $this->db->query($sql);
1692 while ($obj = $this->db->fetch_object($resql)) {
1693 $result[$i] = $obj->fk_socpeople;
1697 $this->error = $this->db->error();
1704 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1711 public function fetch_contact($contactid = null)
1714 if (empty($contactid)) {
1715 $contactid = $this->contact_id;
1718 if (empty($contactid)) {
1722 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1723 $contact = new Contact($this->db);
1724 $result = $contact->fetch($contactid);
1725 $this->contact = $contact;
1729 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1736 public function fetch_thirdparty($force_thirdparty_id = 0)
1741 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1745 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1747 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1748 if ($force_thirdparty_id) {
1749 $idtofetch = $force_thirdparty_id;
1753 $thirdparty = new Societe($this->db);
1754 $result = $thirdparty->fetch($idtofetch);
1756 $this->errors=array_merge($this->errors, $thirdparty->errors);
1758 $this->thirdparty = $thirdparty;
1760 // Use first price level if level not defined for third party
1761 if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1762 $this->thirdparty->price_level = 1;
1779 public function fetchOneLike($ref)
1781 if (!$this->table_ref_field) {
1785 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element." WHERE
".$this->table_ref_field." LIKE
'".$this->db->escape($ref)."' LIMIT 1
";
1787 $query = $this->db->query($sql);
1789 if (!$this->db->num_rows($query)) {
1793 $result = $this->db->fetch_object($query);
1795 return $this->fetch($result->rowid);
1798 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1806 public function fetch_barcode()
1811 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1813 $idtype = $this->barcode_type;
1814 if (empty($idtype) && $idtype != '0') { // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
1815 if ($this->element == 'product' && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
1816 $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1817 } elseif ($this->element == 'societe') {
1818 $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1820 dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1825 if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) { // If data not already loaded
1826 $sql = "SELECT
rowid,
code, libelle as label, coder
";
1827 $sql .= " FROM
".$this->db->prefix()."c_barcode_type
";
1828 $sql .= " WHERE
rowid =
".((int) $idtype);
1829 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1830 $resql = $this->db->query($sql);
1832 $obj = $this->db->fetch_object($resql);
1833 $this->barcode_type = $obj->rowid;
1834 $this->barcode_type_code = $obj->code;
1835 $this->barcode_type_label = $obj->label;
1836 $this->barcode_type_coder = $obj->coder;
1839 dol_print_error($this->db);
1847 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1853 public function fetch_project()
1856 return $this->fetch_projet();
1859 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1865 public function fetch_projet()
1868 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1870 if (empty($this->fk_project) && !empty($this->fk_projet)) {
1871 $this->fk_project = $this->fk_projet; // For backward compatibility
1873 if (empty($this->fk_project)) {
1877 $project = new Project($this->db);
1878 $result = $project->fetch($this->fk_project);
1880 $this->projet = $project; // deprecated
1881 $this->project = $project;
1885 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1891 public function fetch_product()
1894 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1896 if (empty($this->fk_product)) {
1900 $product = new Product($this->db);
1901 $result = $product->fetch($this->fk_product);
1903 $this->product = $product;
1907 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1914 public function fetch_user($userid)
1917 $user = new User($this->db);
1918 $result = $user->fetch($userid);
1919 $this->user = $user;
1923 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1929 public function fetch_origin()
1932 if ($this->origin == 'shipping') {
1933 $this->origin = 'expedition';
1935 if ($this->origin == 'delivery') {
1936 $this->origin = 'livraison';
1938 if ($this->origin == 'order_supplier') {
1939 $this->origin = 'commandeFournisseur';
1942 $origin = $this->origin;
1944 $classname = ucfirst($origin);
1945 $this->$origin = new $classname($this->db);
1946 $this->$origin->fetch($this->origin_id);
1958 public function fetchObjectFrom($table, $field, $key, $element = null)
1964 $sql = "SELECT
rowid FROM
".$this->db->prefix().$table;
1965 $sql .= " WHERE
".$field." =
'".$this->db->escape($key)."'";
1966 if (!empty($element)) {
1967 $sql .= " AND entity IN (
".getEntity($element).")
";
1969 $sql .= " AND entity =
".((int) $conf->entity);
1972 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1973 $resql = $this->db->query($sql);
1975 $row = $this->db->fetch_row($resql);
1976 // Test for avoid error -1
1978 $result = $this->fetch($row[0]);
1993 public function getValueFrom($table, $id, $field)
1996 if (!empty($id) && !empty($field) && !empty($table)) {
1997 $sql = "SELECT
".$field." FROM
".$this->db->prefix().$table;
1998 $sql .= " WHERE
rowid =
".((int) $id);
2000 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2001 $resql = $this->db->query($sql);
2003 $row = $this->db->fetch_row($resql);
2026 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2028 global $user, $langs, $conf;
2030 if (empty($table)) {
2031 $table = $this->table_element;
2036 if (empty($format)) {
2039 if (empty($id_field)) {
2040 $id_field = 'rowid';
2048 if ($table == 'product' && $field == 'note_private') {
2051 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2052 $fk_user_field = 'fk_user_mod';
2055 $sql = "UPDATE
".$this->db->prefix().$table." SET
";
2057 if ($format == 'text') {
2058 $sql .= $field." =
'".$this->db->escape($value)."'";
2059 } elseif ($format == 'int') {
2060 $sql .= $field." =
".((int) $value);
2061 } elseif ($format == 'date') {
2062 $sql .= $field." =
".($value ? "'".$this->db->idate($value)."'" : "null");
2065 if ($fk_user_field) {
2066 if (!empty($fuser) && is_object($fuser)) {
2067 $sql .= ",
".$fk_user_field." =
".((int) $fuser->id);
2068 } elseif (empty($fuser) || $fuser != 'none') {
2069 $sql .= ",
".$fk_user_field." =
".((int) $user->id);
2073 $sql .= " WHERE
".$id_field." =
".((int) $id);
2075 dol_syslog(__METHOD__, LOG_DEBUG);
2076 $resql = $this->db->query($sql);
2079 // call trigger with updated object values
2080 if (method_exists($this, 'fetch')) {
2081 $result = $this->fetch($id);
2083 $result = $this->fetchCommon($id);
2086 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2094 if (property_exists($this, $field)) {
2095 $this->$field = $value;
2097 $this->db->commit();
2100 $this->db->rollback();
2104 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2105 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2107 $this->error = $this->db->lasterror();
2109 $this->db->rollback();
2114 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2123 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2126 global $conf, $user;
2128 if (!$this->table_element) {
2129 dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with
property table_element not defined
");
2132 if ($fieldid == 'none') {
2136 // For backward compatibility
2137 if ($this->table_element == 'facture_rec' && $fieldid == 'title') {
2141 // Security on socid
2143 if ($user->socid > 0) {
2144 $socid = $user->socid;
2147 // this->ismultientitymanaged contains
2148 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2149 $aliastablesociete = 's';
2150 if ($this->element == 'societe') {
2151 $aliastablesociete = 'te'; // te as table_element
2153 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2154 $sql = "SELECT MAX(te.
".$fieldid.")
";
2155 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2156 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2157 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2159 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2160 $tmparray = explode('@', $this->ismultientitymanaged);
2161 $sql .= ",
".$this->db->prefix().$tmparray[1]." as
".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2162 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2163 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2164 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2165 $sql .= " LEFT JOIN
".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid
"; // If we need to link to societe to limit select to socid
2167 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2168 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2170 $sql .= " WHERE te.
".$fieldid." <
'".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2171 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2172 $sql .= " AND sc.fk_user =
".((int) $user->id);
2174 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2175 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2177 if (!empty($filter)) {
2178 if (!preg_match('/^\s*AND/i', $filter)) {
2179 $sql .= " AND
"; // For backward compatibility
2183 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2184 $tmparray = explode('@', $this->ismultientitymanaged);
2185 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2186 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2187 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2189 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2190 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2191 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2192 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2194 $sql .= " AND ug.fk_user = te.rowid
";
2195 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2198 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2201 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2202 $tmparray = explode('@', $this->ismultientitymanaged);
2203 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2205 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2206 $sql .= ' AND te.fk_soc = '.((int) $socid);
2208 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2209 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2211 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2212 $sql .= ' AND te.rowid = '.((int) $socid);
2214 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2216 $result = $this->db->query($sql);
2218 $this->error = $this->db->lasterror();
2221 $row = $this->db->fetch_row($result);
2222 $this->ref_previous = $row[0];
2224 $sql = "SELECT MIN(te.
".$fieldid.")
";
2225 $sql .= " FROM
".(empty($nodbprefix) ?$this->db->prefix():'').$this->table_element." as te
";
2226 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2227 $sql .= ",
".$this->db->prefix()."usergroup_user as ug
";
2229 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2230 $tmparray = explode('@', $this->ismultientitymanaged);
2231 $sql .= ",
".$this->db->prefix().$tmparray[1]." as
".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2232 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2233 $sql .= ",
".$this->db->prefix()."societe as s
"; // If we need to link to societe to limit select to socid
2234 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2235 $sql .= " LEFT JOIN
".$this->db->prefix()."societe as s ON te.fk_soc = s.rowid
"; // If we need to link to societe to limit select to socid
2237 if ($restrictiononfksoc && empty($user->rights->societe->client->voir) && !$socid) {
2238 $sql .= " LEFT JOIN
".$this->db->prefix()."societe_commerciaux as sc ON
".$aliastablesociete.".rowid = sc.fk_soc
";
2240 $sql .= " WHERE te.
".$fieldid." >
'".$this->db->escape($fieldid == 'rowid' ? $this->id : $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2241 if ($restrictiononfksoc == 1 && empty($user->rights->societe->client->voir) && !$socid) {
2242 $sql .= " AND sc.fk_user =
".((int) $user->id);
2244 if ($restrictiononfksoc == 2 && empty($user->rights->societe->client->voir) && !$socid) {
2245 $sql .= " AND (sc.fk_user =
".((int) $user->id).' OR te.fk_soc IS NULL)';
2247 if (!empty($filter)) {
2248 if (!preg_match('/^\s*AND/i', $filter)) {
2249 $sql .= " AND
"; // For backward compatibility
2253 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2254 $tmparray = explode('@', $this->ismultientitymanaged);
2255 $sql .= " AND te.
".$tmparray[0]." =
".($tmparray[1] == "societe
" ? "s
" : "parenttable
").".rowid
"; // If we need to link to this table to limit select to entity
2256 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && empty($user->rights->societe->client->voir) && !$socid) {
2257 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2259 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2260 if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
2261 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2262 $sql .= " AND te.entity IS NOT NULL
"; // Show all users
2264 $sql .= " AND ug.fk_user = te.rowid
";
2265 $sql .= " AND ug.entity IN (
".getEntity('usergroup').")
";
2268 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2271 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2272 $tmparray = explode('@', $this->ismultientitymanaged);
2273 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2275 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2276 $sql .= ' AND te.fk_soc = '.((int) $socid);
2278 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2279 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2281 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2282 $sql .= ' AND te.rowid = '.((int) $socid);
2284 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>
";
2285 // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
2287 $result = $this->db->query($sql);
2289 $this->error = $this->db->lasterror();
2292 $row = $this->db->fetch_row($result);
2293 $this->ref_next = $row[0];
2306 public function getListContactId($source = 'external')
2308 $contactAlreadySelected = array();
2309 $tab = $this->liste_contact(-1, $source);
2313 if ($source == 'thirdparty') {
2314 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2316 $contactAlreadySelected[$i] = $tab[$i]['id'];
2320 return $contactAlreadySelected;
2331 public function setProject($projectid, $notrigger = 0)
2336 if (!$this->table_element) {
2337 dol_syslog(get_class($this)."::
setProject was called on objet with property table_element not defined
", LOG_ERR);
2341 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2342 if (!empty($this->fields['fk_project'])) { // Common case
2344 $sql .= " SET fk_project =
".((int) $projectid);
2346 $sql .= " SET fk_project = NULL
";
2348 $sql .= ' WHERE rowid = '.((int) $this->id);
2349 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2351 $sql .= " SET fk_project =
".((int) $projectid);
2353 $sql .= " SET fk_project = NULL
";
2355 $sql .= ' WHERE id = '.((int) $this->id);
2356 } else // Special case for old architecture objects
2359 $sql .= ' SET fk_projet = '.((int) $projectid);
2361 $sql .= ' SET fk_projet = NULL';
2363 $sql .= " WHERE
rowid =
".((int) $this->id);
2368 dol_syslog(get_class($this)."::
setProject", LOG_DEBUG);
2369 if ($this->db->query($sql)) {
2370 $this->fk_project = ((int) $projectid);
2372 dol_print_error($this->db);
2377 if (!$error && !$notrigger) {
2379 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2382 } //Do also here what you must do to rollback action if trigger fail
2383 // End call triggers
2386 // Commit or rollback
2388 $this->db->rollback();
2391 $this->db->commit();
2402 public function setPaymentMethods($id)
2406 $error = 0; $notrigger = 0;
2408 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2410 if ($this->statut >= 0 || $this->element == 'societe') {
2411 // TODO uniformize field name
2412 $fieldname = 'fk_mode_reglement';
2413 if ($this->element == 'societe') {
2414 $fieldname = 'mode_reglement';
2416 if (get_class($this) == 'Fournisseur') {
2417 $fieldname = 'mode_reglement_supplier';
2419 if (get_class($this) == 'Tva') {
2420 $fieldname = 'fk_typepayment';
2422 if (get_class($this) == 'Salary') {
2423 $fieldname = 'fk_typepayment';
2426 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2427 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2428 $sql .= ' WHERE rowid='.((int) $this->id);
2430 if ($this->db->query($sql)) {
2431 $this->mode_reglement_id = $id;
2433 if (get_class($this) == 'Fournisseur') {
2434 $this->mode_reglement_supplier_id = $id;
2437 if (!$error && !$notrigger) {
2439 if (get_class($this) == 'Commande') {
2440 $result = $this->call_trigger('ORDER_MODIFY', $user);
2442 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2447 // End call triggers
2451 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2452 $this->error = $this->db->error();
2456 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2457 $this->error = 'Status of the object is incompatible '.$this->statut;
2468 public function setMulticurrencyCode($code)
2470 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2471 if ($this->statut >= 0 || $this->element == 'societe') {
2472 $fieldname = 'multicurrency_code';
2474 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2475 $sql .= " SET
".$fieldname." =
'".$this->db->escape($code)."'";
2476 $sql .= ' WHERE rowid='.((int) $this->id);
2478 if ($this->db->query($sql)) {
2479 $this->multicurrency_code = $code;
2481 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2483 $this->setMulticurrencyRate($rate, 2);
2488 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2489 $this->error = $this->db->error();
2493 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2494 $this->error = 'Status of the object is incompatible '.$this->statut;
2506 public function setMulticurrencyRate($rate, $mode = 1)
2508 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.','.$mode.')');
2509 if ($this->statut >= 0 || $this->element == 'societe') {
2510 $fieldname = 'multicurrency_tx';
2512 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2513 $sql .= " SET
".$fieldname." =
".((float) $rate);
2514 $sql .= ' WHERE rowid='.((int) $this->id);
2516 if ($this->db->query($sql)) {
2517 $this->multicurrency_tx = $rate;
2519 // Update line price
2520 if (!empty($this->lines)) {
2521 foreach ($this->lines as &$line) {
2522 // Amounts in company currency will be recalculated
2524 $line->subprice = 0;
2527 // Amounts in foreign currency will be recalculated
2529 $line->multicurrency_subprice = 0;
2532 switch ($this->element) {
2538 $line->remise_percent,
2540 $line->localtax1_tx,
2541 $line->localtax2_tx,
2542 ($line->description ? $line->description : $line->desc),
2545 $line->special_code,
2546 $line->fk_parent_line,
2547 $line->skip_update_total,
2548 $line->fk_fournprice,
2551 $line->product_type,
2554 $line->array_options,
2556 $line->multicurrency_subprice
2562 ($line->description ? $line->description : $line->desc),
2565 $line->remise_percent,
2567 $line->localtax1_tx,
2568 $line->localtax2_tx,
2573 $line->product_type,
2574 $line->fk_parent_line,
2575 $line->skip_update_total,
2576 $line->fk_fournprice,
2579 $line->special_code,
2580 $line->array_options,
2582 $line->multicurrency_subprice
2588 ($line->description ? $line->description : $line->desc),
2591 $line->remise_percent,
2595 $line->localtax1_tx,
2596 $line->localtax2_tx,
2599 $line->product_type,
2600 $line->fk_parent_line,
2601 $line->skip_update_total,
2602 $line->fk_fournprice,
2605 $line->special_code,
2606 $line->array_options,
2607 $line->situation_percent,
2609 $line->multicurrency_subprice
2612 case 'supplier_proposal':
2617 $line->remise_percent,
2619 $line->localtax1_tx,
2620 $line->localtax2_tx,
2621 ($line->description ? $line->description : $line->desc),
2624 $line->special_code,
2625 $line->fk_parent_line,
2626 $line->skip_update_total,
2627 $line->fk_fournprice,
2630 $line->product_type,
2631 $line->array_options,
2633 $line->multicurrency_subprice
2636 case 'order_supplier':
2639 ($line->description ? $line->description : $line->desc),
2642 $line->remise_percent,
2644 $line->localtax1_tx,
2645 $line->localtax2_tx,
2648 $line->product_type,
2652 $line->array_options,
2654 $line->multicurrency_subprice,
2658 case 'invoice_supplier':
2661 ($line->description ? $line->description : $line->desc),
2664 $line->localtax1_tx,
2665 $line->localtax2_tx,
2670 $line->product_type,
2671 $line->remise_percent,
2675 $line->array_options,
2677 $line->multicurrency_subprice,
2682 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2690 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2691 $this->error = $this->db->error();
2695 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2696 $this->error = 'Status of the object is incompatible '.$this->statut;
2708 public function setPaymentTerms($id, $deposit_percent = null)
2710 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2711 if ($this->statut >= 0 || $this->element == 'societe') {
2712 // TODO uniformize field name
2713 $fieldname = 'fk_cond_reglement';
2714 if ($this->element == 'societe') {
2715 $fieldname = 'cond_reglement';
2717 if (get_class($this) == 'Fournisseur') {
2718 $fieldname = 'cond_reglement_supplier';
2721 if (empty($deposit_percent) || $deposit_percent < 0) {
2722 $deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2725 if ($deposit_percent > 100) {
2726 $deposit_percent = 100;
2729 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2730 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2731 if (in_array($this->table_element, array('propal', 'commande'))) {
2732 $sql .= " , deposit_percent =
" . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2734 $sql .= ' WHERE rowid='.((int) $this->id);
2736 if ($this->db->query($sql)) {
2737 $this->cond_reglement_id = $id;
2739 if (get_class($this) == 'Fournisseur') {
2740 $this->cond_reglement_supplier_id = $id;
2742 $this->cond_reglement = $id; // for compatibility
2743 $this->deposit_percent = $deposit_percent;
2746 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2747 $this->error = $this->db->error();
2751 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2752 $this->error = 'Status of the object is incompatible '.$this->statut;
2763 public function setTransportMode($id)
2765 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2766 if ($this->statut >= 0 || $this->element == 'societe') {
2767 $fieldname = 'fk_transport_mode';
2768 if ($this->element == 'societe') {
2769 $fieldname = 'transport_mode';
2771 if (get_class($this) == 'Fournisseur') {
2772 $fieldname = 'transport_mode_supplier';
2775 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2776 $sql .= " SET
".$fieldname." =
".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2777 $sql .= ' WHERE rowid='.((int) $this->id);
2779 if ($this->db->query($sql)) {
2780 $this->transport_mode_id = $id;
2782 if (get_class($this) == 'Fournisseur') {
2783 $this->transport_mode_supplier_id = $id;
2787 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
2788 $this->error = $this->db->error();
2792 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
2793 $this->error = 'Status of the object is incompatible '.$this->statut;
2804 public function setRetainedWarrantyPaymentTerms($id)
2806 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
2807 if ($this->statut >= 0 || $this->element == 'societe') {
2808 $fieldname = 'retained_warranty_fk_cond_reglement';
2810 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2811 $sql .= " SET
".$fieldname." =
".((int) $id);
2812 $sql .= ' WHERE rowid='.((int) $this->id);
2814 if ($this->db->query($sql)) {
2815 $this->retained_warranty_fk_cond_reglement = $id;
2818 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
2819 $this->error = $this->db->error();
2823 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
2824 $this->error = 'Status of the object is incompatible '.$this->statut;
2836 public function setDeliveryAddress($id)
2838 $fieldname = 'fk_delivery_address';
2839 if ($this->element == 'delivery' || $this->element == 'shipping') {
2840 $fieldname = 'fk_address';
2843 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET
".$fieldname." =
".((int) $id);
2844 $sql .= " WHERE
rowid =
".((int) $this->id)." AND fk_statut = 0
";
2846 if ($this->db->query($sql)) {
2847 $this->fk_delivery_address = $id;
2850 $this->error = $this->db->error();
2851 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
2866 public function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2870 if (empty($userused)) {
2876 if (!$this->table_element) {
2877 dol_syslog(get_class($this)."::
setShippingMethod was called on objet with property table_element not defined
", LOG_ERR);
2883 if ($shipping_method_id < 0) {
2884 $shipping_method_id = 'NULL';
2886 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2888 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2889 $sql .= " SET fk_shipping_method =
".((int) $shipping_method_id);
2890 $sql .= " WHERE
rowid=
".((int) $this->id);
2891 $resql = $this->db->query($sql);
2893 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2894 $this->error = $this->db->lasterror();
2899 $this->context = array('shippingmethodupdate'=>1);
2900 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2908 $this->db->rollback();
2911 $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2912 $this->db->commit();
2924 public function setWarehouse($warehouse_id)
2926 if (!$this->table_element) {
2927 dol_syslog(get_class($this)."::
setWarehouse was called on objet with property table_element not defined
", LOG_ERR);
2930 if ($warehouse_id < 0) {
2931 $warehouse_id = 'NULL';
2933 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2935 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2936 $sql .= " SET fk_warehouse =
".((int) $warehouse_id);
2937 $sql .= " WHERE
rowid=
".((int) $this->id);
2939 if ($this->db->query($sql)) {
2940 $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2943 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2944 $this->error = $this->db->error();
2957 public function setDocModel($user, $modelpdf)
2959 if (!$this->table_element) {
2960 dol_syslog(get_class($this)."::
setDocModel was called on objet with property table_element not defined
", LOG_ERR);
2964 $newmodelpdf = dol_trunc($modelpdf, 255);
2966 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
2967 $sql .= " SET model_pdf =
'".$this->db->escape($newmodelpdf)."'";
2968 $sql .= " WHERE
rowid =
".((int) $this->id);
2970 dol_syslog(get_class($this)."::
setDocModel", LOG_DEBUG);
2971 $resql = $this->db->query($sql);
2973 $this->model_pdf = $modelpdf;
2974 $this->modelpdf = $modelpdf; // For bakward compatibility
2977 dol_print_error($this->db);
2991 public function setBankAccount($fk_account, $notrigger = false, $userused = null)
2995 if (empty($userused)) {
3001 if (!$this->table_element) {
3002 dol_syslog(get_class($this)."::
setBankAccount was called on objet with property table_element not defined
", LOG_ERR);
3007 if ($fk_account < 0) {
3008 $fk_account = 'NULL';
3010 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3012 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3013 $sql .= " SET fk_account =
".((int) $fk_account);
3014 $sql .= " WHERE
rowid=
".((int) $this->id);
3016 $resql = $this->db->query($sql);
3018 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3019 $this->error = $this->db->lasterror();
3024 $this->context = array('bankaccountupdate'=>1);
3025 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3033 $this->db->rollback();
3036 $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
3037 $this->db->commit();
3043 // TODO: Move line related operations to CommonObjectLine?
3045 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3055 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3058 if (!$this->table_element_line) {
3059 dol_syslog(get_class($this)."::
line_order was called on objet with property table_element_line not defined
", LOG_ERR);
3062 if (!$this->fk_element) {
3063 dol_syslog(get_class($this)."::
line_order was called on objet with property fk_element not defined
", LOG_ERR);
3067 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3068 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3069 $fieldposition = 'position';
3072 // Count number of lines to reorder (according to choice $renum)
3074 $sql = "SELECT count(
rowid) FROM
".$this->db->prefix().$this->table_element_line;
3075 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3077 $sql .= " AND
" . $fieldposition . " = 0
";
3080 $sql .= " AND
" . $fieldposition . " <> 0
";
3083 dol_syslog(get_class($this)."::
line_order", LOG_DEBUG);
3084 $resql = $this->db->query($sql);
3086 $row = $this->db->fetch_row($resql);
3089 dol_print_error($this->db);
3092 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3095 // We first search all lines that are parent lines (for multilevel details lines)
3096 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3097 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3098 if ($fk_parent_line) {
3099 $sql .= ' AND fk_parent_line IS NULL';
3101 $sql .= " ORDER BY
" . $fieldposition . " ASC,
rowid " . $rowidorder;
3103 dol_syslog(get_class($this)."::
line_order search all parent lines
", LOG_DEBUG);
3104 $resql = $this->db->query($sql);
3107 $num = $this->db->num_rows($resql);
3109 $row = $this->db->fetch_row($resql);
3110 $rows[] = $row[0]; // Add parent line into array rows
3111 $childrens = $this->getChildrenOfLine($row[0]);
3112 if (!empty($childrens)) {
3113 foreach ($childrens as $child) {
3114 array_push($rows, $child);
3120 // Now we set a new number for each lines (parent and children with children included into parent tree)
3121 if (!empty($rows)) {
3122 foreach ($rows as $key => $row) {
3123 $this->updateRangOfLine($row, ($key + 1));
3127 dol_print_error($this->db);
3140 public function getChildrenOfLine($id, $includealltree = 0)
3142 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3143 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3144 $fieldposition = 'position';
3149 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3150 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3151 $sql .= ' AND fk_parent_line = '.((int) $id);
3152 $sql .= " ORDER BY
" . $fieldposition . " ASC
";
3154 dol_syslog(get_class($this)."::
getChildrenOfLine search children lines
for line
".$id, LOG_DEBUG);
3155 $resql = $this->db->query($sql);
3157 if ($this->db->num_rows($resql) > 0) {
3158 while ($row = $this->db->fetch_row($resql)) {
3160 if (!empty($includealltree)) {
3161 $rows = array_merge($rows, $this->getChildrenOfLine($row[0]), $includealltree);
3169 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3177 public function line_up($rowid, $fk_parent_line = true)
3180 $this->line_order(false, 'ASC', $fk_parent_line);
3183 $rang = $this->getRangOfLine($rowid);
3185 // Update position of line
3186 $this->updateLineUp($rowid, $rang);
3189 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3197 public function line_down($rowid, $fk_parent_line = true)
3200 $this->line_order(false, 'ASC', $fk_parent_line);
3203 $rang = $this->getRangOfLine($rowid);
3205 // Get max value for rang
3206 $max = $this->line_max();
3208 // Update position of line
3209 $this->updateLineDown($rowid, $rang, $max);
3219 public function updateRangOfLine($rowid, $rang)
3221 global $hookmanager;
3222 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3223 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3224 $fieldposition = 'position';
3227 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3228 $sql .= ' WHERE rowid = '.((int) $rowid);
3231 if (!$this->db->query($sql)) {
3232 dol_print_error($this->db);
3235 $parameters=array('rowid'=>$rowid, 'rang'=>$rang, 'fieldposition' => $fieldposition);
3237 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3242 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3249 public function line_ajaxorder($rows)
3252 $num = count($rows);
3253 for ($i = 0; $i < $num; $i++) {
3254 $this->updateRangOfLine($rows[$i], ($i + 1));
3265 public function updateLineUp($rowid, $rang)
3268 $fieldposition = 'rang';
3269 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3270 $fieldposition = 'position';
3273 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3274 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3275 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang - 1));
3276 if ($this->db->query($sql)) {
3277 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang - 1));
3278 $sql .= ' WHERE rowid = '.((int) $rowid);
3279 if (!$this->db->query($sql)) {
3280 dol_print_error($this->db);
3283 dol_print_error($this->db);
3296 public function updateLineDown($rowid, $rang, $max)
3299 $fieldposition = 'rang';
3300 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3301 $fieldposition = 'position';
3304 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) $rang);
3305 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3306 $sql .= " AND
" . $fieldposition . " =
" . ((int) ($rang + 1));
3307 if ($this->db->query($sql)) {
3308 $sql = "UPDATE
".$this->db->prefix().$this->table_element_line." SET
".$fieldposition." =
".((int) ($rang + 1));
3309 $sql .= ' WHERE rowid = '.((int) $rowid);
3310 if (!$this->db->query($sql)) {
3311 dol_print_error($this->db);
3314 dol_print_error($this->db);
3325 public function getRangOfLine($rowid)
3327 $fieldposition = 'rang';
3328 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3329 $fieldposition = 'position';
3332 $sql = "SELECT
" . $fieldposition . " FROM
".$this->db->prefix().$this->table_element_line;
3333 $sql .= " WHERE
rowid =
".((int) $rowid);
3336 $resql = $this->db->query($sql);
3338 $row = $this->db->fetch_row($resql);
3351 public function getIdOfLine($rang)
3353 $fieldposition = 'rang';
3354 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3355 $fieldposition = 'position';
3358 $sql = "SELECT
rowid FROM
".$this->db->prefix().$this->table_element_line;
3359 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3360 $sql .= " AND
" . $fieldposition . " =
".((int) $rang);
3361 $resql = $this->db->query($sql);
3363 $row = $this->db->fetch_row($resql);
3370 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3377 public function line_max($fk_parent_line = 0)
3380 $positionfield = 'rang';
3381 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3382 $positionfield = 'position';
3385 // Search the last rang with fk_parent_line
3386 if ($fk_parent_line) {
3387 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3388 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3389 $sql .= " AND fk_parent_line =
".((int) $fk_parent_line);
3391 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3392 $resql = $this->db->query($sql);
3394 $row = $this->db->fetch_row($resql);
3395 if (!empty($row[0])) {
3398 return $this->getRangOfLine($fk_parent_line);
3402 // If not, search the last rang of element
3403 $sql = "SELECT max(
".$positionfield.") FROM
".$this->db->prefix().$this->table_element_line;
3404 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3406 dol_syslog(get_class($this)."::
line_max", LOG_DEBUG);
3407 $resql = $this->db->query($sql);
3409 $row = $this->db->fetch_row($resql);
3417 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3424 public function update_ref_ext($ref_ext)
3427 if (!$this->table_element) {
3428 dol_syslog(get_class($this)."::
update_ref_ext was called on objet with property table_element not defined
", LOG_ERR);
3432 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3433 $sql .= " SET ref_ext =
'".$this->db->escape($ref_ext)."'";
3434 $sql .= " WHERE
".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." =
".((int) $this->id);
3437 if ($this->db->query($sql)) {
3438 $this->ref_ext = $ref_ext;
3441 $this->error = $this->db->error();
3446 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3454 public function update_note($note, $suffix = '')
3459 if (!$this->table_element) {
3460 $this->error = 'update_note was called on objet with property table_element not defined';
3461 dol_syslog(get_class($this)."::
update_note was called on objet with property table_element not defined
", LOG_ERR);
3464 if (!in_array($suffix, array('', '_public', '_private'))) {
3465 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3466 dol_syslog(get_class($this)."::
update_note Parameter suffix must be empty,
'_private' or
'_public'", LOG_ERR);
3470 $newsuffix = $suffix;
3473 if ($this->table_element == 'product' && $newsuffix == '_private') {
3476 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3477 $fieldusermod = "fk_user_mod
";
3478 } elseif ($this->table_element == 'ecm_files') {
3479 $fieldusermod = "fk_user_m
";
3481 $fieldusermod = "fk_user_modif
";
3483 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
3484 $sql .= " SET note
".$newsuffix." =
".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL
");
3485 $sql .= ",
".$fieldusermod." =
".((int) $user->id);
3486 $sql .= " WHERE
rowid =
".((int) $this->id);
3488 dol_syslog(get_class($this)."::
update_note", LOG_DEBUG);
3489 if ($this->db->query($sql)) {
3490 if ($suffix == '_public') {
3491 $this->note_public = $note;
3492 } elseif ($suffix == '_private') {
3493 $this->note_private = $note;
3495 $this->note = $note; // deprecated
3496 $this->note_private = $note;
3500 $this->error = $this->db->lasterror();
3505 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3514 public function update_note_public($note)
3517 return $this->update_note($note, '_public');
3520 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3531 public function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
3534 global $conf, $hookmanager, $action;
3536 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3537 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3539 return 1; // replacement code
3540 } elseif ($reshook < 0) {
3541 return -1; // failure
3542 } // reshook = 0 => execute normal code
3544 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3546 if ($this->element == 'propal') {
3547 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL
";
3548 } elseif ($this->element == 'commande' || $this->element == 'order') {
3549 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER
";
3550 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3551 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE
";
3552 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3553 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE
";
3554 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3555 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER
";
3556 } elseif ($this->element == 'supplier_proposal') {
3557 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL
";
3560 if (!empty($MODULE)) {
3561 if (!empty($conf->global->$MODULE)) {
3562 $modsactivated = explode(',', $conf->global->$MODULE);
3563 foreach ($modsactivated as $mod) {
3564 if (isModEnabled($mod)) {
3565 return 1; // update was disabled by specific setup
3571 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3573 $forcedroundingmode = $roundingadjust;
3574 if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
3575 $forcedroundingmode = getDolGlobalString('MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND');
3576 } elseif ($forcedroundingmode == 'auto') {
3577 $forcedroundingmode = '0';
3582 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3584 // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3585 $fieldtva = 'total_tva';
3586 $fieldlocaltax1 = 'total_localtax1';
3587 $fieldlocaltax2 = 'total_localtax2';
3588 $fieldup = 'subprice';
3589 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3593 if ($this->element == 'invoice_supplier_rec') {
3596 if ($this->element == 'expensereport') {
3597 $fieldup = 'value_unit';
3600 $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,
";
3601 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3602 if ($this->table_element_line == 'facturedet') {
3603 $sql .= ', situation_percent';
3605 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3606 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
3607 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
3609 $product_field = 'product_type';
3610 if ($this->table_element_line == 'contratdet') {
3611 $product_field = ''; // contratdet table has no product_type field
3613 if ($product_field) {
3614 $sql .= " AND
".$product_field." <> 9
";
3617 $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
3619 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3621 $resql = $this->db->query($sql);
3623 $this->total_ht = 0;
3624 $this->total_tva = 0;
3625 $this->total_localtax1 = 0;
3626 $this->total_localtax2 = 0;
3627 $this->total_ttc = 0;
3628 $total_ht_by_vats = array();
3629 $total_tva_by_vats = array();
3630 $total_ttc_by_vats = array();
3631 $this->multicurrency_total_ht = 0;
3632 $this->multicurrency_total_tva = 0;
3633 $this->multicurrency_total_ttc = 0;
3635 $num = $this->db->num_rows($resql);
3638 $obj = $this->db->fetch_object($resql);
3640 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3641 $parameters = array('fk_element' => $obj->rowid);
3642 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3644 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'
3645 // This part of code is to fix data. We should not call it too often.
3646 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3647 $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);
3649 $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3650 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3651 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3652 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3654 if ($diff_on_current_total) {
3655 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3656 $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);
3657 dol_syslog('We found unconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=
".$obj->total_ht." vat=
".$obj->total_tva." tax1=
".$obj->total_localtax1." tax2=
".$obj->total_localtax2." ttc=
".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix =
".$sqlfix, LOG_WARNING);
3658 $resqlfix = $this->db->query($sqlfix);
3660 dol_print_error($this->db, 'Failed to update line');
3662 $obj->total_tva = $tmpcal[1];
3663 $obj->total_ttc = $tmpcal[2];
3664 } elseif ($diff_when_using_price_ht && $roundingadjust == '0') {
3665 // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3666 // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3667 $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);
3668 dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=
".$tmpcal[1].", database=
".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix =
".$sqlfix);
3669 $resqlfix = $this->db->query($sqlfix);
3671 dol_print_error($this->db, 'Failed to update line');
3673 $obj->total_tva = $tmpcal[1];
3674 $obj->total_ttc = $tmpcal[2];
3678 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3679 $this->total_tva += $obj->total_tva;
3680 $this->total_localtax1 += $obj->total_localtax1;
3681 $this->total_localtax2 += $obj->total_localtax2;
3682 $this->total_ttc += $obj->total_ttc;
3683 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3684 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3685 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3687 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3688 $total_ht_by_vats[$obj->vatrate] = 0;
3690 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3691 $total_tva_by_vats[$obj->vatrate] = 0;
3693 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3694 $total_ttc_by_vats[$obj->vatrate] = 0;
3696 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3697 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3698 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3700 if ($forcedroundingmode == '1') { // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3701 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3702 $diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
3703 //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
";
3705 if (abs($diff) > 0.1) {
3706 $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.';
3707 dol_syslog($errmsg, LOG_WARNING);
3708 dol_print_error('', $errmsg);
3711 $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);
3712 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);
3714 $resqlfix = $this->db->query($sqlfix);
3717 dol_print_error($this->db, 'Failed to update line');
3720 $this->total_tva = (float) price2num($this->total_tva - $diff, '', 1);
3721 $this->total_ttc = (float) price2num($this->total_ttc - $diff, '', 1);
3722 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - $diff, '', 1);
3723 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - $diff, '', 1);
3730 // Add revenue stamp to total
3731 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3732 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
3734 // Situations totals
3735 if (!empty($this->situation_cycle_ref) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE) {
3736 $prev_sits = $this->get_prev_sits();
3738 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
3739 $this->total_ht -= $sit->total_ht;
3740 $this->total_tva -= $sit->total_tva;
3741 $this->total_localtax1 -= $sit->total_localtax1;
3742 $this->total_localtax2 -= $sit->total_localtax2;
3743 $this->total_ttc -= $sit->total_ttc;
3744 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
3745 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
3746 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
3751 $this->total_ht = (float) price2num($this->total_ht);
3752 $this->total_tva = (float) price2num($this->total_tva);
3753 $this->total_localtax1 = (float) price2num($this->total_localtax1);
3754 $this->total_localtax2 = (float) price2num($this->total_localtax2);
3755 $this->total_ttc = (float) price2num($this->total_ttc);
3757 $this->db->free($resql);
3759 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
3760 $fieldht = 'total_ht';
3762 $fieldlocaltax1 = 'localtax1';
3763 $fieldlocaltax2 = 'localtax2';
3764 $fieldttc = 'total_ttc';
3765 // Specific code for backward compatibility with old field names
3766 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
3767 $fieldtva = 'total_tva';
3770 if (empty($nodatabaseupdate)) {
3771 $sql = "UPDATE
".$this->db->prefix().$this->table_element.' SET';
3772 $sql .= " ".$fieldht." =
".((float) price2num($this->total_ht, 'MT', 1)).",
";
3773 $sql .= " ".$fieldtva." =
".((float) price2num($this->total_tva, 'MT', 1)).",
";
3774 $sql .= " ".$fieldlocaltax1." =
".((float) price2num($this->total_localtax1, 'MT', 1)).",
";
3775 $sql .= " ".$fieldlocaltax2." =
".((float) price2num($this->total_localtax2, 'MT', 1)).",
";
3776 $sql .= " ".$fieldttc." =
".((float) price2num($this->total_ttc, 'MT', 1));
3777 $sql .= ", multicurrency_total_ht =
".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
3778 $sql .= ", multicurrency_total_tva =
".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
3779 $sql .= ", multicurrency_total_ttc =
".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
3780 $sql .= " WHERE
rowid =
".((int) $this->id);
3782 dol_syslog(get_class($this)."::
update_price", LOG_DEBUG);
3783 $resql = $this->db->query($sql);
3787 $this->error = $this->db->lasterror();
3788 $this->errors[] = $this->db->lasterror();
3798 dol_print_error($this->db, 'Bad request in update_price');
3803 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3814 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
3817 global $user, $hookmanager, $action;
3818 $origin = (!empty($origin) ? $origin : $this->origin);
3819 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
3820 $f_user = isset($f_user) ? $f_user : $user;
3823 if ($origin == 'order') {
3824 $origin = 'commande';
3826 if ($origin == 'invoice') {
3827 $origin = 'facture';
3829 if ($origin == 'invoice_template') {
3830 $origin = 'facturerec';
3832 if ($origin == 'supplierorder') {
3833 $origin = 'order_supplier';
3836 // 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.
3837 // 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.
3838 $coremodule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
3839 // Add module part to target type if object has $module property and isn't in core modules.
3840 $targettype = ((!empty($this->module) && ! in_array($this->module, $coremodule)) ? $this->module.'_' : '').$this->element;
3842 $parameters = array('targettype'=>$targettype);
3843 // Hook for explicitly set the targettype if it must be differtent than $this->element
3844 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3846 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3852 $sql = "INSERT INTO
" . $this->db->prefix() . "element_element (
";
3853 $sql .= "fk_source
";
3854 $sql .= ", sourcetype
";
3855 $sql .= ", fk_target
";
3856 $sql .= ", targettype
";
3857 $sql .= ") VALUES (
";
3858 $sql .= ((int) $origin_id);
3859 $sql .= ",
'" . $this->db->escape($origin) . "'";
3860 $sql .= ",
" . ((int) $this->id);
3861 $sql .= ",
'" . $this->db->escape($targettype) . "'";
3865 if ($this->db->query($sql)) {
3868 $this->context['link_origin'] = $origin;
3869 $this->context['link_origin_id'] = $origin_id;
3870 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
3874 // End call triggers
3877 $this->error = $this->db->lasterror();
3882 $this->db->commit();
3885 $this->db->rollback();
3912 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
3914 global $conf, $hookmanager, $action;
3916 // Important for pdf generation time reduction
3917 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
3918 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
3922 $this->linkedObjectsIds = array();
3923 $this->linkedObjects = array();
3925 $justsource = false;
3926 $justtarget = false;
3927 $withtargettype = false;
3928 $withsourcetype = false;
3930 $parameters = array('sourcetype'=>$sourcetype, 'sourceid'=>$sourceid, 'targettype'=>$targettype, 'targetid'=>$targetid);
3931 // Hook for explicitly set the targettype if it must be differtent than $this->element
3932 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3934 if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
3935 if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
3936 if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
3937 if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
3940 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
3941 $justsource = true; // the source (id and type) is a search criteria
3942 if (!empty($targettype)) {
3943 $withtargettype = true;
3946 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
3947 $justtarget = true; // the target (id and type) is a search criteria
3948 if (!empty($sourcetype)) {
3949 $withsourcetype = true;
3953 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3954 $targetid = (!empty($targetid) ? $targetid : $this->id);
3955 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3956 $targettype = (!empty($targettype) ? $targettype : $this->element);
3958 /*if (empty($sourceid) && empty($targetid))
3960 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
3964 // Links between objects are stored in table element_element
3965 $sql = "SELECT
rowid, fk_source, sourcetype, fk_target, targettype
";
3966 $sql .= " FROM
".$this->db->prefix()."element_element
";
3968 if ($justsource || $justtarget) {
3970 $sql .= "fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3971 if ($withtargettype) {
3972 $sql .= " AND targettype =
'".$this->db->escape($targettype)."'";
3974 } elseif ($justtarget) {
3975 $sql .= "fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."'";
3976 if ($withsourcetype) {
3977 $sql .= " AND sourcetype =
'".$this->db->escape($sourcetype)."'";
3981 $sql .= "(fk_source =
".((int) $sourceid)." AND sourcetype =
'".$this->db->escape($sourcetype)."')
";
3982 $sql .= " ".$clause." (fk_target =
".((int) $targetid)." AND targettype =
'".$this->db->escape($targettype)."')
";
3983 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
3984 $this->linkedObjectsFullLoaded[$this->id] = true;
3987 $sql .= " ORDER BY
".$orderby;
3989 dol_syslog(get_class($this)."::fetchObjectLink
", LOG_DEBUG);
3990 $resql = $this->db->query($sql);
3992 $num = $this->db->num_rows($resql);
3995 $obj = $this->db->fetch_object($resql);
3996 if ($justsource || $justtarget) {
3998 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3999 } elseif ($justtarget) {
4000 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4003 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4004 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4006 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4007 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4013 if (!empty($this->linkedObjectsIds)) {
4014 $tmparray = $this->linkedObjectsIds;
4015 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4016 // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
4017 $module = $element = $subelement = $objecttype;
4019 if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
4020 && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
4021 $module = $element = $regs[1];
4022 $subelement = $regs[2];
4025 $classpath = $element.'/class';
4026 // To work with non standard classpath or module name
4027 if ($objecttype == 'facture') {
4028 $classpath = 'compta/facture/class';
4029 } elseif ($objecttype == 'facturerec') {
4030 $classpath = 'compta/facture/class';
4031 $module = 'facture';
4032 } elseif ($objecttype == 'propal') {
4033 $classpath = 'comm/propal/class';
4034 } elseif ($objecttype == 'supplier_proposal') {
4035 $classpath = 'supplier_proposal/class';
4036 } elseif ($objecttype == 'shipping') {
4037 $classpath = 'expedition/class';
4038 $subelement = 'expedition';
4039 $module = 'expedition_bon';
4040 } elseif ($objecttype == 'delivery') {
4041 $classpath = 'delivery/class';
4042 $subelement = 'delivery';
4043 $module = 'delivery_note';
4044 } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
4045 $classpath = 'fourn/class';
4046 $module = 'fournisseur';
4047 } elseif ($objecttype == 'fichinter') {
4048 $classpath = 'fichinter/class';
4049 $subelement = 'fichinter';
4050 $module = 'ficheinter';
4051 } elseif ($objecttype == 'subscription') {
4052 $classpath = 'adherents/class';
4053 $module = 'adherent';
4054 } elseif ($objecttype == 'contact') {
4055 $module = 'societe';
4058 $classfile = strtolower($subelement);
4059 $classname = ucfirst($subelement);
4061 if ($objecttype == 'order') {
4062 $classfile = 'commande';
4063 $classname = 'Commande';
4064 } elseif ($objecttype == 'invoice_supplier') {
4065 $classfile = 'fournisseur.facture';
4066 $classname = 'FactureFournisseur';
4067 } elseif ($objecttype == 'order_supplier') {
4068 $classfile = 'fournisseur.commande';
4069 $classname = 'CommandeFournisseur';
4070 } elseif ($objecttype == 'supplier_proposal') {
4071 $classfile = 'supplier_proposal';
4072 $classname = 'SupplierProposal';
4073 } elseif ($objecttype == 'facturerec') {
4074 $classfile = 'facture-rec';
4075 $classname = 'FactureRec';
4076 } elseif ($objecttype == 'subscription') {
4077 $classfile = 'subscription';
4078 $classname = 'Subscription';
4079 } elseif ($objecttype == 'project' || $objecttype == 'projet') {
4080 $classpath = 'projet/class';
4081 $classfile = 'project';
4082 $classname = 'Project';
4083 } elseif ($objecttype == 'conferenceorboothattendee') {
4084 $classpath = 'eventorganization/class';
4085 $classfile = 'conferenceorboothattendee';
4086 $classname = 'ConferenceOrBoothAttendee';
4087 $module = 'eventorganization';
4088 } elseif ($objecttype == 'conferenceorbooth') {
4089 $classpath = 'eventorganization/class';
4090 $classfile = 'conferenceorbooth';
4091 $classname = 'ConferenceOrBooth';
4092 $module = 'eventorganization';
4093 } elseif ($objecttype == 'mo') {
4094 $classpath = 'mrp/class';
4100 // Here $module, $classfile and $classname are set, we can use them.
4101 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4102 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4103 dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
4104 //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
4105 if (class_exists($classname)) {
4106 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4107 $object = new $classname($this->db);
4108 $ret = $object->fetch($objectid);
4110 $this->linkedObjects[$objecttype][$i] = $object;
4116 unset($this->linkedObjectsIds[$objecttype]);
4122 dol_print_error($this->db);
4133 public function clearObjectLinkedCache()
4135 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4136 unset($this->linkedObjectsFullLoaded[$this->id]);
4154 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4157 $updatesource = false;
4158 $updatetarget = false;
4159 $f_user = isset($f_user) ? $f_user : $user;
4161 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4162 $updatesource = true;
4163 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4164 $updatetarget = true;
4170 $sql = "UPDATE
" . $this->db->prefix() . "element_element SET
";
4171 if ($updatesource) {
4172 $sql .= "fk_source =
" . ((int) $sourceid);
4173 $sql .= ", sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4174 $sql .= " WHERE fk_target =
" . ((int) $this->id);
4175 $sql .= " AND targettype =
'" . $this->db->escape($this->element) . "'";
4176 } elseif ($updatetarget) {
4177 $sql .= "fk_target =
" . ((int) $targetid);
4178 $sql .= ", targettype =
'" . $this->db->escape($targettype) . "'";
4179 $sql .= " WHERE fk_source =
" . ((int) $this->id);
4180 $sql .= " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4184 if ($this->db->query($sql)) {
4187 $this->context['link_source_id'] = $sourceid;
4188 $this->context['link_source_type'] = $sourcetype;
4189 $this->context['link_target_id'] = $targetid;
4190 $this->context['link_target_type'] = $targettype;
4191 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4195 // End call triggers
4198 $this->error = $this->db->lasterror();
4203 $this->db->commit();
4206 $this->db->rollback();
4224 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
4227 $deletesource = false;
4228 $deletetarget = false;
4229 $f_user = isset($f_user) ? $f_user : $user;
4231 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4232 $deletesource = true;
4233 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4234 $deletetarget = true;
4237 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4238 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4239 $targetid = (!empty($targetid) ? $targetid : $this->id);
4240 $targettype = (!empty($targettype) ? $targettype : $this->element);
4246 $this->context['link_id'] = $rowid;
4247 $this->context['link_source_id'] = $sourceid;
4248 $this->context['link_source_type'] = $sourcetype;
4249 $this->context['link_target_id'] = $targetid;
4250 $this->context['link_target_type'] = $targettype;
4251 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4255 // End call triggers
4259 $sql = "DELETE FROM
" . $this->db->prefix() . "element_element
";
4262 $sql .= " rowid =
" . ((int) $rowid);
4264 if ($deletesource) {
4265 $sql .= " fk_source =
" . ((int) $sourceid) . " AND sourcetype =
'" . $this->db->escape($sourcetype) . "'";
4266 $sql .= " AND fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "'";
4267 } elseif ($deletetarget) {
4268 $sql .= " fk_target =
" . ((int) $targetid) . " AND targettype =
'" . $this->db->escape($targettype) . "'";
4269 $sql .= " AND fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "'";
4271 $sql .= " (fk_source =
" . ((int) $this->id) . " AND sourcetype =
'" . $this->db->escape($this->element) . "')
";
4273 $sql .= " (fk_target =
" . ((int) $this->id) . " AND targettype =
'" . $this->db->escape($this->element) . "')
";
4278 if (!$this->db->query($sql)) {
4279 $this->error = $this->db->lasterror();
4280 $this->errors[] = $this->error;
4286 $this->db->commit();
4289 $this->db->rollback();
4303 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4305 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4311 $sql = "SELECT
".$field_select." FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4312 $resql = $db->query($sql);
4315 if (!empty($resql)) {
4316 while ($res = $db->fetch_object($resql)) {
4317 $TRes[] = $res->{$field_select};
4332 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4334 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4340 $sql = "DELETE FROM
".$db->prefix().$table_element." WHERE
".$field_where." =
".((int) $fk_object_where);
4341 $resql = $db->query($sql);
4343 if (empty($resql)) {
4360 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4362 global $user, $langs, $conf;
4364 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4366 $elementId = (!empty($elementId) ? $elementId : $this->id);
4367 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4371 if ($elementTable == 'facture_rec') {
4372 $fieldstatus = "suspended
";
4374 if ($elementTable == 'mailing') {
4375 $fieldstatus = "statut
";
4377 if ($elementTable == 'cronjob') {
4378 $fieldstatus = "status
";
4380 if ($elementTable == 'user') {
4381 $fieldstatus = "statut
";
4383 if ($elementTable == 'expensereport') {
4384 $fieldstatus = "fk_statut
";
4386 if ($elementTable == 'commande_fournisseur_dispatch') {
4387 $fieldstatus = "status
";
4389 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4390 $fieldstatus = 'status';
4393 $sql = "UPDATE
".$this->db->prefix().$elementTable;
4394 $sql .= " SET
".$fieldstatus." =
".((int) $status);
4395 // If status = 1 = validated, update also fk_user_valid
4396 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4397 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4398 $sql .= ", fk_user_valid =
".((int) $user->id);
4400 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4401 $sql .= ", date_valid =
'".$this->db->idate(dol_now())."'";
4403 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4404 $sql .= ", date_validation =
'".$this->db->idate(dol_now())."'";
4406 $sql .= " WHERE
rowid =
".((int) $elementId);
4407 $sql .= " AND
".$fieldstatus." <>
".((int) $status); // We avoid update if status already correct
4409 dol_syslog(get_class($this)."::
setStatut", LOG_DEBUG);
4410 $resql = $this->db->query($sql);
4414 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4416 if ($nb_rows_affected > 0) {
4417 if (empty($trigkey)) {
4418 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4419 if ($this->element == 'supplier_proposal' && $status == 2) {
4420 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4422 if ($this->element == 'supplier_proposal' && $status == 3) {
4423 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4425 if ($this->element == 'supplier_proposal' && $status == 4) {
4426 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4428 if ($this->element == 'fichinter' && $status == 3) {
4429 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4431 if ($this->element == 'fichinter' && $status == 2) {
4432 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4434 if ($this->element == 'fichinter' && $status == 1) {
4435 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4441 $result = $this->call_trigger($trigkey, $user);
4445 // End call triggers
4448 // The status was probably already good. We do nothing more, no triggers.
4452 $this->db->commit();
4454 if (empty($savElementId)) {
4455 // If the element we update is $this (so $elementId was provided as null)
4456 if ($fieldstatus == 'tosell') {
4457 $this->status = $status;
4458 } elseif ($fieldstatus == 'tobuy') {
4459 $this->status_buy = $status;
4461 $this->statut = $status;
4462 $this->status = $status;
4468 $this->db->rollback();
4469 dol_syslog(get_class($this)."::
setStatut ".$this->error, LOG_ERR);
4473 $this->error = $this->db->lasterror();
4474 $this->db->rollback();
4487 public function getCanvas($id = 0, $ref = '')
4491 if (empty($id) && empty($ref)) {
4494 if (!empty($conf->global->MAIN_DISABLE_CANVAS)) {
4495 return 0; // To increase speed. Not enabled by default.
4501 $sql = "SELECT
rowid, canvas
";
4502 $sql .= " FROM
".$this->db->prefix().$this->table_element;
4503 $sql .= " WHERE entity IN (
".getEntity($this->element).")
";
4505 $sql .= " AND
rowid =
".((int) $id);
4508 $sql .= " AND
ref =
'".$this->db->escape($ref)."'";
4511 $resql = $this->db->query($sql);
4513 $obj = $this->db->fetch_object($resql);
4515 $this->canvas = $obj->canvas;
4521 dol_print_error($this->db);
4533 public function getSpecialCode($lineid)
4535 $sql = "SELECT special_code FROM
".$this->db->prefix().$this->table_element_line;
4536 $sql .= " WHERE
rowid =
".((int) $lineid);
4537 $resql = $this->db->query($sql);
4539 $row = $this->db->fetch_row($resql);
4552 public function isObjectUsed($id = 0, $entity = 0)
4561 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4562 dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
4566 $arraytoscan = $this->childtables;
4567 // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
4568 $tmparray = array_keys($this->childtables);
4569 if (is_numeric($tmparray[0])) {
4570 $arraytoscan = array_flip($this->childtables);
4573 // Test if child exists
4575 foreach ($arraytoscan as $table => $element) {
4576 //print $id.'-'.$table.'-'.$elementname.'<br>';
4577 // Check if element can be deleted
4578 $sql = "SELECT COUNT(*) as nb
";
4579 $sql.= " FROM
".$this->db->prefix().$table." as c
";
4580 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4581 $sql.= ",
".$this->db->prefix().$element['parent']." as p
";
4583 $sql.= " WHERE c.
".$this->fk_element." =
".((int) $id);
4584 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4585 $sql.= " AND c.
".$element['parentkey']." = p.rowid
";
4587 if (!empty($entity)) {
4588 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4589 $sql.= " AND p.entity =
".((int) $entity);
4591 $sql.= " AND c.entity =
".((int) $entity);
4594 $resql = $this->db->query($sql);
4596 $obj = $this->db->fetch_object($resql);
4598 $langs->load("errors
");
4599 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4600 $haschild += $obj->nb;
4601 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4602 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4603 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4604 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4605 } else { // new usage: $element['name']=Translation key
4606 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType
", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4608 break; // We found at least one, we stop here
4611 $this->errors[] = $this->db->lasterror();
4615 if ($haschild > 0) {
4616 $this->errors[] = "ErrorRecordHasChildren
";
4629 public function hasProductsOrServices($predefined = -1)
4633 foreach ($this->lines as $key => $val) {
4635 if ($predefined == -1) {
4638 if ($predefined == 1 && $val->fk_product > 0) {
4641 if ($predefined == 0 && $val->fk_product <= 0) {
4644 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4647 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4654 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4663 public function getTotalDiscount()
4665 if (!empty($this->table_element_line) ) {
4666 $total_discount = 0.00;
4668 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht
";
4669 $sql .= " FROM
".$this->db->prefix().$this->table_element_line;
4670 $sql .= " WHERE
".$this->fk_element." =
".((int) $this->id);
4672 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4673 $resql = $this->db->query($sql);
4675 $num = $this->db->num_rows($resql);
4678 $obj = $this->db->fetch_object($resql);
4680 $pu_ht = $obj->pu_ht;
4682 $total_ht = $obj->total_ht;
4684 $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
4685 $total_discount += $total_discount_line;
4691 //print $total_discount; exit;
4692 return price2num($total_discount);
4705 public function getTotalWeightVolume()
4709 // defined for shipment only
4711 // defined for shipment only
4714 foreach ($this->lines as $line) {
4715 if (isset($line->qty_asked)) {
4716 if (empty($totalOrdered)) {
4717 $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
4719 $totalOrdered += $line->qty_asked; // defined for shipment only
4721 if (isset($line->qty_shipped)) {
4722 if (empty($totalToShip)) {
4723 $totalToShip = 0; // Avoid warning because $totalToShip is ''
4725 $totalToShip += $line->qty_shipped; // defined for shipment only
4726 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4727 if (empty($totalToShip)) {
4730 $totalToShip += $line->qty; // defined for reception only
4733 // Define qty, weight, volume, weight_units, volume_units
4734 if ($this->element == 'shipping') {
4736 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4738 $qty = $line->qty ? $line->qty : 0;
4741 $weight = !empty($line->weight) ? $line->weight : 0;
4742 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
4743 $volume = !empty($line->volume) ? $line->volume : 0;
4744 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
4746 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
4747 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
4748 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
4749 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
4753 if (!empty($weight_units)) {
4754 $weightUnit = $weight_units;
4756 if (!empty($volume_units)) {
4757 $volumeUnit = $volume_units;
4760 if (empty($totalWeight)) {
4761 $totalWeight = 0; // Avoid warning because $totalWeight is ''
4763 if (empty($totalVolume)) {
4764 $totalVolume = 0; // Avoid warning because $totalVolume is ''
4767 //var_dump($line->volume_units);
4768 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4769 $trueWeightUnit = pow(10, $weightUnit);
4770 $totalWeight += $weight * $qty * $trueWeightUnit;
4772 if ($weight_units == 99) {
4773 // conversion 1 Pound = 0.45359237 KG
4774 $trueWeightUnit = 0.45359237;
4775 $totalWeight += $weight * $qty * $trueWeightUnit;
4776 } elseif ($weight_units == 98) {
4777 // conversion 1 Ounce = 0.0283495 KG
4778 $trueWeightUnit = 0.0283495;
4779 $totalWeight += $weight * $qty * $trueWeightUnit;
4781 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
4784 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
4785 //print $line->volume."x
".$line->volume_units."x
".($line->volume_units < 50)."x
".$volumeUnit;
4786 $trueVolumeUnit = pow(10, $volumeUnit);
4787 //print $line->volume;
4788 $totalVolume += $volume * $qty * $trueVolumeUnit;
4790 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
4794 return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
4803 public function setExtraParameters()
4807 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
4809 $sql = "UPDATE
".$this->db->prefix().$this->table_element;
4810 $sql .= " SET extraparams =
".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
4811 $sql .= " WHERE
rowid =
".((int) $this->id);
4814 $resql = $this->db->query($sql);
4816 $this->error = $this->db->lasterror();
4817 $this->db->rollback();
4820 $this->db->commit();
4826 // --------------------
4827 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
4828 // --------------------
4830 /* This is to show add lines */
4841 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
4843 global $conf, $user, $langs, $object, $hookmanager, $extrafields;
4847 if (!is_object($extrafields)) {
4848 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4849 $extrafields = new ExtraFields($this->db);
4851 $extrafields->fetch_name_optionals_label($this->table_element_line);
4853 // Output template part (modules that overwrite templates must declare this into descriptor)
4854 // Use global variables + $dateSelector + $seller and $buyer
4855 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
4856 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4857 foreach ($dirtpls as $module => $reldir) {
4858 if (!empty($module)) {
4859 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
4861 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
4864 if (empty($conf->file->strict_mode)) {
4865 $res = @include $tpl;
4867 $res = include $tpl; // for debug
4877 /* This is to show array of line of details */
4894 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
4896 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
4897 // TODO We should not use global var for this
4898 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
4900 // Define usemargins
4902 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
4906 $num = count($this->lines);
4909 if (!is_object($extrafields)) {
4910 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4911 $extrafields = new ExtraFields($this->db);
4913 $extrafields->fetch_name_optionals_label($this->table_element_line);
4915 $parameters = array('num'=>$num, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$this->table_element_line);
4916 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4917 if (empty($reshook)) {
4918 // Output template part (modules that overwrite templates must declare this into descriptor)
4919 // Use global variables + $dateSelector + $seller and $buyer
4920 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
4921 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
4922 foreach ($dirtpls as $module => $reldir) {
4924 if (!empty($module)) {
4925 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
4927 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
4929 if (file_exists($tpl)) {
4930 if (empty($conf->file->strict_mode)) {
4931 $res = @include $tpl;
4933 $res = include $tpl; // for debug
4945 foreach ($this->lines as $line) {
4947 $line->fetch_optionals();
4949 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
4950 if (is_object($hookmanager)) { // Old code is commented on preceding line.
4951 if (empty($line->fk_parent_line)) {
4952 $parameters = array('line'=>$line, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'table_element_line'=>$line->table_element);
4953 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4955 $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);
4956 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4959 if (empty($reshook)) {
4960 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
4985 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
4987 global $conf, $langs, $user, $object, $hookmanager;
4989 global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
4991 $object_rights = $this->getRights();
4993 $element = $this->element;
4998 // Line in view mode
4999 if ($action != 'editline' || $selected != $line->id) {
5001 if (!empty($line->fk_product) && $line->fk_product > 0) {
5002 $product_static = new Product($this->db);
5003 $product_static->fetch($line->fk_product);
5005 $product_static->ref = $line->ref; //can change ref in hook
5006 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5008 $text = $product_static->getNomUrl(1);
5010 // Define output language and label
5011 if (getDolGlobalInt('MAIN_MULTILANGS')) {
5012 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5013 dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5017 $prod = new Product($this->db);
5018 $prod->fetch($line->fk_product);
5020 $outputlangs = $langs;
5022 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5023 $newlang = GETPOST('lang_id', 'aZ09');
5025 if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang) && is_object($this->thirdparty)) {
5026 $newlang = $this->thirdparty->default_lang; // To use language of customer
5028 if (!empty($newlang)) {
5029 $outputlangs = new Translate("", $conf);
5030 $outputlangs->setDefaultLang($newlang);
5033 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label
"])) ? $prod->multilangs[$outputlangs->defaultlang]["label
"] : $line->product_label;
5035 $label = $line->product_label;
5038 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5039 $description .= (getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE') ? '' : (!empty($line->description) ? dol_htmlentitiesbr($line->description) : '')); // Description is what to show on popup. We shown nothing if already into desc.
5042 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5044 // Output template part (modules that overwrite templates must declare this into descriptor)
5045 // Use global variables + $dateSelector + $seller and $buyer
5046 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5047 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5048 foreach ($dirtpls as $module => $reldir) {
5050 if (!empty($module)) {
5051 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5053 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5055 if (file_exists($tpl)) {
5056 if (empty($conf->file->strict_mode)) {
5057 $res = @include $tpl;
5059 $res = include $tpl; // for debug
5068 // Line in update mode
5069 if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) {
5070 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5072 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5074 // Output template part (modules that overwrite templates must declare this into descriptor)
5075 // Use global variables + $dateSelector + $seller and $buyer
5076 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5077 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5078 foreach ($dirtpls as $module => $reldir) {
5079 if (!empty($module)) {
5080 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5082 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5085 if (empty($conf->file->strict_mode)) {
5086 $res = @include $tpl;
5088 $res = include $tpl; // for debug
5098 /* This is to show array of line of details of source object */
5111 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5113 global $langs, $hookmanager, $conf, $form, $action;
5115 print '<tr class="liste_titre
">';
5116 print '<td class="linecolref
">'.$langs->trans('Ref').'</td>';
5117 print '<td class="linecoldescription
">'.$langs->trans('Description').'</td>';
5118 print '<td class="linecolvat right
">'.$langs->trans('VATRate').'</td>';
5119 print '<td class="linecoluht right
">'.$langs->trans('PriceUHT').'</td>';
5120 if (isModEnabled("multicurrency
")) {
5121 print '<td class="linecoluht_currency right
">'.$langs->trans('PriceUHTCurrency').'</td>';
5123 print '<td class="linecolqty right
">'.$langs->trans('Qty').'</td>';
5124 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5125 print '<td class="linecoluseunit left
">'.$langs->trans('Unit').'</td>';
5127 print '<td class="linecoldiscount right
">'.$langs->trans('ReductionShort').'</td>';
5128 print '<td class="linecolht right
">'.$langs->trans('TotalHT').'</td>';
5129 print '<td class="center
">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5133 if (!empty($this->lines)) {
5134 foreach ($this->lines as $line) {
5136 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5137 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5138 $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
5139 if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
5140 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5142 if (empty($reshook)) {
5143 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5164 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5166 global $langs, $conf;
5169 if (!empty($line->date_start)) {
5170 $date_start = $line->date_start;
5172 $date_start = $line->date_debut_prevue;
5173 if ($line->date_debut_reel) {
5174 $date_start = $line->date_debut_reel;
5177 if (!empty($line->date_end)) {
5178 $date_end = $line->date_end;
5180 $date_end = $line->date_fin_prevue;
5181 if ($line->date_fin_reel) {
5182 $date_end = $line->date_fin_reel;
5186 $this->tpl['id'] = $line->id;
5188 $this->tpl['label'] = '';
5189 if (!empty($line->fk_parent_line)) {
5190 $this->tpl['label'] .= img_picto('', 'rightarrow');
5193 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5194 $discount = new DiscountAbsolute($this->db);
5195 $discount->fk_soc = $this->socid;
5196 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5197 } elseif (!empty($line->fk_product)) {
5198 $productstatic = new Product($this->db);
5199 $productstatic->id = $line->fk_product;
5200 $productstatic->ref = $line->ref;
5201 $productstatic->type = $line->fk_product_type;
5202 if (empty($productstatic->ref)) {
5203 $line->fetch_product();
5204 $productstatic = $line->product;
5207 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5208 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5210 if ($line->product_type == 1 && ($date_start || $date_end)) {
5211 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5214 $this->tpl['label'] .= ($line->product_type == -1 ? ' ' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5215 if (!empty($line->desc)) {
5216 $this->tpl['label'] .= $line->desc;
5218 $this->tpl['label'] .= ($line->label ? ' '.$line->label : '');
5222 if ($line->product_type == 1 && ($date_start || $date_end)) {
5223 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5227 if (!empty($line->desc)) {
5228 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5229 $discount = new DiscountAbsolute($this->db);
5230 $discount->fetch($line->fk_remise_except);
5231 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote
", $discount->getNomUrl(0));
5232 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5233 $discount = new DiscountAbsolute($this->db);
5234 $discount->fetch($line->fk_remise_except);
5235 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit
", $discount->getNomUrl(0));
5236 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5237 $discount = new DiscountAbsolute($this->db);
5238 $discount->fetch($line->fk_remise_except);
5239 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived
", $discount->getNomUrl(0));
5240 } elseif ($line->desc == '(EXCESS PAID)') {
5241 $discount = new DiscountAbsolute($this->db);
5242 $discount->fetch($line->fk_remise_except);
5243 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid
", $discount->getNomUrl(0));
5245 $this->tpl['description'] = dol_trunc($line->desc, 60);
5248 $this->tpl['description'] = ' ';
5252 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5253 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5254 if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) {
5255 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5258 $this->tpl['price'] = price($line->subprice);
5259 $this->tpl['total_ht'] = price($line->total_ht);
5260 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5261 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' ';
5262 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5263 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5265 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' ';
5267 // Is the line strike or not
5268 $this->tpl['strike'] = 0;
5269 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5270 $this->tpl['strike'] = 1;
5273 // Output template part (modules that overwrite templates must declare this into descriptor)
5274 // Use global variables + $dateSelector + $seller and $buyer
5275 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5276 foreach ($dirtpls as $module => $reldir) {
5277 if (!empty($module)) {
5278 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5280 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5283 if (empty($conf->file->strict_mode)) {
5284 $res = @include $tpl;
5286 $res = include $tpl; // for debug
5295 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5306 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5311 $sql = "INSERT INTO
".$this->db->prefix()."element_resources (
";
5312 $sql .= "resource_id
";
5313 $sql .= ", resource_type
";
5314 $sql .= ", element_id
";
5315 $sql .= ", element_type
";
5317 $sql .= ", mandatory
";
5318 $sql .= ") VALUES (
";
5319 $sql .= $resource_id;
5320 $sql .= ",
'".$this->db->escape($resource_type)."'";
5321 $sql .= ",
'".$this->db->escape($this->id)."'";
5322 $sql .= ",
'".$this->db->escape($this->element)."'";
5323 $sql .= ",
'".$this->db->escape($busy)."'";
5324 $sql .= ",
'".$this->db->escape($mandatory)."'";
5328 if ($this->db->query($sql)) {
5329 $this->db->commit();
5332 $this->error = $this->db->lasterror();
5333 $this->db->rollback();
5338 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5347 public function delete_resource($rowid, $element, $notrigger = 0)
5354 $sql = "DELETE FROM
".$this->db->prefix()."element_resources
";
5355 $sql .= " WHERE
rowid =
".((int) $rowid);
5359 $resql = $this->db->query($sql);
5361 $this->error = $this->db->lasterror();
5362 $this->db->rollback();
5366 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5368 $this->db->rollback();
5372 $this->db->commit();
5383 public function __clone()
5385 // Force a copy of this->lines, otherwise it will point to same object.
5386 if (isset($this->lines) && is_array($this->lines)) {
5387 $nboflines = count($this->lines);
5388 for ($i = 0; $i < $nboflines; $i++) {
5389 $this->lines[$i] = clone $this->lines[$i];
5407 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5409 global $conf, $langs, $user, $hookmanager, $action;
5411 $srctemplatepath = '';
5413 $parameters = array('modelspath'=>$modelspath, 'modele'=>$modele, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'hidedesc'=>$hidedesc, 'hideref'=>$hideref, 'moreparams'=>$moreparams);
5414 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5416 if (empty($reshook)) {
5417 dol_syslog("commonGenerateDocument modele=
".$modele." outputlangs->defaultlang=
".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5419 if (empty($modele)) {
5420 $this->error = 'BadValueForParameterModele';
5424 // Increase limit for PDF build
5425 $err = error_reporting();
5427 @set_time_limit(120);
5428 error_reporting($err);
5430 // If selected model is a filename template (then $modele="modelname
" or "modelname:filename
")
5431 $tmp = explode(':', $modele, 2);
5432 if (!empty($tmp[1])) {
5434 $srctemplatepath = $tmp[1];
5437 // Search template files
5441 $dirmodels = array('/');
5442 if (is_array($conf->modules_parts['models'])) {
5443 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5445 foreach ($dirmodels as $reldir) {
5446 foreach (array('doc', 'pdf') as $prefix) {
5447 if (in_array(get_class($this), array('Adherent'))) {
5448 // Member module use prefix_modele.class.php
5449 $file = $prefix."_
".$modele.".class.php
";
5451 // Other module use prefix_modele.modules.php
5452 $file = $prefix."_
".$modele.".modules.php
";
5455 // On verifie l'emplacement du modele
5456 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5457 if (file_exists($file)) {
5459 $classname = $prefix.'_'.$modele;
5468 // If generator was found
5470 global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after.
5474 $obj = new $classname($this->db);
5476 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5477 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5478 $varfortemplatedir = $obj->scandir;
5479 if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) {
5480 $dirtoscan = $conf->global->$varfortemplatedir;
5482 $listoffiles = array();
5484 // Now we add first model found in directories scanned
5485 $listofdir = explode(',', $dirtoscan);
5486 foreach ($listofdir as $key => $tmpdir) {
5487 $tmpdir = trim($tmpdir);
5488 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5490 unset($listofdir[$key]);
5493 if (is_dir($tmpdir)) {
5494 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5495 if (count($tmpfiles)) {
5496 $listoffiles = array_merge($listoffiles, $tmpfiles);
5501 if (count($listoffiles)) {
5502 foreach ($listoffiles as $record) {
5503 $srctemplatepath = $record['fullname'];
5509 if (empty($srctemplatepath)) {
5510 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5515 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5516 if (!dol_is_file($srctemplatepath)) {
5517 dol_syslog("Failed to locate
template file
".$srctemplatepath, LOG_WARNING);
5518 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5523 // We save charset_output to restore it because write_file can change it if needed for
5524 // output format that does not support UTF8.
5525 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5527 if (in_array(get_class($this), array('Adherent'))) {
5528 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5530 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5532 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5534 if ($resultwritefile > 0) {
5535 $outputlangs->charset_output = $sav_charset_output;
5537 // We delete old preview
5538 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5539 dol_delete_preview($this);
5541 // Index file in database
5542 if (!empty($obj->result['fullpath'])) {
5543 $destfull = $obj->result['fullpath'];
5545 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5546 $update_main_doc_field = 0;
5547 if (!empty($obj->update_main_doc_field)) {
5548 $update_main_doc_field = 1;
5551 $this->indexFile($destfull, $update_main_doc_field);
5553 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);
5556 // Success in building document. We build meta file.
5557 dol_meta_create($this);
5561 $outputlangs->charset_output = $sav_charset_output;
5562 $this->error = $obj->error;
5563 $this->errors = $obj->errors;
5564 dol_syslog("Error generating document
for ".__CLASS__.". Error:
".$obj->error, LOG_ERR);
5569 $this->error = $langs->trans("Error
").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5570 $this->errors[] = $this->error;
5571 dol_syslog($this->error, LOG_ERR);
5573 $this->error = $langs->trans("Error
")." ".$langs->trans("ErrorFileDoesNotExists
", $filefound);
5574 $this->errors[] = $this->error;
5575 dol_syslog($this->error, LOG_ERR);
5593 public function indexFile($destfull, $update_main_doc_field)
5595 global $conf, $user;
5597 $upload_dir = dirname($destfull);
5598 $destfile = basename($destfull);
5599 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5601 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5602 $filename = basename($destfile);
5603 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5604 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5606 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5607 $ecmfile = new EcmFiles($this->db);
5608 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5610 // Set the public "share
" key
5611 $setsharekey = false;
5612 if ($this->element == 'propal' || $this->element == 'proposal') {
5613 if (!isset($conf->global->PROPOSAL_ALLOW_ONLINESIGN) || !empty($conf->global->PROPOSAL_ALLOW_ONLINESIGN)) {
5614 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5616 if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5617 $setsharekey = true;
5620 if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
5621 $setsharekey = true;
5623 if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
5624 $setsharekey = true;
5626 if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
5627 $setsharekey = true;
5629 if ($this->element == 'product' && !empty($conf->global->PRODUCT_ALLOW_EXTERNAL_DOWNLOAD)) {
5630 $setsharekey = true;
5632 if ($this->element == 'contrat' && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) {
5633 $setsharekey = true;
5635 if ($this->element == 'fichinter' && !empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD)) {
5636 $setsharekey = true;
5638 if ($this->element == 'supplier_proposal' && !empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
5639 $setsharekey = true;
5643 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5644 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5645 $ecmfile->share = getRandomPassword(true);
5650 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5651 $ecmfile->fullpath_orig = '';
5652 $ecmfile->gen_or_uploaded = 'generated';
5653 $ecmfile->description = ''; // indexed content
5654 $ecmfile->keywords = ''; // keyword content
5655 $result = $ecmfile->update($user);
5657 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5661 $ecmfile->entity = $conf->entity;
5662 $ecmfile->filepath = $rel_dir;
5663 $ecmfile->filename = $filename;
5664 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5665 $ecmfile->fullpath_orig = '';
5666 $ecmfile->gen_or_uploaded = 'generated';
5667 $ecmfile->description = ''; // indexed content
5668 $ecmfile->keywords = ''; // keyword content
5669 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5670 $ecmfile->src_object_id = $this->id;
5672 $result = $ecmfile->create($user);
5674 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5679 /*$this->result['fullname']=$destfull;
5680 $this->result['filepath']=$ecmfile->filepath;
5681 $this->result['filename']=$ecmfile->filename;*/
5682 //var_dump($obj->update_main_doc_field);exit;
5684 if ($update_main_doc_field && !empty($this->table_element)) {
5685 $sql = "UPDATE
".$this->db->prefix().$this->table_element." SET last_main_doc =
'".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5686 $sql .= " WHERE
rowid =
".((int) $this->id);
5688 $resql = $this->db->query($sql);
5690 dol_print_error($this->db);
5693 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5708 public function addThumbs($file)
5710 global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
5712 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
5714 $file_osencoded = dol_osencode($file);
5715 if (file_exists($file_osencoded)) {
5716 // Create small thumbs for company (Ratio is near 16/9)
5717 // Used on logon for example
5718 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
5720 // Create mini thumbs for company (Ratio is near 16/9)
5721 // Used on menu or for setup page for example
5722 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
5727 /* Functions common to commonobject and commonobjectline */
5729 /* For default values */
5743 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
5745 global $conf, $_POST;
5747 // If param here has been posted, we use this value first.
5748 if (GETPOSTISSET($fieldname)) {
5749 return GETPOST($fieldname, 'alphanohtml', 3);
5752 if (isset($alternatevalue)) {
5753 return $alternatevalue;
5756 $newelement = $this->element;
5757 if ($newelement == 'facture') {
5758 $newelement = 'invoice';
5760 if ($newelement == 'commande') {
5761 $newelement = 'order';
5763 if (empty($newelement)) {
5764 dol_syslog("Ask a
default value
using common method getDefaultCreateValueForField on an
object with no property ->element defined. Return empty
string.
", LOG_WARNING);
5768 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
5769 //var_dump($keyforfieldname);
5770 if (isset($conf->global->$keyforfieldname)) {
5771 return $conf->global->$keyforfieldname;
5774 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
5781 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5792 public function call_trigger($triggerName, $user)
5795 global $langs, $conf;
5796 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
5797 dol_print_error('', 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_
" as required.');
5800 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers.
5801 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
5802 $langs = new Translate('', $conf);
5805 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
5806 $interface = new Interfaces($this->db);
5807 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
5810 if (!empty($this->errors)) {
5811 $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.
5813 $this->errors = $interface->errors;
5820 /* Functions for data in other language */
5830 public function fetchValuesForExtraLanguages()
5832 // To avoid SQL errors. Probably not the better solution though
5833 if (!$this->element) {
5836 if (!($this->id > 0)) {
5839 if (is_array($this->array_languages)) {
5843 $this->array_languages = array();
5845 $element = $this->element;
5846 if ($element == 'categorie') {
5847 $element = 'categories'; // For compatibility
5850 // Request to get translation values for object
5851 $sql = "SELECT
rowid, property, lang , value
";
5852 $sql .= " FROM
".$this->db->prefix()."object_lang
";
5853 $sql .= " WHERE type_object =
'".$this->db->escape($element)."'";
5854 $sql .= " AND fk_object =
".((int) $this->id);
5856 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
5857 $resql = $this->db->query($sql);
5859 $numrows = $this->db->num_rows($resql);
5862 while ($i < $numrows) {
5863 $obj = $this->db->fetch_object($resql);
5864 $key = $obj->property;
5865 $value = $obj->value;
5866 $codelang = $obj->lang;
5867 $type = $this->fields[$key]['type'];
5869 // we can add this attribute to object
5870 if (preg_match('/date/', $type)) {
5871 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
5873 $this->array_languages[$key][$codelang] = $value;
5880 $this->db->free($resql);
5888 dol_print_error($this->db);
5899 public function setValuesForExtraLanguages($onlykey = '')
5901 global $_POST, $langs;
5904 foreach ($_POST as $postfieldkey => $postfieldvalue) {
5905 $tmparray = explode('-', $postfieldkey);
5906 if ($tmparray[0] != 'field') {
5910 $element = $tmparray[1];
5911 $key = $tmparray[2];
5912 $codelang = $tmparray[3];
5913 //var_dump("postfieldkey=
".$postfieldkey." element=
".$element." key=
".$key." codelang=
".$codelang);
5915 if (!empty($onlykey) && $key != $onlykey) {
5918 if ($element != $this->element) {
5922 $key_type = $this->fields[$key]['type'];
5925 if (isset($this->fields[$key]['enabled'])) {
5926 $enabled = dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
5929 if (isset($this->fields[$key]['perms']))
5931 $perms = dol_eval($this->fields[$key]['perms'], 1, 1, '1');
5933 if (empty($enabled)) {
5936 //if (empty($perms)) continue;
5938 if (in_array($key_type, array('date'))) {
5940 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5941 $value_key = dol_mktime(0, 0, 0, GETPOST($postfieldkey."month
", 'int'), GETPOST($postfieldkey."day
", 'int'), GETPOST($postfieldkey."year
", 'int'));
5942 } elseif (in_array($key_type, array('datetime'))) {
5944 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
5945 $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'));
5946 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
5947 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
5948 if (!empty($value_arr)) {
5949 $value_key = implode(',', $value_arr);
5953 } elseif (in_array($key_type, array('price', 'double'))) {
5954 $value_arr = GETPOST($postfieldkey, 'alpha');
5955 $value_key = price2num($value_arr);
5957 $value_key = GETPOST($postfieldkey);
5958 if (in_array($key_type, array('link')) && $value_key == '-1') {
5963 $this->array_languages[$key][$codelang] = $value_key;
5965 /*if ($nofillrequired) {
5966 $langs->load('errors');
5967 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
5976 /* Functions for extrafields */
5984 public function fetchNoCompute($id)
5988 $savDisableCompute = $conf->disable_compute;
5989 $conf->disable_compute = 1;
5991 $ret = $this->fetch($id);
5993 $conf->disable_compute = $savDisableCompute;
5998 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6008 public function fetch_optionals($rowid = null, $optionsArray = null)
6011 global $conf, $extrafields;
6013 if (empty($rowid)) {
6016 if (empty($rowid) && isset($this->rowid)) {
6017 $rowid = $this->rowid; // deprecated
6020 // To avoid SQL errors. Probably not the better solution though
6021 if (!$this->table_element) {
6025 $this->array_options = array();
6027 if (!is_array($optionsArray)) {
6028 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6029 if (!isset($extrafields) || !is_object($extrafields)) {
6030 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6031 $extrafields = new ExtraFields($this->db);
6034 // Load array of extrafields for elementype = $this->table_element
6035 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6036 $extrafields->fetch_name_optionals_label($this->table_element);
6038 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6040 global $extrafields;
6041 dol_syslog("Warning:
fetch_optionals was called with param optionsArray defined when you should pass
null now
", LOG_WARNING);
6044 $table_element = $this->table_element;
6045 if ($table_element == 'categorie') {
6046 $table_element = 'categories'; // For compatibility
6049 // Request to get complementary values
6050 if (is_array($optionsArray) && count($optionsArray) > 0) {
6051 $sql = "SELECT
rowid";
6052 foreach ($optionsArray as $name => $label) {
6053 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate') {
6057 $sql .= " FROM
".$this->db->prefix().$table_element."_extrafields
";
6058 $sql .= " WHERE fk_object =
".((int) $rowid);
6060 //dol_syslog(get_class($this)."::
fetch_optionals get extrafields data
for ".$this->table_element, LOG_DEBUG); // Too verbose
6061 $resql = $this->db->query($sql);
6063 $numrows = $this->db->num_rows($resql);
6065 $tab = $this->db->fetch_array($resql);
6067 foreach ($tab as $key => $value) {
6068 // 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)
6069 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6070 // we can add this attribute to object
6071 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6072 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6073 $this->array_options["options_
".$key] = $this->db->jdate($value);
6075 $this->array_options["options_
".$key] = $value;
6078 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_
".$key]);
6083 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6084 // in the element's extrafields table)
6085 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6086 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6087 //var_dump($conf->disable_compute);
6088 if (empty($conf->disable_compute)) {
6089 $this->array_options["options_
".$key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '');
6094 $this->db->free($resql);
6102 $this->errors[]=$this->db->lasterror;
6115 public function deleteExtraFields()
6119 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6125 $table_element = $this->table_element;
6126 if ($table_element == 'categorie') {
6127 $table_element = 'categories'; // For compatibility
6132 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6134 $resql = $this->db->query($sql_del);
6136 $this->error = $this->db->lasterror();
6137 $this->db->rollback();
6140 $this->db->commit();
6155 public function insertExtraFields($trigger = '', $userused = null)
6157 global $conf, $langs, $user;
6159 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6163 if (empty($userused)) {
6169 if (!empty($this->array_options)) {
6171 $langs->load('admin');
6172 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6173 $extrafields = new ExtraFields($this->db);
6174 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6176 // Eliminate copied source object extra fields that do not exist in target object
6177 $new_array_options = array();
6178 foreach ($this->array_options as $key => $value) {
6179 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6180 $new_array_options[$key] = $value;
6181 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contains the 'options_' prefix
6182 $new_array_options['options_'.$key] = $value;
6186 foreach ($new_array_options as $key => $value) {
6187 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6188 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6189 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
6190 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6191 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6192 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6193 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6195 // If we clone, we have to clean unique extrafields to prevent duplicates.
6196 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6197 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6198 $new_array_options[$key] = null;
6201 // Similar code than into insertExtraFields
6202 if ($attributeRequired) {
6203 $mandatorypb = false;
6204 if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
6205 $mandatorypb = true;
6207 if ($this->array_options[$key] === '') {
6208 $mandatorypb = true;
6210 if ($attributeType == 'sellist' && $this->array_options[$key] == '0') {
6211 $mandatorypb = true;
6214 $langs->load("errors
");
6215 dol_syslog("Mandatory field
'".$key."' is empty during create and
set to required into definition of extrafields
");
6216 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6221 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6222 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6224 if (!empty($attrfieldcomputed)) {
6225 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6226 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6227 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6228 $new_array_options[$key] = $value;
6230 $new_array_options[$key] = null;
6234 switch ($attributeType) {
6236 if (!is_numeric($value) && $value != '') {
6237 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6239 } elseif ($value == '') {
6240 $new_array_options[$key] = null;
6245 $value = price2num($value);
6246 if (!is_numeric($value) && $value != '') {
6247 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." for ".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6248 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6250 } elseif ($value == '') {
6253 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6254 $new_array_options[$key] = $value;
6256 /*case 'select': // Not required, we chosed value='0' for undefined values
6259 $this->array_options[$key] = null;
6264 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6265 // If there is an encryption choice, we use it to crypt data before insert
6266 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6267 $algo = reset($tmparrays);
6269 //global $action; // $action may be 'create', 'update', 'update_extras'...
6270 //var_dump($action);
6271 //var_dump($this->oldcopy);exit;
6272 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
6273 //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
6274 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.
6275 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6278 $newvalue = dol_hash($this->array_options[$key], $algo);
6279 $new_array_options[$key] = $newvalue;
6282 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6285 } else // Common usage
6287 $new_array_options[$key] = $this->array_options[$key];
6292 // If data is a string instead of a timestamp, we convert it
6293 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6294 $this->array_options[$key] = strtotime($this->array_options[$key]);
6296 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6299 $param_list = array_keys($attributeParam['options']);
6302 $InfoFieldList = explode(":
", $param_list[0]);
6303 dol_include_once($InfoFieldList[1]);
6304 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6305 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6306 $new_array_options[$key] = '';
6308 $object = new $InfoFieldList[0]($this->db);
6309 if (is_numeric($value)) {
6310 $res = $object->fetch($value); // Common case
6312 $res = $object->fetch('', $value); // For compatibility
6316 $new_array_options[$key] = $object->id;
6318 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6319 $this->db->rollback();
6324 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6332 $table_element = $this->table_element;
6333 if ($table_element == 'categorie') {
6334 $table_element = 'categories'; // For compatibility
6337 dol_syslog(get_class($this)."::
insertExtraFields delete then insert
", LOG_DEBUG);
6339 $sql_del = "DELETE FROM
".$this->db->prefix().$table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6340 $this->db->query($sql_del);
6342 $sql = "INSERT INTO
".$this->db->prefix().$table_element."_extrafields (fk_object
";
6343 foreach ($new_array_options as $key => $value) {
6344 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6345 // Add field of attribut
6346 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6347 $sql .= ",
".$attributeKey;
6350 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6351 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6352 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6353 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6354 $sql .= ",
".$tmpkey;
6358 $sql .= ") VALUES (
".$this->id;
6360 foreach ($new_array_options as $key => $value) {
6361 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6362 // Add field of attribute
6363 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator)
6364 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6365 $sql .= ",
'".$this->db->escape($new_array_options[$key])."'";
6371 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6372 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6373 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6374 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6375 if (in_array($tmpval, array('int', 'double', 'price'))) {
6386 $resql = $this->db->query($sql);
6388 $this->error = $this->db->lasterror();
6392 if (!$error && $trigger) {
6394 $this->context = array('extrafieldaddupdate'=>1);
6395 $result = $this->call_trigger($trigger, $userused);
6403 $this->db->rollback();
6406 $this->db->commit();
6424 public function insertExtraLanguages($trigger = '', $userused = null)
6426 global $conf, $langs, $user;
6428 if (empty($userused)) {
6434 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6435 return 0; // For avoid conflicts if trigger used
6438 if (is_array($this->array_languages)) {
6439 $new_array_languages = $this->array_languages;
6441 foreach ($new_array_languages as $key => $value) {
6442 $attributeKey = $key;
6443 $attributeType = $this->fields[$attributeKey]['type'];
6444 $attributeLabel = $this->fields[$attributeKey]['label'];
6446 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6447 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6449 switch ($attributeType) {
6451 if (!is_numeric($value) && $value != '') {
6452 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6454 } elseif ($value == '') {
6455 $new_array_languages[$key] = null;
6459 $value = price2num($value);
6460 if (!is_numeric($value) && $value != '') {
6461 dol_syslog($langs->trans("ExtraLanguageHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6462 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue
", $attributeLabel);
6464 } elseif ($value == '') {
6465 $new_array_languages[$key] = null;
6467 $new_array_languages[$key] = $value;
6470 /*case 'select': // Not required, we chosed value='0' for undefined values
6473 $this->array_options[$key] = null;
6481 $table_element = $this->table_element;
6482 if ($table_element == 'categorie') {
6483 $table_element = 'categories'; // For compatibility
6488 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6489 foreach ($langcodearray as $langcode => $value) {
6490 $sql_del = "DELETE FROM
".$this->db->prefix()."object_lang
";
6491 $sql_del .= " WHERE fk_object =
".((int) $this->id)." AND property =
'".$this->db->escape($key)."' AND type_object =
'".$this->db->escape($table_element)."'";
6492 $sql_del .= " AND lang =
'".$this->db->escape($langcode)."'";
6493 $this->db->query($sql_del);
6495 if ($value !== '') {
6496 $sql = "INSERT INTO
".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value
";
6497 $sql .= ") VALUES (
".$this->id.",
'".$this->db->escape($key)."',
'".$this->db->escape($table_element)."',
'".$this->db->escape($langcode)."',
'".$this->db->escape($value)."'";
6500 $resql = $this->db->query($sql);
6502 $this->error = $this->db->lasterror();
6510 if (!$error && $trigger) {
6512 $this->context = array('extralanguagesaddupdate'=>1);
6513 $result = $this->call_trigger($trigger, $userused);
6521 $this->db->rollback();
6524 $this->db->commit();
6542 public function updateExtraField($key, $trigger = null, $userused = null)
6544 global $conf, $langs, $user;
6546 if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
6550 if (empty($userused)) {
6556 if (!empty($this->array_options) && isset($this->array_options["options_
".$key])) {
6558 $langs->load('admin');
6559 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6560 $extrafields = new ExtraFields($this->db);
6561 $extrafields->fetch_name_optionals_label($this->table_element);
6563 $value = $this->array_options["options_
".$key];
6565 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6566 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6567 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6568 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6569 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6571 // Similar code than into insertExtraFields
6572 if ($attributeRequired) {
6573 $mandatorypb = false;
6574 if ($attributeType == 'link' && $this->array_options["options_
".$key] == '-1') {
6575 $mandatorypb = true;
6577 if ($this->array_options["options_
".$key] === '') {
6578 $mandatorypb = true;
6581 $langs->load("errors
");
6582 dol_syslog("Mandatory field
'options_".$key."' is empty during update and
set to required into definition of extrafields
");
6583 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6588 //dol_syslog("attributeLabel=
".$attributeLabel, LOG_DEBUG);
6589 //dol_syslog("attributeType=
".$attributeType, LOG_DEBUG);
6591 if (!empty($attrfieldcomputed)) {
6592 if (!empty($conf->global->MAIN_STORE_COMPUTED_EXTRAFIELDS)) {
6593 $value = dol_eval($attrfieldcomputed, 1, 0, '');
6594 dol_syslog($langs->trans("Extrafieldcomputed
")." sur
".$attributeLabel."(
".$value.")
", LOG_DEBUG);
6595 $this->array_options["options_
".$key] = $value;
6597 $this->array_options["options_
".$key] = null;
6601 switch ($attributeType) {
6603 if (!is_numeric($value) && $value != '') {
6604 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6606 } elseif ($value === '') {
6607 $this->array_options["options_
".$key] = null;
6611 $value = price2num($value);
6612 if (!is_numeric($value) && $value != '') {
6613 dol_syslog($langs->trans("ExtraFieldHasWrongValue
")." sur
".$attributeLabel."(
".$value."is not
'".$attributeType."')
", LOG_DEBUG);
6614 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue
", $attributeLabel);
6616 } elseif ($value === '') {
6619 //dol_syslog("double value
"." sur
".$attributeLabel."(
".$value." is
'".$attributeType."')
", LOG_DEBUG);
6620 $this->array_options["options_
".$key] = $value;
6622 /*case 'select': // Not required, we chosed value='0' for undefined values
6625 $this->array_options[$key] = null;
6629 $this->array_options["options_
".$key] = price2num($this->array_options["options_
".$key]);
6633 if (empty($this->array_options["options_
".$key])) {
6634 $this->array_options["options_
".$key] = null;
6636 $this->array_options["options_
".$key] = $this->db->idate($this->array_options["options_
".$key]);
6640 if (empty($this->array_options["options_
".$key])) {
6641 $this->array_options["options_
".$key] = null;
6646 $param_list = array_keys($attributeParam['options']);
6649 $InfoFieldList = explode(":
", $param_list[0]);
6650 dol_include_once($InfoFieldList[1]);
6651 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
6653 if ($value == '-1') // -1 is key for no defined in combo list of objects
6655 $new_array_options[$key] = '';
6657 $object = new $InfoFieldList[0]($this->db);
6658 if (is_numeric($value)) $res = $object->fetch($value); // Common case
6659 else $res = $object->fetch('', $value); // For compatibility
6661 if ($res > 0) $new_array_options[$key] = $object->id;
6663 $this->error = "Id/Ref
'".$value."' for object '".$object->element."' not found
";
6664 $this->db->rollback();
6669 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6677 $linealreadyfound = 0;
6679 // 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)
6680 $sql = "SELECT COUNT(
rowid) as nb FROM
".$this->db->prefix().$this->table_element."_extrafields WHERE fk_object =
".((int) $this->id);
6681 $resql = $this->db->query($sql);
6683 $tmpobj = $this->db->fetch_object($resql);
6685 $linealreadyfound = $tmpobj->nb;
6689 if ($linealreadyfound) {
6690 if ($this->array_options["options_
".$key] === null) {
6691 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
null";
6693 $sql = "UPDATE
".$this->db->prefix().$this->table_element."_extrafields SET
".$key." =
'".$this->db->escape($this->array_options["options_".$key])."'";
6695 $sql .= " WHERE fk_object =
".((int) $this->id);
6697 $result = $this->insertExtraFields('', $user);
6703 $resql = $this->db->query($sql);
6706 $this->error = $this->db->lasterror();
6708 if (!$error && $trigger) {
6710 $this->context = array('extrafieldupdate'=>1);
6711 $result = $this->call_trigger($trigger, $userused);
6719 dol_syslog(__METHOD__.$this->error, LOG_ERR);
6720 $this->db->rollback();
6723 $this->db->commit();
6741 public function updateExtraLanguages($key, $trigger = null, $userused = null)
6743 global $conf, $langs, $user;
6745 if (empty($userused)) {
6751 if (!empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) {
6752 return 0; // For avoid conflicts if trigger used
6773 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
6775 global $conf, $langs, $form;
6777 if (!is_object($form)) {
6778 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6779 $form = new Form($this->db);
6782 if (!empty($this->fields)) {
6783 $val = $this->fields[$key];
6786 // Validation tests and output
6787 $fieldValidationErrorMsg = '';
6788 $validationClass = '';
6789 $fieldValidationErrorMsg = $this->getFieldError($key);
6790 if (!empty($fieldValidationErrorMsg)) {
6791 $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
6793 $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
6800 $param['options'] = array();
6802 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
6803 // Because we work on extrafields
6804 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6805 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6807 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6808 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6810 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
6811 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6813 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6814 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
6816 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
6817 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
6819 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
6820 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
6822 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
6823 $param['options'] = array($reg[1] => 'N');
6825 } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
6826 $param['options'] = array();
6829 } elseif (preg_match('/varchar/', $val['type'])) {
6830 $param['options'] = array();
6833 $param['options'] = array();
6834 $type = $this->fields[$key]['type'];
6837 // Special case that force options and type ($type can be integer, varchar, ...)
6838 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
6839 $param['options'] = $this->fields[$key]['arrayofkeyval'];
6843 $label = $this->fields[$key]['label'];
6844 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
6845 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
6846 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
6847 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
6848 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
6849 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
6851 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
6852 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
6853 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
6855 $objectid = $this->id;
6858 if (!preg_match('/^search_/', $keyprefix)) {
6859 return '<span class="opacitymedium
">'.$langs->trans("AutomaticallyCalculated
").'</span>';
6865 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
6866 if (empty($morecss) && !empty($val['css'])) {
6867 $morecss = $val['css'];
6868 } elseif (empty($morecss)) {
6869 if ($type == 'date') {
6870 $morecss = 'minwidth100imp';
6871 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
6872 $morecss = 'minwidth200imp';
6873 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6874 $morecss = 'maxwidth75';
6875 } elseif ($type == 'url') {
6876 $morecss = 'minwidth400';
6877 } elseif ($type == 'boolean') {
6880 if (round($size) < 12) {
6881 $morecss = 'minwidth100';
6882 } elseif (round($size) <= 48) {
6883 $morecss = 'minwidth200';
6885 $morecss = 'minwidth400';
6890 // Add validation state class
6891 if (!empty($validationClass)) {
6892 $morecss.= $validationClass;
6895 if (in_array($type, array('date'))) {
6896 $tmp = explode(',', $size);
6900 // Do not show current date when field not required (see selectDate() method)
6901 if (!$required && $value == '') {
6905 // TODO Must also support $moreparam
6906 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
6907 } elseif (in_array($type, array('datetime'))) {
6908 $tmp = explode(',', $size);
6912 // Do not show current date when field not required (see selectDate() method)
6913 if (!$required && $value == '') $value = '-1';
6915 // TODO Must also support $moreparam
6916 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
6917 } elseif (in_array($type, array('duration'))) {
6918 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
6919 } elseif (in_array($type, array('int', 'integer'))) {
6920 $tmp = explode(',', $size);
6922 $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' : '').'>';
6923 } elseif (in_array($type, array('real'))) {
6924 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6925 } elseif (preg_match('/varchar/', $type)) {
6926 $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' : '').'>';
6927 } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
6928 $out = '<input type="text
" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
6929 } elseif (preg_match('/^text/', $type)) {
6930 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6931 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6932 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
6933 $out = $doleditor->Create(1);
6935 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6937 } elseif (preg_match('/^html/', $type)) {
6938 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
6939 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
6940 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
6941 $out = $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
6943 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
6945 } elseif ($type == 'boolean') {
6947 if (!empty($value)) {
6948 $checked = ' checked value="1
" ';
6950 $checked = ' value="1
" ';
6952 $out = '<input type="checkbox
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
6953 } elseif ($type == 'price') {
6954 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6955 $value = price($value);
6957 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
6958 } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
6959 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
6960 $value = price($value);
6962 $out = '<input type="text
" class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
6963 } elseif ($type == 'select') {
6965 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6966 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6967 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6970 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6971 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
6972 $out .= '<option value="0
"> </option>';
6974 foreach ($param['options'] as $keyb => $valb) {
6975 if ((string) $keyb == '') {
6978 if (strpos($valb, "|
") !== false) {
6979 list($valb, $parent) = explode('|', $valb);
6981 $out .= '<option value="'.$keyb.'"';
6982 $out .= (((string) $value == (string) $keyb) ? ' selected' : '');
6983 $out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
6984 $out .= '>'.$valb.'</option>';
6986 $out .= '</select>';
6987 } elseif ($type == 'sellist') {
6989 if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
6990 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6991 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
6994 $out .= '<select class="flat
'.$morecss.' maxwidthonsmartphone
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
6995 if (is_array($param['options'])) {
6996 $param_list = array_keys($param['options']);
6997 $InfoFieldList = explode(":
", $param_list[0]);
7001 // 1 : label field name
7002 // 2 : key fields name (if differ of rowid)
7003 // 3 : key field parent (for dependent lists)
7004 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7005 // 5 : id category type
7006 // 6 : ids categories list separated by comma for category root
7007 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7009 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7010 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7011 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7013 $keyList = $InfoFieldList[2].' as rowid';
7016 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7017 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7018 $keyList .= ', '.$parentField;
7021 $filter_categorie = false;
7022 if (count($InfoFieldList) > 5) {
7023 if ($InfoFieldList[0] == 'categorie') {
7024 $filter_categorie = true;
7028 if ($filter_categorie === false) {
7029 $fields_label = explode('|', $InfoFieldList[1]);
7030 if (is_array($fields_label)) {
7032 $keyList .= implode(', ', $fields_label);
7036 $sql = "SELECT
" . $keyList;
7037 $sql .= " FROM
" . $this->db->prefix() . $InfoFieldList[0];
7038 if (!empty($InfoFieldList[4])) {
7039 // can use SELECT request
7040 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7041 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7044 // current object id can be use into filter
7045 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7046 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7048 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7051 //We have to join on extrafield table
7052 if (strpos($InfoFieldList[4], 'extra') !== false) {
7053 $sql .= " as main,
" . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra
";
7054 $sqlwhere .= " WHERE extra.fk_object=main.
" . $InfoFieldList[2] . " AND
" . $InfoFieldList[4];
7056 $sqlwhere .= " WHERE
" . $InfoFieldList[4];
7059 $sqlwhere .= ' WHERE 1=1';
7061 // Some tables may have field, some other not. For the moment we disable it.
7062 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7063 $sqlwhere .= " AND entity =
" . ((int) $conf->entity);
7068 $sql .= ' ORDER BY ' . implode(', ', $fields_label);
7070 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7071 $resql = $this->db->query($sql);
7073 $out .= '<option value="0
"> </option>';
7074 $num = $this->db->num_rows($resql);
7078 $obj = $this->db->fetch_object($resql);
7080 // Several field into label (eq table:code|libelle:rowid)
7082 $fields_label = explode('|', $InfoFieldList[1]);
7083 if (count($fields_label) > 1) {
7085 foreach ($fields_label as $field_toshow) {
7086 $labeltoshow .= $obj->$field_toshow . ' ';
7089 $labeltoshow = $obj->{$InfoFieldList[1]};
7091 $labeltoshow = dol_trunc($labeltoshow, 45);
7093 if ($value == $obj->rowid) {
7094 foreach ($fields_label as $field_toshow) {
7095 $translabel = $langs->trans($obj->$field_toshow);
7096 if ($translabel != $obj->$field_toshow) {
7097 $labeltoshow = dol_trunc($translabel) . ' ';
7099 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7102 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7105 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7106 if ($translabel != $obj->{$InfoFieldList[1]}) {
7107 $labeltoshow = dol_trunc($translabel, 18);
7109 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7112 if (empty($labeltoshow)) {
7113 $labeltoshow = '(not defined)';
7115 if ($value == $obj->rowid) {
7116 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7119 if (!empty($InfoFieldList[3]) && $parentField) {
7120 $parent = $parentName . ':' . $obj->{$parentField};
7124 $out .= '<option value="' . $obj->rowid . '"';
7125 $out .= ($value == $obj->rowid ? ' selected' : '');
7126 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7127 $out .= '>' . $labeltoshow . '</option>';
7132 $this->db->free($resql);
7134 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7137 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7138 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7139 $out .= '<option value="0
"> </option>';
7140 foreach ($data as $data_key => $data_value) {
7141 $out .= '<option value="' . $data_key . '"';
7142 $out .= ($value == $data_key ? ' selected' : '');
7143 $out .= '>' . $data_value . '</option>';
7147 $out .= '</select>';
7148 } elseif ($type == 'checkbox') {
7149 $value_arr = explode(',', $value);
7150 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, $morecss, 0, '100%');
7151 } elseif ($type == 'radio') {
7153 foreach ($param['options'] as $keyopt => $valopt) {
7154 $out .= '<input class="flat
'.$morecss.'" type="radio
" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7155 $out .= ' value="'.$keyopt.'"';
7156 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'"';
7157 $out .= ($value == $keyopt ? 'checked' : '');
7158 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_
'.$keyopt.'">'.$valopt.'</label><br>';
7160 } elseif ($type == 'chkbxlst') {
7161 if (is_array($value)) {
7162 $value_arr = $value;
7164 $value_arr = explode(',', $value);
7167 if (is_array($param['options'])) {
7168 $param_list = array_keys($param['options']);
7169 $InfoFieldList = explode(":
", $param_list[0]);
7173 // 1 : label field name
7174 // 2 : key fields name (if differ of rowid)
7175 // 3 : key field parent (for dependent lists)
7176 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7177 // 5 : id category type
7178 // 6 : ids categories list separated by comma for category root
7179 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7181 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7182 list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7183 $keyList .= ', '.$parentField;
7185 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7186 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7187 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7189 $keyList = $InfoFieldList[2].' as rowid';
7193 $filter_categorie = false;
7194 if (count($InfoFieldList) > 5) {
7195 if ($InfoFieldList[0] == 'categorie') {
7196 $filter_categorie = true;
7200 if ($filter_categorie === false) {
7201 $fields_label = explode('|', $InfoFieldList[1]);
7202 if (is_array($fields_label)) {
7204 $keyList .= implode(', ', $fields_label);
7208 $sql = "SELECT
" . $keyList;
7209 $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7210 if (!empty($InfoFieldList[4])) {
7211 // can use SELECT request
7212 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7213 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7216 // current object id can be use into filter
7217 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7218 $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
7220 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7223 // We have to join on extrafield table
7224 if (strpos($InfoFieldList[4], 'extra') !== false) {
7225 $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
7226 $sqlwhere .= " WHERE extra.fk_object=main.
" . $InfoFieldList[2] . " AND
" . $InfoFieldList[4];
7228 $sqlwhere .= " WHERE
" . $InfoFieldList[4];
7231 $sqlwhere .= ' WHERE 1=1';
7233 // Some tables may have field, some other not. For the moment we disable it.
7234 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7235 $sqlwhere .= " AND entity =
" . ((int) $conf->entity);
7237 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7241 dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
7242 $resql = $this->db->query($sql);
7244 $num = $this->db->num_rows($resql);
7251 $obj = $this->db->fetch_object($resql);
7254 // Several field into label (eq table:code|libelle:rowid)
7255 $fields_label = explode('|', $InfoFieldList[1]);
7256 if (count($fields_label) > 1) {
7258 foreach ($fields_label as $field_toshow) {
7259 $labeltoshow .= $obj->$field_toshow . ' ';
7262 $labeltoshow = $obj->{$InfoFieldList[1]};
7264 $labeltoshow = dol_trunc($labeltoshow, 45);
7266 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7267 foreach ($fields_label as $field_toshow) {
7268 $translabel = $langs->trans($obj->$field_toshow);
7269 if ($translabel != $obj->$field_toshow) {
7270 $labeltoshow = dol_trunc($translabel, 18) . ' ';
7272 $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
7276 $data[$obj->rowid] = $labeltoshow;
7279 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7280 if ($translabel != $obj->{$InfoFieldList[1]}) {
7281 $labeltoshow = dol_trunc($translabel, 18);
7283 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
7286 if (empty($labeltoshow)) {
7287 $labeltoshow = '(not defined)';
7290 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7291 $data[$obj->rowid] = $labeltoshow;
7294 if (!empty($InfoFieldList[3]) && $parentField) {
7295 $parent = $parentName . ':' . $obj->{$parentField};
7299 $data[$obj->rowid] = $labeltoshow;
7304 $this->db->free($resql);
7306 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
7308 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7311 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7312 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7313 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, $morecss, 0, '100%');
7316 } elseif ($type == 'link') {
7317 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
7318 $param_list_array = explode(':', $param_list[0]);
7319 $showempty = (($required && $default != '') ? 0 : 1);
7321 if (!preg_match('/search_/', $keyprefix)) {
7322 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7323 if (!empty($this->fields[$key]['picto'])) {
7324 $morecss .= ' widthcentpercentminusxx';
7326 $morecss .= ' widthcentpercentminusx';
7329 if (!empty($this->fields[$key]['picto'])) {
7330 $morecss .= ' widthcentpercentminusx';
7335 $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);
7337 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7338 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
".
7339 list($class, $classfile) = explode(':', $param_list[0]);
7340 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
7341 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
7343 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
7345 $paramforthenewlink = '';
7346 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
7347 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOST('id', 'int') : '');
7348 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
7349 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOST('originid', 'int') : '');
7350 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
7351 // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
7352 $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>';
7355 } elseif ($type == 'password') {
7356 // If prefix is 'search_', field is used as a filter, we use a common text field.
7357 $out = '<input type="'.($keyprefix == 'search_
' ? 'text
' : 'password
').'" class="flat
'.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7358 } elseif ($type == 'array') {
7360 $newval['type'] = 'varchar(256)';
7363 if (!empty($value)) {
7364 foreach ($value as $option) {
7365 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del
" href="javascript:;
"><span class="fa fa-minus-circle valignmiddle
"></span></a> ';
7366 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
7369 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add
" href="javascript:;
"><span class="fa fa-plus-circle valignmiddle
"></span></a>';
7371 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del
" href="javascript:;
"><span class="fa fa-minus-circle valignmiddle
"></span></a> ';
7372 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
7374 if (!empty($conf->use_javascript_ajax)) {
7377 $(document).ready(function() {
7378 $("a#
'.dol_escape_js($keyprefix.$key.$keysuffix).'_add
").click(function() {
7379 $("'.dol_escape_js($newInput).'").insertBefore(this);
7382 $(document).on("click
", "a.
'.dol_escape_js($keyprefix.$key.$keysuffix).'_del
", function() {
7383 $(this).parent().remove();
7389 if (!empty($hidden)) {
7390 $out = '<input type="hidden
" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
7393 if ($isDependList==1) {
7394 $out .= $this->getJSListDependancies('_common');
7397 if ($type == 'date') $out.=' (YYYY-MM-DD)';
7398 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
7401 // Display error message for field
7402 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
7403 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
7422 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
7424 global $conf, $langs, $form;
7426 if (!is_object($form)) {
7427 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7428 $form = new Form($this->db);
7431 $objectid = $this->id; // Not used ???
7433 $label = empty($val['label']) ? '' : $val['label'];
7434 $type = empty($val['type']) ? '' : $val['type'];
7435 $size = empty($val['css']) ? '' : $val['css'];
7438 // Convert var to be able to share same code than showOutputField of extrafields
7439 if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7440 $type = 'varchar'; // convert varchar(xx) int varchar
7442 } elseif (preg_match('/varchar/', $type)) {
7443 $type = 'varchar'; // convert varchar(xx) int varchar
7445 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7448 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7452 $default = empty($val['default']) ? '' : $val['default'];
7453 $computed = empty($val['computed']) ? '' : $val['computed'];
7454 $unique = empty($val['unique']) ? '' : $val['unique'];
7455 $required = empty($val['required']) ? '' : $val['required'];
7457 $param['options'] = array();
7459 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7460 $param['options'] = $val['arrayofkeyval'];
7462 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7464 $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7465 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7466 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7468 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7469 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7471 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7472 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7474 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
7475 $param['options'] = array($reg[1] => 'N');
7479 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
7480 $list = (empty($val['list']) ? '' : $val['list']);
7481 $help = (empty($val['help']) ? '' : $val['help']);
7482 $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)
7488 // If field is a computed field, value must become result of compute
7490 // Make the eval of compute string
7491 //var_dump($computed);
7492 $value = dol_eval($computed, 1, 0, '');
7495 if (empty($morecss)) {
7496 if ($type == 'date') {
7497 $morecss = 'minwidth100imp';
7498 } elseif ($type == 'datetime' || $type == 'timestamp') {
7499 $morecss = 'minwidth200imp';
7500 } elseif (in_array($type, array('int', 'double', 'price'))) {
7501 $morecss = 'maxwidth75';
7502 } elseif ($type == 'url') {
7503 $morecss = 'minwidth400';
7504 } elseif ($type == 'boolean') {
7507 if (is_numeric($size) && round($size) < 12) {
7508 $morecss = 'minwidth100';
7509 } elseif (is_numeric($size) && round($size) <= 48) {
7510 $morecss = 'minwidth200';
7512 $morecss = 'minwidth400';
7517 // Format output value differently according to properties of field
7518 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
7519 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.
7520 $value = $this->getNomUrl(1, '', 0, '', 1);
7522 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
7523 $value = $this->getLibStatut(3);
7524 } elseif ($type == 'date') {
7525 if (!empty($value)) {
7526 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
7530 } elseif ($type == 'datetime' || $type == 'timestamp') {
7531 if (!empty($value)) {
7532 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
7536 } elseif ($type == 'duration') {
7537 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
7538 if (!is_null($value) && $value !== '') {
7539 $value = convertSecondToTime($value, 'allhourmin');
7541 } elseif ($type == 'double' || $type == 'real') {
7542 if (!is_null($value) && $value !== '') {
7543 $value = price($value);
7545 } elseif ($type == 'boolean') {
7547 if (!empty($value)) {
7548 $checked = ' checked ';
7550 $value = '<input type="checkbox
" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
7551 } elseif ($type == 'mail' || $type == 'email') {
7552 $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
7553 } elseif ($type == 'url') {
7554 $value = dol_print_url($value, '_blank', 32, 1);
7555 } elseif ($type == 'phone') {
7556 $value = dol_print_phone($value, '', 0, 0, '', ' ', 'phone');
7557 } elseif ($type == 'ip') {
7558 $value = dol_print_ip($value, 0);
7559 } elseif ($type == 'price') {
7560 if (!is_null($value) && $value !== '') {
7561 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
7563 } elseif ($type == 'select') {
7564 $value = isset($param['options'][$value])?$param['options'][$value]:'';
7565 } elseif ($type == 'sellist') {
7566 $param_list = array_keys($param['options']);
7567 $InfoFieldList = explode(":
", $param_list[0]);
7569 $selectkey = "rowid";
7572 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7573 $selectkey = $InfoFieldList[2];
7574 $keyList = $InfoFieldList[2].' as rowid';
7577 $fields_label = explode('|', $InfoFieldList[1]);
7578 if (is_array($fields_label)) {
7580 $keyList .= implode(', ', $fields_label);
7583 $filter_categorie = false;
7584 if (count($InfoFieldList) > 5) {
7585 if ($InfoFieldList[0] == 'categorie') {
7586 $filter_categorie = true;
7590 $sql = "SELECT
".$keyList;
7591 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7592 if (strpos($InfoFieldList[4], 'extra') !== false) {
7595 if ($selectkey == 'rowid' && empty($value)) {
7596 $sql .= " WHERE
".$selectkey." = 0
";
7597 } elseif ($selectkey == 'rowid') {
7598 $sql .= " WHERE
".$selectkey." =
".((int) $value);
7600 $sql .= " WHERE
".$selectkey." =
'".$this->db->escape($value)."'";
7603 //$sql.= ' AND entity = '.$conf->entity;
7605 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
7606 $resql = $this->db->query($sql);
7608 if ($filter_categorie === false) {
7609 $value = ''; // value was used, so now we reste it to use it to build final output
7610 $numrows = $this->db->num_rows($resql);
7612 $obj = $this->db->fetch_object($resql);
7614 // Several field into label (eq table:code|libelle:rowid)
7615 $fields_label = explode('|', $InfoFieldList[1]);
7617 if (is_array($fields_label) && count($fields_label) > 1) {
7618 foreach ($fields_label as $field_toshow) {
7620 if (!empty($obj->$field_toshow)) {
7621 $translabel = $langs->trans($obj->$field_toshow);
7623 if ($translabel != $field_toshow) {
7624 $value .= dol_trunc($translabel, 18) . ' ';
7626 $value .= $obj->$field_toshow . ' ';
7631 if (!empty($obj->{$InfoFieldList[1]})) {
7632 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7634 if ($translabel != $obj->{$InfoFieldList[1]}) {
7635 $value = dol_trunc($translabel, 18);
7637 $value = $obj->{$InfoFieldList[1]};
7642 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
7645 $obj = $this->db->fetch_object($resql);
7646 $c = new Categorie($this->db);
7647 $c->fetch($obj->rowid);
7648 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1
" with html formatted text
7649 foreach ($ways as $way) {
7650 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
"' . ($c->color ? ' style="background: #
' . $c->color . ';
"' : ' style="background: #aaa
"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
7652 $value = '<div class="select2-container-multi-dolibarr
" style="width: 90%;
"><ul class="select2-choices-dolibarr
">'.implode(' ', $toprint).'</ul></div>';
7655 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7657 } elseif ($type == 'radio') {
7658 $value = $param['options'][$value];
7659 } elseif ($type == 'checkbox') {
7660 $value_arr = explode(',', $value);
7662 if (is_array($value_arr) && count($value_arr) > 0) {
7664 foreach ($value_arr as $keyval => $valueval) {
7665 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">'.$param['options'][$valueval].'</li>';
7667 $value = '<div class="select2-container-multi-dolibarr
" style="width: 90%;
"><ul class="select2-choices-dolibarr
">'.implode(' ', $toprint).'</ul></div>';
7669 } elseif ($type == 'chkbxlst') {
7670 $value_arr = explode(',', $value);
7672 $param_list = array_keys($param['options']);
7673 $InfoFieldList = explode(":
", $param_list[0]);
7675 $selectkey = "rowid";
7678 if (count($InfoFieldList) >= 3) {
7679 $selectkey = $InfoFieldList[2];
7680 $keyList = $InfoFieldList[2].' as rowid';
7683 $fields_label = explode('|', $InfoFieldList[1]);
7684 if (is_array($fields_label)) {
7686 $keyList .= implode(', ', $fields_label);
7689 $filter_categorie = false;
7690 if (count($InfoFieldList) > 5) {
7691 if ($InfoFieldList[0] == 'categorie') {
7692 $filter_categorie = true;
7696 $sql = "SELECT
".$keyList;
7697 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
7698 if (strpos($InfoFieldList[4], 'extra') !== false) {
7701 // $sql.= " WHERE
".$selectkey."=
'".$this->db->escape($value)."'";
7702 // $sql.= ' AND entity = '.$conf->entity;
7704 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
7705 $resql = $this->db->query($sql);
7707 if ($filter_categorie === false) {
7708 $value = ''; // value was used, so now we reste it to use it to build final output
7710 while ($obj = $this->db->fetch_object($resql)) {
7711 // Several field into label (eq table:code|libelle:rowid)
7712 $fields_label = explode('|', $InfoFieldList[1]);
7713 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7714 if (is_array($fields_label) && count($fields_label) > 1) {
7715 foreach ($fields_label as $field_toshow) {
7717 if (!empty($obj->$field_toshow)) {
7718 $translabel = $langs->trans($obj->$field_toshow);
7720 if ($translabel != $field_toshow) {
7721 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">' . dol_trunc($translabel, 18) . '</li>';
7723 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">' . $obj->$field_toshow . '</li>';
7728 if (!empty($obj->{$InfoFieldList[1]})) {
7729 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7731 if ($translabel != $obj->{$InfoFieldList[1]}) {
7732 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">' . dol_trunc($translabel, 18) . '</li>';
7734 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
" style="background: #bbb
">' . $obj->{$InfoFieldList[1]} . '</li>';
7740 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
7743 while ($obj = $this->db->fetch_object($resql)) {
7744 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7745 $c = new Categorie($this->db);
7746 $c->fetch($obj->rowid);
7747 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1
" with html formatted text
7748 foreach ($ways as $way) {
7749 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories
"' . ($c->color ? ' style="background: #
' . $c->color . ';
"' : ' style="background: #aaa
"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
7754 $value = '<div class="select2-container-multi-dolibarr
" style="width: 90%;
"><ul class="select2-choices-dolibarr
">'.implode(' ', $toprint).'</ul></div>';
7756 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
7758 } elseif ($type == 'link') {
7761 // only if something to display (perf)
7763 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
7765 $InfoFieldList = explode(":
", $param_list[0]);
7766 $classname = $InfoFieldList[0];
7767 $classpath = $InfoFieldList[1];
7768 $getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
7769 $getnomurlparam2 = (empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]);
7770 if (!empty($classpath)) {
7771 dol_include_once($InfoFieldList[1]);
7772 if ($classname && class_exists($classname)) {
7773 $object = new $classname($this->db);
7774 if ($object->element === 'product') { // Special cas for product because default valut of fetch are wrong
7775 $result = $object->fetch($value, '', '', '', 0, 1, 1);
7777 $result = $object->fetch($value);
7780 if ($object->element === 'product') {
7781 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
7782 if (isset($val['get_name_url_params'])) {
7783 $get_name_url_params = explode(':', $val['get_name_url_params']);
7784 if (!empty($get_name_url_params)) {
7785 $param_num_max = count($get_name_url_param_arr) - 1;
7786 foreach ($get_name_url_params as $param_num => $param_value) {
7787 if ($param_num > $param_num_max) {
7790 $get_name_url_param_arr[$param_num] = $param_value;
7798 $value = $object->getNomUrl($get_name_url_param_arr[0], $get_name_url_param_arr[1], $get_name_url_param_arr[2], $get_name_url_param_arr[3], $get_name_url_param_arr[4], $get_name_url_param_arr[5], $get_name_url_param_arr[6]);
7800 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
7807 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7808 return 'Error bad setup of extrafield';
7813 } elseif ($type == 'password') {
7814 $value = preg_replace('/./i', '*', $value);
7815 } elseif ($type == 'array') {
7816 $value = implode('<br>', $value);
7817 } else { // text|html|varchar
7818 $value = dol_htmlentitiesbr($value);
7821 //print $type.'-'.$size.'-'.$value;
7833 public function clearFieldError($fieldKey)
7836 unset($this->validateFieldsErrors[$fieldKey]);
7846 public function setFieldError($fieldKey, $msg = '')
7849 if (empty($msg)) { $msg = $langs->trans("UnknowError
"); }
7851 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
7860 public function getFieldError($fieldKey)
7862 if (!empty($this->validateFieldsErrors[$fieldKey])) {
7863 return $this->validateFieldsErrors[$fieldKey];
7876 public function validateField($val, $fieldKey, $fieldValue)
7880 if (!class_exists('Validate')) { require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
7882 $this->clearFieldError($fieldKey);
7884 if (!isset($val[$fieldKey])) {
7885 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
7890 $param['options'] = array();
7891 $type = $val[$fieldKey]['type'];
7894 if (isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1) {
7895 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
7906 // Convert var to be able to share same code than showOutputField of extrafields
7907 if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
7908 $type = 'varchar'; // convert varchar(xx) int varchar
7910 } elseif (preg_match('/varchar/', $type)) {
7911 $type = 'varchar'; // convert varchar(xx) int varchar
7914 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7918 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7922 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
7923 $param['options'] = $val['arrayofkeyval'];
7926 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
7928 $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
7929 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7930 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7932 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
7933 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
7935 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
7936 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
7944 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
7945 $validate = new Validate($this->db, $langs);
7948 // little trick : to perform tests with good performances sort tests by quick to low
7954 // Required test and empty value
7955 if ($required && !$validate->isNotEmptyString($fieldValue)) {
7956 $this->setFieldError($fieldKey, $validate->error);
7958 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
7959 // if no value sent and the field is not mandatory, no need to perform tests
7964 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
7965 $this->setFieldError($fieldKey, $validate->error);
7970 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
7971 $this->setFieldError($fieldKey, $validate->error);
7979 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
7980 if (!$validate->isTimestamp($fieldValue)) {
7981 $this->setFieldError($fieldKey, $validate->error);
7983 } else { return true; }
7984 } elseif ($type == 'duration') {
7985 if (!$validate->isDuration($fieldValue)) {
7986 $this->setFieldError($fieldKey, $validate->error);
7988 } else { return true; }
7989 } elseif (in_array($type, array('double', 'real', 'price'))) {
7991 if (!$validate->isNumeric($fieldValue)) {
7992 $this->setFieldError($fieldKey, $validate->error);
7994 } else { return true; }
7995 } elseif ($type == 'boolean') {
7996 if (!$validate->isBool($fieldValue)) {
7997 $this->setFieldError($fieldKey, $validate->error);
7999 } else { return true; }
8000 } elseif ($type == 'mail') {
8001 if (!$validate->isEmail($fieldValue)) {
8002 $this->setFieldError($fieldKey, $validate->error);
8005 } elseif ($type == 'url') {
8006 if (!$validate->isUrl($fieldValue)) {
8007 $this->setFieldError($fieldKey, $validate->error);
8009 } else { return true; }
8010 } elseif ($type == 'phone') {
8011 if (!$validate->isPhone($fieldValue)) {
8012 $this->setFieldError($fieldKey, $validate->error);
8014 } else { return true; }
8015 } elseif ($type == 'select' || $type == 'radio') {
8016 if (!isset($param['options'][$fieldValue])) {
8017 $this->error = $langs->trans('RequireValidValue');
8019 } else { return true; }
8020 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
8021 $param_list = array_keys($param['options']);
8022 $InfoFieldList = explode(":
", $param_list[0]);
8023 $value_arr = explode(',', $fieldValue);
8024 $value_arr = array_map(array($this->db, 'escape'), $value_arr);
8026 $selectkey = "rowid";
8027 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8028 $selectkey = $InfoFieldList[2];
8031 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8032 $this->setFieldError($fieldKey, $validate->error);
8034 } else { return true; }
8035 } elseif ($type == 'link') {
8036 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
8037 $InfoFieldList = explode(":
", $param_list[0]);
8038 $classname = $InfoFieldList[0];
8039 $classpath = $InfoFieldList[1];
8040 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8041 $this->setFieldError($fieldKey, $validate->error);
8043 } else { return true; }
8046 // if no test failled all is ok
8063 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card')
8065 global $db, $conf, $langs, $action, $form, $hookmanager;
8067 if (!is_object($form)) {
8068 $form = new Form($db);
8070 if (!is_object($extrafields)) {
8071 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
8072 return 'Bad parameter extrafields for showOptionals';
8074 if (!is_array($extrafields->attributes[$this->table_element])) {
8075 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);
", LOG_WARNING);
8080 $parameters = array('mode'=>$mode, 'params'=>$params, 'keysuffix'=>$keysuffix, 'keyprefix'=>$keyprefix, 'display_type'=>$display_type);
8081 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
8083 if (empty($reshook)) {
8084 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) {
8086 $out .= '<!-- commonobject:showOptionals --> ';
8089 $nbofextrafieldsshown = 0;
8090 $extrafields_collapse_num = '';
8091 $e = 0; // var to manage the modulo (odd/even)
8093 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
8094 // Show only the key field in params
8095 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
8099 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
8101 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
8102 $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '1');
8104 if (empty($enabled)) {
8109 if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
8110 $visibility = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '1');
8114 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
8115 $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '1');
8118 if (($mode == 'create') && abs($visibility) != 1 && abs($visibility) != 3) {
8119 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
8120 } elseif (($mode == 'edit') && abs($visibility) != 1 && abs($visibility) != 3 && abs($visibility) != 4) {
8121 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
8122 } elseif ($mode == 'view' && empty($visibility)) {
8125 if (empty($perms)) {
8128 // Load language if required
8129 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
8130 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
8134 if (is_array($params) && count($params) > 0 && $display_type=='card') {
8135 if (array_key_exists('cols', $params)) {
8136 $colspan = $params['cols'];
8137 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
8139 if (preg_match('/colspan="(\d+)
"/', $params['colspan'], $reg)) {
8142 $colspan = $params['colspan'];
8146 $colspan = intval($colspan);
8150 $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
8154 // We get the value of property found with GETPOST so it takes into account:
8155 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
8156 $check = 'alphanohtml';
8157 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
8158 $check = 'restricthtml';
8160 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
8161 // GETPOST("options_
" . $key) can be 'abc' or array(0=>'abc')
8162 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
8163 if (is_array($getposttemp)) {
8164 // $getposttemp is an array but following code expects a comma separated string
8165 $value = implode(",
", $getposttemp);
8167 $value = $getposttemp;
8170 $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.
8172 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_
".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
8176 $nbofextrafieldsshown++;
8178 // Output value of the current field
8179 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
8180 $extrafields_collapse_num = '';
8181 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
8182 if (!empty($extrafield_param) && is_array($extrafield_param)) {
8183 $extrafield_param_list = array_keys($extrafield_param['options']);
8185 if (count($extrafield_param_list) > 0) {
8186 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
8188 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
8189 $extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
8194 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
8195 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8197 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
8199 if (is_array($params) && count($params) > 0) {
8200 if (array_key_exists('class', $params)) {
8201 $class .= $params['class'].' ';
8203 if (array_key_exists('style', $params)) {
8204 $csstyle = $params['style'];
8208 // add html5 elements
8209 $domData = ' data-element="extrafield
"';
8210 $domData .= ' data-targetelement="'.$this->element.'"';
8211 $domData .= ' data-targetid="'.$this->id.'"';
8213 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
8214 if ($display_type=='card') {
8215 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
8219 if ($action == 'selectlines') {
8224 // Convert date into timestamp format (value in memory must be a timestamp)
8225 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
8226 $datenotinstring = null;
8227 if (array_key_exists('options_'.$key, $this->array_options)) {
8228 $datenotinstring = $this->array_options['options_'.$key];
8229 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8230 $datenotinstring = $this->db->jdate($datenotinstring);
8233 $datekey = $keyprefix.'options_'.$key.$keysuffix;
8234 $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOST($datekey.'month', 'int', 3), GETPOST($datekey.'day', 'int', 3), GETPOST($datekey.'year', 'int', 3)) : $datenotinstring;
8236 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
8237 $datenotinstring = null;
8238 if (array_key_exists('options_'.$key, $this->array_options)) {
8239 $datenotinstring = $this->array_options['options_'.$key];
8240 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8241 $datenotinstring = $this->db->jdate($datenotinstring);
8244 $timekey = $keyprefix.'options_'.$key.$keysuffix;
8245 $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;
8247 // Convert float submited string into real php numeric (value in memory must be a php numeric)
8248 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
8249 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
8250 $value = price2num($value);
8251 } elseif (isset($this->array_options['options_'.$key])) {
8252 $value = $this->array_options['options_'.$key];
8256 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
8257 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'int', 'boolean'))) {
8258 if ($action == 'create') {
8259 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
8263 $labeltoshow = $langs->trans($label);
8264 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
8266 if ($display_type == 'card') {
8267 $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.' >';
8268 if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
8269 $out .= '<td></td>';
8271 $out .= '<td class="titlefieldcreate wordbreak
';
8272 } elseif ($display_type == 'line
') {
8273 $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.' >
';
8274 $out .= '<div style=
"display: inline-block; padding-right:4px" class=
"wordbreak';
8276 //$out .= "titlefield
";
8277 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
8278 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
8279 $tpl_context = isset($params["tpl_context
"]) ? $params["tpl_context
"] : "none
";
8280 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
8281 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
8282 $out .= ' fieldrequired';
8286 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
8287 if (!empty($extrafields->attributes[$this->table_element]['help
'][$key])) {
8288 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8290 $out .= $labeltoshow;
8292 if ($mode != 'view
' && !empty($extrafields->attributes[$this->table_element]['required
'][$key])) {
8293 $out .= ' <span style=
"color: red">*</span>
';
8296 if (!empty($extrafields->attributes[$this->table_element]['help
'][$key])) {
8297 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
8299 $out .= $labeltoshow;
8303 $out .= ($display_type == 'card
' ? '</td>
' : '</div>
');
8305 $html_id = !empty($this->id) ? $this->element.'_extras_
'.$key.'_
'.$this->id : '';
8306 if ($display_type == 'card
') {
8307 // 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
8308 $out .= '<td
'.($html_id ? 'id=
"'.$html_id.'" ' : '').' class=
"valuefieldcreate '.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan=
"'.$colspan.'"' : '').'>
';
8309 } elseif ($display_type == 'line
') {
8310 $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].'">
';
8315 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
8318 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8321 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
8325 $out .= ($display_type=='card
' ? '</td>
' : '</div>
');
8327 if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
8328 $out .= ($display_type=='card
' ? '</tr>
' : '</div>
');
8330 $out .= ($display_type=='card
' ? '</tr>
' : '</div>
');
8337 // Add code to manage list depending on others
8338 if (!empty($conf->use_javascript_ajax)) {
8339 $out .= $this->getJSListDependancies();
8344 if (empty($nbofextrafieldsshown)) {
8350 $out .= $hookmanager->resPrint;
8359 public function getJSListDependancies($type = '_extra
')
8363 jQuery(document).ready(
function() {
8364 function showOptions
'.$type.'(child_list, parent_list, orig_select)
8366 var val = $(
"select[name=\""+parent_list+
"\"]").val();
8367 var parentVal = parent_list +
":" + val;
8368 if(typeof val ==
"string"){
8370 var options = orig_select.find(
"option[parent=\""+parentVal+
"\"]").clone();
8371 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8372 $(
"select[name=\""+child_list+
"\"]").append(options);
8374 var options = orig_select.find(
"option[parent]").clone();
8375 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8376 $(
"select[name=\""+child_list+
"\"]").append(options);
8378 }
else if(val > 0) {
8379 var options = orig_select.find(
"option[parent=\""+parentVal+
"\"]").clone();
8380 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8381 $(
"select[name=\""+child_list+
"\"]").append(options);
8383 var options = orig_select.find(
"option[parent]").clone();
8384 $(
"select[name=\""+child_list+
"\"] option[parent]").
remove();
8385 $(
"select[name=\""+child_list+
"\"]").append(options);
8388 function setListDependencies
'.$type.'() {
8389 jQuery(
"select option[parent]").parent().each(
function() {
8390 var orig_select = {};
8391 var child_list = $(
this).attr(
"name");
8392 orig_select[child_list] = $(
this).clone();
8393 var parent = $(
this).find(
"option[parent]:first").attr(
"parent");
8394 var infos = parent.split(
":");
8395 var parent_list = infos[0];
8398 if ($(
"#"+child_list).val() == 0 && $(
"#"+parent_list).val() == 0){
8399 $(
"#"+child_list).hide();
8401 }
else if ($(
"#"+parent_list).val() != 0){
8402 $(
"#"+parent_list).show();
8405 $(
"select[name=\""+parent_list+
"\"]").click(
function() {
8406 if ($(
this).val() != 0){
8407 $(
"#"+child_list).show()
8412 $(
"select[name=\""+parent_list+
"\"]").change(
function() {
8413 showOptions
'.$type.'(child_list, parent_list, orig_select[child_list]);
8415 $(
"#"+child_list).val(0).trigger(
"change");
8417 if ($(
this).val() == 0){
8418 $(
"#"+child_list).hide();
8424 setListDependencies
'.$type.'();
8434 public function getRights()
8438 $element = $this->element;
8439 if ($element == 'facturerec
') {
8440 $element = 'facture
';
8441 } elseif ($element == 'invoice_supplier_rec
') {
8442 return $user->rights->fournisseur->facture;
8443 } elseif ($element == 'evaluation
') {
8444 return $user->rights->hrm->evaluation;
8447 return $user->rights->{$element};
8462 public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8464 foreach ($tables as $table) {
8465 $sql = 'UPDATE
'.$dbs->prefix().$table.' SET fk_soc =
'.((int) $dest_id).' WHERE fk_soc =
'.((int) $origin_id);
8467 if (!$dbs->query($sql)) {
8468 if ($ignoreerrors) {
8469 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.
8471 //$this->errors = $db->lasterror();
8491 public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
8493 foreach ($tables as $table) {
8494 $sql = 'UPDATE
'.MAIN_DB_PREFIX.$table.' SET fk_product =
'.((int) $dest_id).' WHERE fk_product =
'.((int) $origin_id);
8496 if (!$dbs->query($sql)) {
8497 if ($ignoreerrors) {
8498 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.
8500 //$this->errors = $db->lasterror();
8520 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
8526 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull > 0)) {
8527 // When ForceBuyingPriceIfNull is set
8528 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
8530 // Get cost price for margin calculation
8531 if (!empty($fk_product) && $fk_product > 0) {
8532 if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice
') {
8533 require_once DOL_DOCUMENT_ROOT.'/product/
class/product.class.php
';
8534 $product = new Product($this->db);
8535 $result = $product->fetch($fk_product);
8537 $this->errors[] = 'ErrorProductIdDoesNotExists
';
8540 if ($product->cost_price > 0) {
8541 $buyPrice = $product->cost_price;
8542 } elseif ($product->pmp > 0) {
8543 $buyPrice = $product->pmp;
8545 } elseif (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp
') {
8546 require_once DOL_DOCUMENT_ROOT.'/product/
class/product.class.php
';
8547 $product = new Product($this->db);
8548 $result = $product->fetch($fk_product);
8550 $this->errors[] = 'ErrorProductIdDoesNotExists
';
8553 if ($product->pmp > 0) {
8554 $buyPrice = $product->pmp;
8558 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1
', 'pmp
', 'costprice
'))) {
8559 require_once DOL_DOCUMENT_ROOT.'/fourn/
class/fournisseur.product.class.php
';
8560 $productFournisseur = new ProductFournisseur($this->db);
8561 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
8562 $buyPrice = $productFournisseur->fourn_unitprice;
8563 } elseif ($result < 0) {
8564 $this->errors[] = $productFournisseur->error;
8573 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8591 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)
8594 global $conf, $user, $langs;
8596 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php
';
8597 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php
';
8599 $sortfield = 'position_name
';
8605 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8606 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
8608 // For backward compatibility
8609 if ($modulepart == 'product
') {
8610 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO
')) {
8611 $dir = $sdir.'/
'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8612 $pdir = '/
'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
8616 // Defined relative dir to DOL_DATA_ROOT
8619 $relativedir = preg_replace('/^
'.preg_quote(DOL_DATA_ROOT, '/
').'/
', '', $dir);
8620 $relativedir = preg_replace('/^[\\/]/
', '', $relativedir);
8621 $relativedir = preg_replace('/[\\/]$/
', '', $relativedir);
8624 $dirthumb = $dir.'thumbs/
';
8625 $pdirthumb = $pdir.'thumbs/
';
8627 $return = '<!-- Photo -->
'."\n";
8630 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$
', $sortfield, (strtolower($sortorder) == 'desc
' ?SORT_DESC:SORT_ASC), 1);
8632 /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO
')) // For backward compatiblity, we scan also old dirs
8634 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$
',$sortfield,(strtolower($sortorder)=='desc
'?SORT_DESC:SORT_ASC),1);
8635 $filearray=array_merge($filearray, $filearrayold);
8638 completeFileArrayWithDatabaseInfo($filearray, $relativedir);
8640 if (count($filearray)) {
8641 if ($sortfield && $sortorder) {
8642 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
8645 foreach ($filearray as $key => $val) {
8647 $file = $val['name'];
8649 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
8650 if (image_format_supported($file) >= 0) {
8653 $viewfilename = $file;
8655 if ($size == 1 || $size == 'small
') { // Format vignette
8656 // Find name of thumb file
8657 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small
'));
8658 if (!dol_is_file($dirthumb.$photo_vignette)) {
8659 $photo_vignette = '';
8662 // Get filesize of original file
8663 $imgarray = dol_getImageSize($dir.$photo);
8666 if ($nbphoto == 1) {
8667 $return .= '<table
class=
"valigntop center centpercent" style=
"border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">
';
8670 if ($nbphoto % $nbbyrow == 1) {
8671 $return .= '<tr
class=
"center valignmiddle" style=
"border: 1px">
';
8673 $return .= '<td style=
"width: '.ceil(100 / $nbbyrow).'%" class=
"photo">
';
8674 } elseif ($nbbyrow < 0) {
8675 $return .= '<div
class=
"inline-block">
';
8680 $relativefile = preg_replace('/^\
8681 if (empty($nolink)) {
8684 $return .=
'<a href="'.$urladvanced.
'">';
8686 $return .=
'<a href="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'" class="aphoto" target="_blank" rel="noopener noreferrer">';
8692 $alt = $langs->transnoentitiesnoconv(
'File').
': '.$relativefile;
8693 $alt .=
' - '.$langs->transnoentitiesnoconv(
'Size').
': '.$imgarray[
'width'].
'x'.$imgarray[
'height'];
8698 $addphotorefcss = 1;
8700 if ($usesharelink) {
8701 if ($val[
'share']) {
8702 if (empty($maxHeight) || $photo_vignette && $imgarray[
'height'] > $maxHeight) {
8703 $return .=
'<!-- Show original file (thumb not yet available with shared links) -->';
8704 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?hashp='.urlencode($val[
'share']).
'" title="'.
dol_escape_htmltag($alt).
'">';
8706 $return .=
'<!-- Show original file -->';
8707 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/viewimage.php?hashp='.urlencode($val[
'share']).
'" title="'.
dol_escape_htmltag($alt).
'">';
8710 $return .=
'<!-- Show nophoto file (because file is not shared) -->';
8711 $return .=
'<img class="photo photowithmargin'.($addphotorefcss ?
' photoref' :
'').
'" height="'.$maxHeight.
'" src="'.DOL_URL_ROOT.
'/public/theme/common/nophoto.png" title="'.
dol_escape_htmltag($alt).
'">';
8714 if (empty($maxHeight) || $photo_vignette && $imgarray[
'height'] > $maxHeight) {
8715 $return .=
'<!-- Show thumb -->';
8716 $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).
'">';
8718 $return .=
'<!-- Show original file -->';
8719 $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).
'">';
8723 if (empty($nolink)) {
8728 if ($showfilename) {
8729 $return .=
'<br>'.$viewfilename;
8734 if ($photo_vignette && (
image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) {
8735 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=addthumb&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">'.
img_picto($langs->trans(
'GenerateThumb'),
'refresh').
' </a>';
8738 if ($modulepart ==
'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8740 $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> ';
8743 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8751 if (($nbphoto % $nbbyrow) == 0) {
8754 } elseif ($nbbyrow < 0) {
8755 $return .=
'</div>';
8760 $return .=
'<img class="photo photowithmargin" src="'.DOL_URL_ROOT.
'/viewimage.php?modulepart='.$modulepart.
'&entity='.$this->entity.
'&file='.urlencode($pdir.$photo).
'">';
8762 if ($showfilename) {
8763 $return .=
'<br>'.$viewfilename;
8767 if ($modulepart ==
'product' && ($user->rights->produit->creer || $user->rights->service->creer)) {
8769 $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> ';
8772 $return .=
'<a href="'.$_SERVER[
"PHP_SELF"].
'?id='.$this->
id.
'&action=delete&token='.
newToken().
'&file='.urlencode($pdir.$viewfilename).
'">';
8779 if ($nbmax && $nbphoto >= $nbmax) {
8785 if ($size == 1 || $size ==
'small') {
8788 while ($nbphoto % $nbbyrow) {
8789 $return .=
'<td style="width: '.ceil(100 / $nbbyrow).
'%"> </td>';
8794 $return .=
'</table>';
8800 $this->nbphoto = $nbphoto;
8814 if (is_array($info)) {
8815 if (isset($info[
'type']) && $info[
'type'] ==
'array') {
8832 if (isset($info[
'type']) && ($info[
'type'] ==
'date' || $info[
'type'] ==
'datetime' || $info[
'type'] ==
'timestamp')) {
8846 if (is_array($info)) {
8847 if (isset($info[
'type']) && ($info[
'type'] ==
'duration')) {
8865 if (is_array($info)) {
8866 if (isset($info[
'type']) && (preg_match(
'/(^int|int$)/i', $info[
'type']))) {
8884 if (is_array($info)) {
8885 if (isset($info[
'type']) && (preg_match(
'/^(double|real|price)/i', $info[
'type']))) {
8902 if (is_array($info)) {
8903 if (isset($info[
'type']) && $info[
'type'] ==
'text') {
8920 if (is_array($info)) {
8921 if (isset($info[
'notnull']) && $info[
'notnull'] !=
'1') {
8938 if (is_array($info)) {
8939 if (isset($info[
'notnull']) && $info[
'notnull'] ==
'-1') {
8956 if (is_array($info)) {
8957 if (isset($info[
'index']) && $info[
'index'] ==
true) {
8979 $queryarray = array();
8980 foreach ($this->fields as $field => $info) {
8982 if ($this->isDate($info)) {
8983 if (empty($this->{$field})) {
8984 $queryarray[$field] =
null;
8986 $queryarray[$field] = $this->
db->idate($this->{$field});
8988 } elseif ($this->isDuration($info)) {
8990 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
8991 if (!isset($this->{$field})) {
8992 if (!empty($info[
'default'])) {
8993 $queryarray[$field] = $info[
'default'];
8995 $queryarray[$field] = 0;
8998 $queryarray[$field] = (int) $this->{$field};
9001 $queryarray[$field] =
null;
9003 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9004 if ($field ==
'entity' && is_null($this->{$field})) {
9005 $queryarray[$field] = ((int) $conf->entity);
9008 if ((isset($this->{$field}) && $this->{$field} !=
'') || !empty($info[
'notnull'])) {
9009 if (!isset($this->{$field})) {
9010 $queryarray[$field] = 0;
9011 } elseif ($this->isInt($info)) {
9012 $queryarray[$field] = (int) $this->{$field};
9013 } elseif ($this->isFloat($info)) {
9014 $queryarray[$field] = (double) $this->{$field};
9017 $queryarray[$field] =
null;
9023 $queryarray[$field] = $this->{$field};
9026 if ($info[
'type'] ==
'timestamp' && empty($queryarray[$field])) {
9027 unset($queryarray[$field]);
9029 if (!empty($info[
'notnull']) && $info[
'notnull'] == -1 && empty($queryarray[$field])) {
9030 $queryarray[$field] =
null;
9047 foreach ($this->fields as $field => $info) {
9048 if ($this->isDate($info)) {
9049 if (is_null($obj->{$field}) || $obj->{$field} ===
'' || $obj->{$field} ===
'0000-00-00 00:00:00' || $obj->{$field} ===
'1000-01-01 00:00:00') {
9050 $this->{$field} =
'';
9052 $this->{$field} = $db->jdate($obj->{$field});
9054 } elseif ($this->isInt($info)) {
9055 if ($field ==
'rowid') {
9056 $this->
id = (int) $obj->{$field};
9058 if ($this->isForcedToNullIfZero($info)) {
9059 if (empty($obj->{$field})) {
9060 $this->{$field} =
null;
9062 $this->{$field} = (double) $obj->{$field};
9065 if (!is_null($obj->{$field}) || (isset($info[
'notnull']) && $info[
'notnull'] == 1)) {
9066 $this->{$field} = (int) $obj->{$field};
9068 $this->{$field} =
null;
9072 } elseif ($this->isFloat($info)) {
9073 if ($this->isForcedToNullIfZero($info)) {
9074 if (empty($obj->{$field})) {
9075 $this->{$field} =
null;
9077 $this->{$field} = (double) $obj->{$field};
9080 if (!is_null($obj->{$field}) || (isset($info[
'notnull']) && $info[
'notnull'] == 1)) {
9081 $this->{$field} = (double) $obj->{$field};
9083 $this->{$field} =
null;
9087 $this->{$field} = isset($obj->{$field}) ? $obj->{$field} :
null;
9092 if (!isset($this->fields[
'ref']) && isset($this->
id)) {
9093 $this->
ref = $this->id;
9105 $keys = array_keys($this->fields);
9106 if (!empty($alias)) {
9107 $keys_with_alias = array();
9108 foreach ($keys as $fieldname) {
9109 $keys_with_alias[] = $alias .
'.' . $fieldname;
9111 return implode(
',', $keys_with_alias);
9113 return implode(
',', $keys);
9124 protected function quote($value, $fieldsentry)
9126 if (is_null($value)) {
9128 } elseif (preg_match(
'/^(int|double|real|price)/i', $fieldsentry[
'type'])) {
9130 } elseif (preg_match(
'/int$/i', $fieldsentry[
'type'])) {
9131 return (
int) $value;
9132 } elseif ($fieldsentry[
'type'] ==
'boolean') {
9139 return "'".$this->db->escape($value).
"'";
9154 dol_syslog(get_class($this).
"::createCommon create", LOG_DEBUG);
9160 $fieldvalues = $this->setSaveQuery();
9162 if (array_key_exists(
'date_creation', $fieldvalues) && empty($fieldvalues[
'date_creation'])) {
9163 $fieldvalues[
'date_creation'] = $this->
db->idate($now);
9165 if (array_key_exists(
'fk_user_creat', $fieldvalues) && !($fieldvalues[
'fk_user_creat'] > 0)) {
9166 $fieldvalues[
'fk_user_creat'] = $user->id;
9168 unset($fieldvalues[
'rowid']);
9169 if (array_key_exists(
'ref', $fieldvalues)) {
9175 foreach ($fieldvalues as $k => $v) {
9177 $value = $this->fields[$k];
9178 $values[$k] = $this->quote($v, $value);
9182 foreach ($keys as $key) {
9184 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9187 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9191 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && is_null($this->fields[$key][
'default'])) {
9193 $langs->load(
"errors");
9194 dol_syslog(
"Mandatory field '".$key.
"' is empty and required into ->fields definition of class");
9195 $this->errors[] = $langs->trans(
"ErrorFieldRequired", $this->fields[$key][
'label']);
9199 if (isset($this->fields[$key][
'notnull']) && $this->fields[$key][
'notnull'] == 1 && (!isset($values[$key]) || $values[$key] ===
'NULL') && !is_null($this->fields[$key][
'default'])) {
9200 $values[$key] = $this->quote($this->fields[$key][
'default'], $this->fields[$key]);
9204 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && empty($values[$key])) {
9205 if (isset($this->fields[$key][
'default'])) {
9206 $values[$key] = ((int) $this->fields[$key][
'default']);
9208 $values[$key] =
'null';
9211 if (!empty($this->fields[$key][
'foreignkey']) && empty($values[$key])) {
9212 $values[$key] =
'null';
9223 $sql =
"INSERT INTO ".$this->db->prefix().$this->table_element;
9224 $sql .=
" (".implode(
", ", $keys).
')';
9225 $sql .=
" VALUES (".implode(
", ", $values).
")";
9227 $res = $this->
db->query($sql);
9230 if ($this->
db->lasterrno() ==
'DB_ERROR_RECORD_ALREADY_EXISTS') {
9231 $this->errors[] =
"ErrorRefAlreadyExists";
9233 $this->errors[] = $this->
db->lasterror();
9239 $this->
id = $this->
db->last_insert_id($this->
db->prefix().$this->table_element);
9244 if (key_exists(
'ref', $this->fields) && $this->fields[
'ref'][
'notnull'] > 0 && key_exists(
'default', $this->fields[
'ref']) && $this->fields[
'ref'][
'default'] ==
'(PROV)') {
9245 $sql =
"UPDATE ".$this->db->prefix().$this->table_element.
" SET ref = '(PROV".((int) $this->
id).
")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->
id);
9246 $resqlupdate = $this->
db->query($sql);
9248 if ($resqlupdate ===
false) {
9250 $this->errors[] = $this->
db->lasterror();
9252 $this->
ref =
'(PROV'.$this->id.
')';
9259 $result = $this->insertExtraFields();
9266 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
9267 $num = (is_array($this->lines) ? count($this->lines) : 0);
9268 for ($i = 0; $i < $num; $i++) {
9269 $line = $this->lines[$i];
9271 $keyforparent = $this->fk_element;
9272 $line->$keyforparent = $this->id;
9276 if (!is_object($line)) {
9277 $line = (object) $line;
9280 $result = $line->create($user, 1);
9282 $this->error = $line->error;
9283 $this->
db->rollback();
9290 if (!$error && !$notrigger) {
9292 $result = $this->call_trigger(strtoupper(get_class($this)).
'_CREATE', $user);
9301 $this->
db->rollback();
9304 $this->
db->commit();
9320 if (empty($id) && empty($ref) && empty($morewhere)) {
9324 $fieldlist = $this->getFieldList(
't');
9325 if (empty($fieldlist)) {
9329 $sql =
"SELECT ".$fieldlist;
9330 $sql .=
" FROM ".$this->db->prefix().$this->table_element.
' as t';
9333 $sql .=
' WHERE t.rowid = '.((int) $id);
9334 } elseif (!empty($ref)) {
9335 $sql .=
" WHERE t.ref = '".$this->db->escape($ref).
"'";
9337 $sql .=
' WHERE 1 = 1';
9339 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
9340 $sql .=
' AND t.entity IN ('.getEntity($this->table_element).
')';
9347 $res = $this->
db->query($sql);
9349 $obj = $this->
db->fetch_object($res);
9351 $this->setVarsFromFetchObj($obj);
9355 $this->fetch_optionals();
9362 $this->error = $this->
db->lasterror();
9363 $this->errors[] = $this->error;
9376 $objectlineclassname = get_class($this).
'Line';
9377 if (!class_exists($objectlineclassname)) {
9378 $this->error =
'Error, class '.$objectlineclassname.
' not found during call of fetchLinesCommon';
9382 $objectline =
new $objectlineclassname($this->
db);
9384 $sql =
"SELECT ".$objectline->getFieldList(
'l');
9385 $sql .=
" FROM ".$this->db->prefix().$objectline->table_element.
" as l";
9386 $sql .=
" WHERE l.fk_".$this->db->escape($this->element).
" = ".((int) $this->
id);
9390 if (isset($objectline->fields[
'position'])) {
9391 $sql .= $this->
db->order(
'position',
'ASC');
9396 $num_rows = $this->
db->num_rows(
$resql);
9398 while ($i < $num_rows) {
9399 $obj = $this->
db->fetch_object(
$resql);
9401 $newline =
new $objectlineclassname($this->
db);
9402 $newline->setVarsFromFetchObj($obj);
9404 $this->lines[] = $newline;
9411 $this->error = $this->
db->lasterror();
9412 $this->errors[] = $this->error;
9426 global $conf, $langs;
9427 dol_syslog(get_class($this).
"::updateCommon update", LOG_DEBUG);
9438 $fieldvalues = $this->setSaveQuery();
9440 if (array_key_exists(
'date_modification', $fieldvalues) && empty($fieldvalues[
'date_modification'])) {
9441 $fieldvalues[
'date_modification'] = $this->
db->idate($now);
9443 if (array_key_exists(
'fk_user_modif', $fieldvalues) && !($fieldvalues[
'fk_user_modif'] > 0)) {
9444 $fieldvalues[
'fk_user_modif'] = $user->id;
9446 unset($fieldvalues[
'rowid']);
9447 if (array_key_exists(
'ref', $fieldvalues)) {
9455 foreach ($fieldvalues as $k => $v) {
9457 $value = $this->fields[$k];
9458 $values[$k] = $this->quote($v, $value);
9459 $tmp[] = $k.
'='.$this->quote($v, $this->fields[$k]);
9463 foreach ($keys as $key) {
9464 if (preg_match(
'/^integer:/i', $this->fields[$key][
'type']) && $values[$key] ==
'-1') {
9467 if (!empty($this->fields[$key][
'foreignkey']) && $values[$key] ==
'-1') {
9480 $sql =
'UPDATE '.$this->db->prefix().$this->table_element.
' SET '.implode(
', ', $tmp).
' WHERE rowid='.((int) $this->
id);
9485 $res = $this->
db->query($sql);
9488 $this->errors[] = $this->
db->lasterror();
9494 $result = $this->insertExtraFields();
9501 if (!$error && !$notrigger) {
9503 $result = $this->call_trigger(strtoupper(get_class($this)).
'_MODIFY', $user);
9512 $this->
db->rollback();
9515 $this->
db->commit();
9530 dol_syslog(get_class($this).
"::deleteCommon delete", LOG_DEBUG);
9536 if ($forcechilddeletion) {
9537 foreach ($this->childtables as $table) {
9538 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9541 $this->error = $this->
db->lasterror();
9542 $this->errors[] = $this->error;
9543 $this->
db->rollback();
9547 } elseif (!empty($this->fk_element) && !empty($this->childtables)) {
9548 $objectisused = $this->isObjectUsed($this->
id);
9549 if (!empty($objectisused)) {
9550 dol_syslog(get_class($this).
"::deleteCommon Can't delete record as it has some child", LOG_WARNING);
9551 $this->error =
'ErrorRecordHasChildren';
9552 $this->errors[] = $this->error;
9553 $this->
db->rollback();
9559 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
9560 foreach ($this->childtablesoncascade as $table) {
9561 $deleteFromObject = explode(
':', $table);
9562 if (count($deleteFromObject) >= 2) {
9563 $className = str_replace(
'@',
'', $deleteFromObject[0]);
9564 $filePath = $deleteFromObject[1];
9565 $columnName = $deleteFromObject[2];
9566 $TMoreSQL = array();
9567 $more_sql = $deleteFromObject[3];
9568 if (!empty($more_sql)) {
9569 $TMoreSQL[
'customsql'] = $more_sql;
9572 $childObject =
new $className($this->
db);
9573 if (method_exists($childObject,
'deleteByParentField')) {
9574 $result = $childObject->deleteByParentField($this->
id, $columnName, $TMoreSQL);
9577 $this->errors[] = $childObject->error;
9582 $this->errors[] =
"You defined a cascade delete on an object $childObject but there is no method deleteByParentField for it";
9587 $this->errors[] =
'Cannot include child class file '.$filePath;
9592 $sql =
"DELETE FROM ".$this->db->prefix().$table.
" WHERE ".$this->fk_element.
" = ".((int) $this->
id);
9597 $this->error = $this->
db->lasterror();
9598 $this->errors[] = $this->error;
9608 $result = $this->call_trigger(strtoupper(get_class($this)).
'_DELETE', $user);
9618 $res = $this->deleteEcmFiles(1);
9625 $res = $this->deleteObjectLinked();
9630 if (!$error && !empty($this->isextrafieldmanaged)) {
9631 $result = $this->deleteExtraFields();
9638 $sql =
'DELETE FROM '.$this->db->prefix().$this->table_element.
' WHERE rowid='.((int) $this->
id);
9643 $this->errors[] = $this->
db->lasterror();
9649 $this->
db->rollback();
9652 $this->
db->commit();
9674 if (!empty($parentId) && !empty($parentField)) {
9677 $sql =
"SELECT rowid FROM ".$this->db->prefix().$this->table_element;
9678 $sql .=
" WHERE ".$parentField.
" = ".(int) $parentId;
9681 $sqlwhere = array();
9682 if (count($filter) > 0) {
9683 foreach ($filter as $key => $value) {
9684 if ($key ==
'customsql') {
9685 $sqlwhere[] = $value;
9686 } elseif (strpos($value,
'%') ===
false) {
9687 $sqlwhere[] = $key.
" IN (".$this->
db->sanitize($this->
db->escape($value)).
")";
9689 $sqlwhere[] = $key.
" LIKE '%".$this->
db->escape($value).
"%'";
9693 if (count($sqlwhere) > 0) {
9694 $sql .=
" AND (".implode(
" ".$filtermode.
" ", $sqlwhere).
")";
9699 $this->errors[] = $this->
db->lasterror();
9702 while ($obj = $this->
db->fetch_object(
$resql)) {
9703 $result = $this->fetch($obj->rowid);
9706 $this->errors[] = $this->error;
9708 if (get_class($this) ==
'Contact') {
9709 $result = $this->
delete();
9711 $result = $this->
delete($user);
9715 $this->errors[] = $this->error;
9723 if (empty($error)) {
9724 $this->
db->commit();
9727 $this->error = implode(
', ', $this->errors);
9728 $this->
db->rollback();
9750 $tmpforobjectclass = get_class($this);
9751 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).
'Line';
9756 $result = $this->call_trigger(
'LINE'.strtoupper($tmpforobjectclass).
'_DELETE', $user);
9762 if (empty($error)) {
9763 $sql =
"DELETE FROM ".$this->db->prefix().$this->table_element_line;
9764 $sql .=
" WHERE rowid = ".((int) $idline);
9768 $this->error =
"Error ".$this->db->lasterror();
9773 if (empty($error)) {
9775 $tmpobjectline =
new $tmpforobjectlineclass($this->
db);
9776 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
9777 $tmpobjectline->id = $idline;
9778 $result = $tmpobjectline->deleteExtraFields();
9781 $this->error =
"Error ".get_class($this).
"::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
9786 if (empty($error)) {
9787 $this->
db->commit();
9790 dol_syslog(get_class($this).
"::deleteLineCommon ERROR:".$this->error, LOG_ERR);
9791 $this->
db->rollback();
9812 $statusfield =
'status';
9813 if ($this->element ==
'don' || $this->element ==
'donation') {
9814 $statusfield =
'fk_statut';
9817 $sql =
"UPDATE ".$this->db->prefix().$this->table_element;
9818 $sql .=
" SET ".$statusfield.
" = ".((int) $status);
9819 $sql .=
" WHERE rowid = ".((int) $this->
id);
9821 if ($this->
db->query($sql)) {
9823 $this->oldcopy = clone $this;
9826 if (!$error && !$notrigger) {
9828 $result = $this->call_trigger($triggercode, $user);
9835 $this->status = $status;
9836 $this->
db->commit();
9839 $this->
db->rollback();
9843 $this->error = $this->
db->error();
9844 $this->
db->rollback();
9861 $this->specimen = 1;
9863 'label' =>
'This is label',
9864 'ref' =>
'ABCD1234',
9865 'description' =>
'This is a description',
9867 'note_public' =>
'Public note',
9868 'note_private' =>
'Private note',
9869 'date_creation' => (
dol_now() - 3600 * 48),
9870 'date_modification' => (
dol_now() - 3600 * 24),
9871 'fk_user_creat' => $user->id,
9872 'fk_user_modif' => $user->id,
9875 foreach ($fields as $key => $value) {
9876 if (array_key_exists($key, $this->fields)) {
9877 $this->{$key} = $value;
9892 require_once DOL_DOCUMENT_ROOT.
'/core/class/comment.class.php';
9895 $result = $comment->fetchAllFor($this->element, $this->
id);
9897 $this->errors = array_merge($this->errors, $comment->errors);
9900 $this->comments = $comment->comments;
9902 return count($this->comments);
9912 return count($this->comments);
9923 if (!is_array($parameters)) {
9926 foreach ($parameters as $parameter) {
9927 if (isset($this->$parameter)) {
9928 $this->$parameter = trim($this->$parameter);
9947 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
9951 $existing = $c->containing($this->
id, $type_categ,
'id');
9971 if (!is_array($categories)) {
9972 $categories = array($categories);
9975 dol_syslog(get_class($this).
"::setCategoriesCommon Oject Id:".$this->
id.
' type_categ:'.$type_categ.
' nb tag add:'.count($categories), LOG_DEBUG);
9977 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
9979 if (empty($type_categ)) {
9980 dol_syslog(__METHOD__.
': Type '.$type_categ.
'is an unknown category type. Done nothing.', LOG_ERR);
9986 $existing = $c->containing($this->
id, $type_categ,
'id');
9987 if ($remove_existing) {
9989 if (is_array($existing)) {
9990 $to_del = array_diff($existing, $categories);
9991 $to_add = array_diff($categories, $existing);
9994 $to_add = $categories;
9998 $to_add = array_diff($categories, $existing);
10005 foreach ($to_del as $del) {
10006 if ($c->fetch($del) > 0) {
10007 $result=$c->del_type($this, $type_categ);
10010 $this->error = $c->error;
10011 $this->errors = $c->errors;
10018 foreach ($to_add as $add) {
10019 if ($c->fetch($add) > 0) {
10020 $result = $c->add_type($this, $type_categ);
10023 $this->error = $c->error;
10024 $this->errors = $c->errors;
10032 return $error ? (-1 * $error) : $ok;
10045 $this->
db->begin();
10047 if (empty($type)) {
10048 $type = $this->table_element;
10051 require_once DOL_DOCUMENT_ROOT.
'/categories/class/categorie.class.php';
10054 $sql =
"INSERT INTO ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]).
" (fk_categorie, fk_product)";
10055 $sql .=
" SELECT fk_categorie, $toId FROM ".$this->db->prefix().
"categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10056 $sql .=
" WHERE fk_product = ".((int) $fromId);
10058 if (!$this->
db->query($sql)) {
10059 $this->error = $this->
db->lasterror();
10060 $this->
db->rollback();
10064 $this->
db->commit();
10078 $this->
db->begin();
10082 switch ($this->element) {
10084 $element =
'propale';
10087 $element =
'produit';
10089 case 'order_supplier':
10090 $element =
'fournisseur/commande';
10092 case 'invoice_supplier':
10093 $element =
'fournisseur/facture/'.get_exdir($this->
id, 2, 0, 1, $this,
'invoice_supplier');
10096 $element =
'expedition/sending';
10099 $element = $this->element;
10103 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files_extrafields WHERE fk_object IN (";
10104 $sql .=
" SELECT rowid FROM ".$this->db->prefix().
"ecm_files WHERE filename LIKE '".$this->
db->escape($this->
ref).
"%'";
10105 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->
db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10108 if (!$this->
db->query($sql)) {
10109 $this->error = $this->
db->lasterror();
10110 $this->
db->rollback();
10115 $sql =
"DELETE FROM ".$this->db->prefix().
"ecm_files";
10116 $sql .=
" WHERE filename LIKE '".$this->db->escape($this->
ref).
"%'";
10117 $sql .=
" AND filepath = '".$this->db->escape($element).
"/".$this->
db->escape($this->
ref).
"' AND entity = ".((int) $conf->entity);
10119 if (!$this->
db->query($sql)) {
10120 $this->error = $this->
db->lasterror();
10121 $this->
db->rollback();
10128 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files_extrafields";
10129 $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).
")";
10132 $this->error = $this->
db->lasterror();
10133 $this->
db->rollback();
10137 $sql =
'DELETE FROM '.$this->db->prefix().
"ecm_files";
10138 $sql .=
" WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ?
"" :
"@".$this->module)).
"' AND src_object_id = ".((int) $this->
id);
10141 $this->error = $this->
db->lasterror();
10142 $this->
db->rollback();
10147 $this->
db->commit();
Class to manage categories.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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...
getCategoriesCommon($type_categ)
Sets object to given categories.
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getBannerAddress($htmlkey, $object)
Return full address for banner.
swapContactStatus($rowid)
Update status of a contact linked to object.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
deleteByParentField($parentId=0, $parentField='', $filter=array(), $filtermode="AND")
Delete all child object from a parent ID.
getFieldList($alias='')
Function to concat keys of fields.
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
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...
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setDocModel($user, $modelpdf)
Set last model used by doc generator.
isFloat($info)
Function test if type is float.
setExtraParameters()
Set extra parameters.
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
update_ref_ext($ref_ext)
Update external ref of element.
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0, $display_type='card')
Function to show lines of extrafields with output datas.
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...
createCommon(User $user, $notrigger=false)
Create object into database.
updateRangOfLine($rowid, $rang)
Update position of line (rang)
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='', $f_user=null, $notrigger=0)
Delete all links between an object $this.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
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).
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
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....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
setSaveQuery()
Function to prepare a part of the query for insert by returning an array with all properties of objec...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
errorsToString()
Method to output saved errors.
setBankAccount($fk_account, $notrigger=false, $userused=null)
Change the bank account.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1)
Get array of all contacts for an object.
setWarehouse($warehouse_id)
Change the warehouse.
setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
Change the shipping method.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
trimParameters($parameters)
Trim object parameters.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
fetchComments()
Load comments linked with current task.
updateCommon(User $user, $notrigger=false)
Update object into database.
getRangOfLine($rowid)
Get position of line (rang)
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
update_note($note, $suffix='')
Update note of element.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
getKanbanView($option='')
Return clicable link of object (with eventually picto)
fetchLinesCommon($morewhere='')
Load object in memory from the database.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
isDuration($info)
Function test if type is duration.
canBeNull($info)
Function test if field can be null.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
Class to manage Dolibarr users.
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='', $dbtouse=0, $withregion=0, $outputlangs='', $entconv=1)
Return state translated from an id.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("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->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
print *****$script_file(".$version.") pid c cd cd cd description as p label as s rowid
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_now($mode='auto')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='')
Clean a string from all punctuation characters to use it as a ref or login.
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
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.
dol_ucwords($string, $encoding="UTF-8")
Convert first character of all the words of a string to upper.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
$conf db name
Only used if Module[ID]Name translation string is not found.
$conf db
API class for accounts.
print *****$script_file(".$version.") pid code
! Closing after partial payment: discount_vat, badcustomer or badsupplier, bankcharge,...