dolibarr 20.0.0
commonobject.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
6 * Copyright (C) 2011-2022 Philippe Grand <philippe.grand@atoo-net.com>
7 * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
8 * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
9 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
10 * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
11 * Copyright (C) 2016 Bahfir abbes <bafbes@gmail.com>
12 * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13 * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
14 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
17 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18 * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
19 * Copyright (C) 2023 Lenin Rivas <lenin.rivas777@gmail.com>
20 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
21 *
22 * This program is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation; either version 3 of the License, or
25 * (at your option) any later version.
26 *
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
31 *
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <https://www.gnu.org/licenses/>.
34 */
35
42require_once DOL_DOCUMENT_ROOT.'/core/class/doldeprecationhandler.class.php';
43
49abstract class CommonObject
50{
51 use DolDeprecationHandler;
52
53 const TRIGGER_PREFIX = ''; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
54
58 public $module;
59
63 public $db;
64
68 public $id;
69
73 public $entity;
74
79 public $error;
80
84 public $errorhidden;
85
89 public $errors = array();
90
94 private $validateFieldsErrors = array();
95
99 public $element;
100
105 public $fk_element;
106
112 public $element_for_permission;
113
117 public $table_element;
118
122 public $table_element_line = '';
123
128 public $ismultientitymanaged;
129
133 public $import_key;
134
138 public $array_options = array();
139
140
144 public $fields = array();
145
150 public $array_languages = null; // Value is array() when load already tried
151
155 public $contacts_ids;
156
160 public $linked_objects;
161
165 public $linkedObjectsIds;
166
170 public $linkedObjects;
171
175 private $linkedObjectsFullLoaded = array();
176
180 public $oldcopy;
181
185 public $oldref;
186
190 protected $table_ref_field = '';
191
195 public $restrictiononfksoc = 0;
196
197
198 // The following vars are used by some objects only.
199 // We keep these properties in CommonObject in order to provide common methods using them.
200
204 public $context = array();
205
209 public $actionmsg;
213 public $actionmsg2;
214
218 public $canvas;
219
224 public $project;
225
230 public $fk_project;
231
237 private $projet;
238
244 public $fk_projet;
245
250 public $contact;
251
256 public $contact_id;
257
262 public $thirdparty;
263
268 public $user;
269
274 public $origin_type;
275
280 public $origin_id;
281
286
292 public $origin;
293
302 private $expedition;
303
309 private $livraison;
310
316 private $commandeFournisseur;
317
318
322 public $ref;
323
327 public $ref_ext;
328
332 public $ref_previous;
333
337 public $ref_next;
338
342 public $newref;
343
350 public $statut;
351
359 public $status;
360
361
366 public $country;
367
372 public $country_id;
373
378 public $country_code;
379
384 public $state;
385
390 public $state_id;
391
396 public $fk_departement;
397
402 public $state_code;
403
408 public $region_id;
409
414 public $region_code;
415
420 public $region;
421
422
427 public $barcode_type;
428
433 public $barcode_type_code;
434
439 public $barcode_type_label;
440
445 public $barcode_type_coder;
446
451 public $mode_reglement_id;
452
457 public $cond_reglement_id;
458
462 public $demand_reason_id;
463
468 public $transport_mode_id;
469
477 private $cond_reglement; // Private to call DolDeprecationHandler
481 protected $depr_cond_reglement; // Internal value for deprecation
482
488 public $fk_delivery_address;
489
494 public $shipping_method_id;
495
500 public $shipping_method;
501
502 // Multicurrency
506 public $fk_multicurrency;
507
512 public $multicurrency_code;
513
518 public $multicurrency_tx;
519
523 public $multicurrency_total_ht;
524
528 public $multicurrency_total_tva;
529
533 public $multicurrency_total_ttc;
534
538 public $multicurrency_total_localtax1; // not in database
539
543 public $multicurrency_total_localtax2; // not in database
544
549 public $model_pdf;
550
555 public $last_main_doc;
556
562 public $fk_bank;
563
568 public $fk_account;
569
574 public $note_public;
575
580 public $note_private;
581
587 public $note;
588
593 public $total_ht;
594
599 public $total_tva;
600
605 public $total_localtax1;
606
611 public $total_localtax2;
612
617 public $total_ttc;
618
619
623 public $lines;
624
628 public $actiontypecode;
629
634 public $comments = array();
635
639 public $name;
640
644 public $lastname;
645
649 public $firstname;
650
654 public $civility_id;
655
656 // Dates
660 public $date_creation;
661
665 public $date_validation;
666
670 public $date_modification;
671
677 public $tms;
678
684 private $date_update;
685
689 public $date_cloture;
690
695 public $user_author;
696
701 public $user_creation;
702
706 public $user_creation_id;
707
712 public $user_valid;
713
718 public $user_validation;
719
723 public $user_validation_id;
724
728 public $user_closing_id;
729
734 public $user_modification;
735
739 public $user_modification_id;
740
745 public $fk_user_creat;
746
751 public $fk_user_modif;
752
753
757 public $next_prev_filter;
758
762 public $specimen = 0;
763
767 public $sendtoid;
768
774 private $alreadypaid;
775
779 public $totalpaid;
780
784 public $labelStatus = array();
785
789 public $labelStatusShort = array();
790
794 public $tpl;
795
796
800 public $showphoto_on_popup;
801
805 public $nb = array();
806
810 public $nbphoto;
811
815 public $output;
816
820 public $extraparams = array();
821
825 protected $childtables = array();
826
832 protected $childtablesoncascade = array();
833
837 public $product;
838
842 public $cond_reglement_supplier_id;
843
849 public $deposit_percent;
850
851
855 public $retained_warranty_fk_cond_reglement;
856
860 public $warehouse_id;
861
865 public $isextrafieldmanaged = 0;
866
867
868 // No constructor as it is an abstract class
869
875 protected function deprecatedProperties()
876 {
877 return array(
878 'alreadypaid' => 'totalpaid',
879 'cond_reglement' => 'depr_cond_reglement',
880 //'note' => 'note_private', // Some classes needs ->note and others need ->note_public/private so we can't manage deprecation for this field with dolDeprecationHandler
881 'commandeFournisseur' => 'origin_object',
882 'expedition' => 'origin_object',
883 'fk_project' => 'fk_project',
884 'livraison' => 'origin_object',
885 'projet' => 'project',
886 'statut' => 'status',
887 );
888 }
889
890
901 public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
902 {
903 global $db, $conf;
904
905 $sql = "SELECT rowid, ref, ref_ext";
906 $sql .= " FROM ".$db->prefix().$element;
907 $sql .= " WHERE entity IN (".getEntity($element).")";
908
909 if ($id > 0) {
910 $sql .= " AND rowid = ".((int) $id);
911 } elseif ($ref) {
912 $sql .= " AND ref = '".$db->escape($ref)."'";
913 } elseif ($ref_ext) {
914 $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
915 } else {
916 $error = 'ErrorWrongParameters';
917 dol_syslog(get_class()."::isExistingObject ".$error, LOG_ERR);
918 return -1;
919 }
920 if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
921 $sql .= " AND entity = ".((int) $conf->entity);
922 }
923
924 dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
925 $resql = $db->query($sql);
926 if ($resql) {
927 $num = $db->num_rows($resql);
928 if ($num > 0) {
929 return 1;
930 } else {
931 return 0;
932 }
933 }
934 return -1;
935 }
936
942 public function isEmpty()
943 {
944 return (empty($this->id));
945 }
946
954 {
955 if (!empty($object->error)) {
956 $this->error = $object->error;
957 }
958 if (!empty($object->errors)) {
959 $this->errors = array_merge($this->errors, $object->errors);
960 }
961 }
962
970 public function getTooltipContentArray($params)
971 {
972 return [];
973 }
974
982 public function getTooltipContent($params)
983 {
984 global $action, $extrafields, $langs, $hookmanager;
985
986 // If there is too much extrafields, we do not include them into tooltip
987 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
988
989 $data = $this->getTooltipContentArray($params);
990 $count = 0;
991
992 // Add extrafields
993 if (!empty($extrafields->attributes[$this->table_element]['label'])) {
994 $data['opendivextra'] = '<div class="centpercent wordbreak divtooltipextra">';
995 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
996 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
997 continue;
998 }
999 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1000 $data['more_extrafields'] = '<br>...';
1001 break;
1002 }
1003 $enabled = 1;
1004 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
1005 $enabled = (int) dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
1006 }
1007 if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
1008 $enabled = (int) dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
1009 }
1010 $perms = 1;
1011 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
1012 $perms = (int) dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
1013 }
1014 if (empty($enabled)) {
1015 continue; // 0 = Never visible field
1016 }
1017 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1018 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation
1019 }
1020 if (empty($perms)) {
1021 continue; // 0 = Not visible
1022 }
1023 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
1024 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
1025 }
1026 $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
1027 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
1028 $data[$key] = '<br><b><u>'. $labelextra . '</u></b>';
1029 } else {
1030 $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
1031 $data[$key] = '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
1032 $count++;
1033 }
1034 }
1035 $data['closedivextra'] = '</div>';
1036 }
1037
1038 $hookmanager->initHooks(array($this->element . 'dao'));
1039 $parameters = array(
1040 'tooltipcontentarray' => &$data,
1041 'params' => $params,
1042 );
1043 // Note that $action and $object may have been modified by some hooks
1044 $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
1045
1046 //var_dump($data);
1047 $label = implode($data);
1048
1049 return $label;
1050 }
1051
1052
1058 public function errorsToString()
1059 {
1060 return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').implode(', ', $this->errors)) : '');
1061 }
1062
1063
1070 public function getFormatedCustomerRef($objref)
1071 {
1072 global $hookmanager;
1073
1074 $parameters = array('objref' => $objref);
1075 $action = '';
1076 $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1077 if ($reshook > 0) {
1078 return $hookmanager->resArray['objref'];
1079 }
1080 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1081 }
1082
1089 public function getFormatedSupplierRef($objref)
1090 {
1091 global $hookmanager;
1092
1093 $parameters = array('objref' => $objref);
1094 $action = '';
1095 $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1096 if ($reshook > 0) {
1097 return $hookmanager->resArray['objref'];
1098 }
1099 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1100 }
1101
1111 public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
1112 {
1113 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1114 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1115 $tmparray = getCountry($this->country_id, 'all');
1116 $this->country_code = $tmparray['code'];
1117 $this->country = $tmparray['label'];
1118 }
1119
1120 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1121 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1122 $tmparray = getState($this->state_id, 'all', null, 1);
1123 $this->state_code = $tmparray['code'];
1124 $this->state = $tmparray['label'];
1125 $this->region_code = $tmparray['region_code'];
1126 $this->region = $tmparray['region'];
1127 }
1128
1129 return dol_format_address($this, $withcountry, $sep, null, 0, $extralangcode);
1130 }
1131
1132
1141 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1142 {
1143 global $user, $dolibarr_main_url_root;
1144
1145 if (empty($this->last_main_doc)) {
1146 return ''; // No way to known which document name to use
1147 }
1148
1149 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1150 $ecmfile = new EcmFiles($this->db);
1151 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1152 if ($result < 0) {
1153 $this->error = $ecmfile->error;
1154 $this->errors = $ecmfile->errors;
1155 return -1;
1156 }
1157
1158 if (empty($ecmfile->id)) { // No entry into file index already exists, we should initialize the shared key manually.
1159 // Add entry into index
1160 if ($initsharekey) {
1161 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1162
1163 // TODO We can't, we don't have full path of file, only last_main_doc and ->element, so we must first rebuild full path $destfull
1164 /*
1165 $ecmfile->filepath = $rel_dir;
1166 $ecmfile->filename = $filename;
1167 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1168 $ecmfile->fullpath_orig = '';
1169 $ecmfile->gen_or_uploaded = 'generated';
1170 $ecmfile->description = ''; // indexed content
1171 $ecmfile->keywords = ''; // keyword content
1172 $ecmfile->share = getRandomPassword(true);
1173 $result = $ecmfile->create($user);
1174 if ($result < 0)
1175 {
1176 $this->error = $ecmfile->error;
1177 $this->errors = $ecmfile->errors;
1178 }
1179 */
1180 } else {
1181 return '';
1182 }
1183 } elseif (empty($ecmfile->share)) { // Entry into file index already exists but no share key is defined.
1184 // Add entry into index
1185 if ($initsharekey) {
1186 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1187 $ecmfile->share = getRandomPassword(true);
1188 $ecmfile->update($user);
1189 } else {
1190 return '';
1191 }
1192 }
1193 // Define $urlwithroot
1194 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1195 // This is to use external domain name found into config file
1196 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1197 //else
1198 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1199 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1200
1201 $forcedownload = 0;
1202
1203 $paramlink = '';
1204 //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1205 //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1206 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1207 if (!empty($ecmfile->share)) {
1208 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1209 }
1210 if ($forcedownload) {
1211 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1212 }
1213
1214 if ($relativelink) {
1215 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1216 } else {
1217 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1218 }
1219
1220 // Here $ecmfile->share is defined
1221 return $linktoreturn;
1222 }
1223
1224
1225 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1235 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1236 {
1237 // phpcs:enable
1238 global $user, $langs;
1239
1240
1241 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1242
1243 // Check parameters
1244 if ($fk_socpeople <= 0) {
1245 $langs->load("errors");
1246 $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1247 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1248 return -1;
1249 }
1250 if (!$type_contact) {
1251 $langs->load("errors");
1252 $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1253 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1254 return -2;
1255 }
1256
1257 $id_type_contact = 0;
1258 if (is_numeric($type_contact)) {
1259 $id_type_contact = $type_contact;
1260 } else {
1261 // We look for id type_contact
1262 $sql = "SELECT tc.rowid";
1263 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1264 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1265 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1266 $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1267 //print $sql;
1268 $resql = $this->db->query($sql);
1269 if ($resql) {
1270 $obj = $this->db->fetch_object($resql);
1271 if ($obj) {
1272 $id_type_contact = $obj->rowid;
1273 }
1274 }
1275 }
1276
1277 if ($id_type_contact == 0) {
1278 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");
1279 return 0;
1280 }
1281
1282 $datecreate = dol_now();
1283
1284 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1285 $TListeContacts = $this->liste_contact(-1, $source);
1286 $already_added = false;
1287 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1288 foreach ($TListeContacts as $array_contact) {
1289 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1290 $already_added = true;
1291 break;
1292 }
1293 }
1294 }
1295
1296 if (!$already_added) {
1297 $this->db->begin();
1298
1299 // Insert into database
1300 $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1301 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1302 $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1303 $sql .= "'".$this->db->idate($datecreate)."'";
1304 $sql .= ", 4, ".((int) $id_type_contact);
1305 $sql .= ")";
1306
1307 $resql = $this->db->query($sql);
1308 if ($resql) {
1309 if (!$notrigger) {
1310 $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1311 if ($result < 0) {
1312 $this->db->rollback();
1313 return -1;
1314 }
1315 }
1316
1317 $this->db->commit();
1318 return 1;
1319 } else {
1320 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1321 $this->error = $this->db->errno();
1322 $this->db->rollback();
1323 return -2;
1324 } else {
1325 $this->error = $this->db->lasterror();
1326 $this->db->rollback();
1327 return -1;
1328 }
1329 }
1330 } else {
1331 return 0;
1332 }
1333 }
1334
1335 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1343 public function copy_linked_contact($objFrom, $source = 'internal')
1344 {
1345 // phpcs:enable
1346 $contacts = $objFrom->liste_contact(-1, $source);
1347 foreach ($contacts as $contact) {
1348 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1349 return -1;
1350 }
1351 }
1352 return 1;
1353 }
1354
1355 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1365 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1366 {
1367 // phpcs:enable
1368 // Insert into database
1369 $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1370 $sql .= " statut = ".$statut;
1371 if ($type_contact_id) {
1372 $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1373 }
1374 if ($fk_socpeople) {
1375 $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1376 }
1377 $sql .= " where rowid = ".((int) $rowid);
1378 $resql = $this->db->query($sql);
1379 if ($resql) {
1380 return 0;
1381 } else {
1382 $this->error = $this->db->lasterror();
1383 return -1;
1384 }
1385 }
1386
1387 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1395 public function delete_contact($rowid, $notrigger = 0)
1396 {
1397 // phpcs:enable
1398 global $user;
1399
1400 $error = 0;
1401
1402 $this->db->begin();
1403
1404 if (!$error && empty($notrigger)) {
1405 // Call trigger
1406 $this->context['contact_id'] = ((int) $rowid);
1407 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1408 if ($result < 0) {
1409 $error++;
1410 }
1411 // End call triggers
1412 }
1413
1414 if (!$error) {
1415 dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1416
1417 $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1418 $sql .= " WHERE rowid = ".((int) $rowid);
1419
1420 $result = $this->db->query($sql);
1421 if (!$result) {
1422 $error++;
1423 $this->errors[] = $this->db->lasterror();
1424 }
1425 }
1426
1427 if (!$error) {
1428 $this->db->commit();
1429 return 1;
1430 } else {
1431 $this->error = $this->db->lasterror();
1432 $this->db->rollback();
1433 return -1;
1434 }
1435 }
1436
1437 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1445 public function delete_linked_contact($source = '', $code = '')
1446 {
1447 // phpcs:enable
1448 $listId = '';
1449 $temp = array();
1450 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1451
1452 if (!empty($typeContact)) {
1453 foreach ($typeContact as $key => $value) {
1454 array_push($temp, $key);
1455 }
1456 $listId = implode(",", $temp);
1457 }
1458
1459 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1460 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1461 if (empty($listId)) {
1462 return 0;
1463 }
1464
1465 $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1466 $sql .= " WHERE element_id = ".((int) $this->id);
1467 $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1468
1469 dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1470 if ($this->db->query($sql)) {
1471 return 1;
1472 } else {
1473 $this->error = $this->db->lasterror();
1474 return -1;
1475 }
1476 }
1477
1478 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1490 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1491 {
1492 // phpcs:enable
1493 global $langs;
1494
1495 $tab = array();
1496
1497 $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
1498 if ($source == 'internal') {
1499 $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender";
1500 }
1501 if ($source == 'external' || $source == 'thirdparty') {
1502 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1503 }
1504 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1505 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
1506 $sql .= " FROM ".$this->db->prefix()."c_type_contact tc,";
1507 $sql .= " ".$this->db->prefix()."element_contact ec";
1508 if ($source == 'internal') { // internal contact (user)
1509 $sql .= " LEFT JOIN ".$this->db->prefix()."user t on ec.fk_socpeople = t.rowid";
1510 }
1511 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1512 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on ec.fk_socpeople = t.rowid";
1513 }
1514 $sql .= " WHERE ec.element_id = ".((int) $this->id);
1515 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1516 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1517 if ($code) {
1518 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1519 }
1520 if ($source == 'internal') {
1521 $sql .= " AND tc.source = 'internal'";
1522 if ($status >= 0) {
1523 $sql .= " AND t.statut = ".((int) $status);
1524 }
1525 }
1526 if ($source == 'external' || $source == 'thirdparty') {
1527 $sql .= " AND tc.source = 'external'";
1528 if ($status >= 0) {
1529 $sql .= " AND t.statut = ".((int) $status); // t is llx_socpeople
1530 }
1531 }
1532 $sql .= " AND tc.active = 1";
1533 if ($statusoflink >= 0) {
1534 $sql .= " AND ec.statut = ".((int) $statusoflink);
1535 }
1536 $sql .= " ORDER BY t.lastname ASC";
1537
1538 dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1539 $resql = $this->db->query($sql);
1540 if ($resql) {
1541 $num = $this->db->num_rows($resql);
1542 $i = 0;
1543 while ($i < $num) {
1544 $obj = $this->db->fetch_object($resql);
1545
1546 if (!$list) {
1547 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1548 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1549 $tab[$i] = array(
1550 'parentId' => $this->id,
1551 'source' => $obj->source,
1552 'socid' => $obj->socid,
1553 'id' => $obj->id,
1554 'nom' => $obj->lastname, // For backward compatibility
1555 'civility' => $obj->civility,
1556 'lastname' => $obj->lastname,
1557 'firstname' => $obj->firstname,
1558 'email' => $obj->email,
1559 'login' => (empty($obj->login) ? '' : $obj->login),
1560 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1561 'gender' => (empty($obj->gender) ? '' : $obj->gender),
1562 'statuscontact' => $obj->statuscontact,
1563 'rowid' => $obj->rowid,
1564 'code' => $obj->code,
1565 'libelle' => $libelle_type,
1566 'status' => $obj->statuslink,
1567 'fk_c_type_contact' => $obj->fk_c_type_contact
1568 );
1569 } else {
1570 $tab[$i] = $obj->id;
1571 }
1572
1573 $i++;
1574 }
1575
1576 return $tab;
1577 } else {
1578 $this->error = $this->db->lasterror();
1579 dol_print_error($this->db);
1580 return -1;
1581 }
1582 }
1583
1584
1591 public function swapContactStatus($rowid)
1592 {
1593 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1594 $sql .= " tc.code, tc.libelle as type_label";
1595 $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1596 $sql .= " WHERE ec.rowid =".((int) $rowid);
1597 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1598 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1599
1600 dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1601 $resql = $this->db->query($sql);
1602 if ($resql) {
1603 $obj = $this->db->fetch_object($resql);
1604 $newstatut = ($obj->statut == 4) ? 5 : 4;
1605 $result = $this->update_contact($rowid, $newstatut);
1606 $this->db->free($resql);
1607 return $result;
1608 } else {
1609 $this->error = $this->db->error();
1610 dol_print_error($this->db);
1611 return -1;
1612 }
1613 }
1614
1615 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1626 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1627 {
1628 // phpcs:enable
1629 global $langs;
1630
1631 if (empty($order)) {
1632 $order = 'position';
1633 }
1634 if ($order == 'position') {
1635 $order .= ',code';
1636 }
1637
1638 $tab = array();
1639 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1640 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1641 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1642 if ($activeonly == 1) {
1643 $sql .= " AND tc.active=1"; // only the active types
1644 }
1645 if (!empty($source) && $source != 'all') {
1646 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1647 }
1648 if (!empty($code)) {
1649 $sql .= " AND tc.code='".$this->db->escape($code)."'";
1650 }
1651 $sql .= $this->db->order($order, 'ASC');
1652
1653 //print "sql=".$sql;
1654 $resql = $this->db->query($sql);
1655 if ($resql) {
1656 $num = $this->db->num_rows($resql);
1657 $i = 0;
1658 while ($i < $num) {
1659 $obj = $this->db->fetch_object($resql);
1660
1661 $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1662 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1663 if (empty($option)) {
1664 $tab[$obj->rowid] = $libelle_type;
1665 } else {
1666 $tab[$obj->code] = $libelle_type;
1667 }
1668 $i++;
1669 }
1670 return $tab;
1671 } else {
1672 $this->error = $this->db->lasterror();
1673 //dol_print_error($this->db);
1674 return null;
1675 }
1676 }
1677
1689 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1690 {
1691 global $langs, $conf;
1692
1693 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1694
1695 $tab = array();
1696
1697 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element";
1698 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1699
1700 $sqlWhere = array();
1701 if (!empty($element)) {
1702 $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1703 }
1704 if (!empty($excludeelement)) {
1705 $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1706 }
1707
1708 if ($activeonly == 1) {
1709 $sqlWhere[] = " tc.active=1"; // only the active types
1710 }
1711
1712 if (!empty($source) && $source != 'all') {
1713 $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1714 }
1715
1716 if (!empty($code)) {
1717 $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1718 }
1719
1720 if (count($sqlWhere) > 0) {
1721 $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1722 }
1723
1724 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1725
1726 dol_syslog(__METHOD__, LOG_DEBUG);
1727 $resql = $this->db->query($sql);
1728 if ($resql) {
1729 $num = $this->db->num_rows($resql);
1730 if ($num > 0) {
1731 $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1732
1733 while ($obj = $this->db->fetch_object($resql)) {
1734 $modulename = $obj->element;
1735 if (strpos($obj->element, 'project') !== false) {
1736 $modulename = 'projet';
1737 } elseif ($obj->element == 'contrat') {
1738 $element = 'contract';
1739 } elseif ($obj->element == 'action') {
1740 $modulename = 'agenda';
1741 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1742 $modulename = 'fournisseur';
1743 }
1744 if (!empty($conf->{$modulename}->enabled)) {
1745 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1746 $tmpelement = $obj->element;
1747 $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1748 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1749 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1750 }
1751 }
1752 }
1753 return $tab;
1754 } else {
1755 $this->error = $this->db->lasterror();
1756 return null;
1757 }
1758 }
1759
1771 public function getIdContact($source, $code, $status = 0)
1772 {
1773 global $conf;
1774
1775 $result = array();
1776 $i = 0;
1777 // Particular case for shipping
1778 if ($this->element == 'shipping' && $this->origin_id != 0) {
1779 $id = $this->origin_id;
1780 $element = 'commande';
1781 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1782 $id = $this->origin_id;
1783 $element = 'order_supplier';
1784 } else {
1785 $id = $this->id;
1786 $element = $this->element;
1787 }
1788
1789 $sql = "SELECT ec.fk_socpeople";
1790 $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1791 if ($source == 'internal') {
1792 $sql .= " ".$this->db->prefix()."user as c,";
1793 }
1794 if ($source == 'external') {
1795 $sql .= " ".$this->db->prefix()."socpeople as c,";
1796 }
1797 $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1798 $sql .= " WHERE ec.element_id = ".((int) $id);
1799 $sql .= " AND ec.fk_socpeople = c.rowid";
1800 if ($source == 'internal') {
1801 $sql .= " AND c.entity IN (".getEntity('user').")";
1802 }
1803 if ($source == 'external') {
1804 $sql .= " AND c.entity IN (".getEntity('societe').")";
1805 }
1806 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1807 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1808 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1809 if ($code) {
1810 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1811 }
1812 $sql .= " AND tc.active = 1";
1813 if ($status) {
1814 $sql .= " AND ec.statut = ".((int) $status);
1815 }
1816
1817 dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1818 $resql = $this->db->query($sql);
1819 if ($resql) {
1820 while ($obj = $this->db->fetch_object($resql)) {
1821 $result[$i] = $obj->fk_socpeople;
1822 $i++;
1823 }
1824 } else {
1825 $this->error = $this->db->error();
1826 return null;
1827 }
1828
1829 return $result;
1830 }
1831
1832 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1839 public function fetch_contact($contactid = null)
1840 {
1841 // phpcs:enable
1842 if (empty($contactid)) {
1843 $contactid = $this->contact_id;
1844 }
1845
1846 if (empty($contactid)) {
1847 return 0;
1848 }
1849
1850 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1851 $contact = new Contact($this->db);
1852 $result = $contact->fetch($contactid);
1853 $this->contact = $contact;
1854 return $result;
1855 }
1856
1857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1865 public function fetch_thirdparty($force_thirdparty_id = 0)
1866 {
1867 // phpcs:enable
1868 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1869 return 0;
1870 }
1871
1872 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1873
1874 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1875 if ($force_thirdparty_id) {
1876 $idtofetch = $force_thirdparty_id;
1877 }
1878
1879 if ($idtofetch) {
1880 $thirdparty = new Societe($this->db);
1881 $result = $thirdparty->fetch($idtofetch);
1882 if ($result < 0) {
1883 $this->errors = array_merge($this->errors, $thirdparty->errors);
1884 }
1885 $this->thirdparty = $thirdparty;
1886
1887 // Use first price level if level not defined for third party
1888 if (getDolGlobalString('PRODUIT_MULTIPRICES') && empty($this->thirdparty->price_level)) {
1889 $this->thirdparty->price_level = 1;
1890 }
1891
1892 return $result;
1893 } else {
1894 return -1;
1895 }
1896 }
1897
1898
1906 public function fetchOneLike($ref)
1907 {
1908 if (!$this->table_ref_field) {
1909 return 0;
1910 }
1911
1912 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1913 $sql .= " WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."'"; // no escapeforlike here
1914 $sql .= " LIMIT 1";
1915
1916 $query = $this->db->query($sql);
1917
1918 if (!$this->db->num_rows($query)) {
1919 return 0;
1920 }
1921
1922 $result = $this->db->fetch_object($query);
1923
1924 if (method_exists($this, 'fetch')) {
1925 return $this->fetch($result->rowid);
1926 } else {
1927 $this->error = 'Fetch method not implemented on '.get_class($this);
1928 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
1929 array_push($this->errors, $this->error);
1930 return -1;
1931 }
1932 }
1933
1934 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1942 public function fetch_barcode()
1943 {
1944 // phpcs:enable
1945 global $conf;
1946
1947 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1948
1949 $idtype = $this->barcode_type;
1950 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
1951 if ($this->element == 'product' && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) {
1952 $idtype = getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE');
1953 } elseif ($this->element == 'societe') {
1954 $idtype = getDolGlobalString('GENBARCODE_BARCODETYPE_THIRDPARTY');
1955 } else {
1956 dol_syslog('Call fetch_barcode with barcode_type not defined and cannot be guessed', LOG_WARNING);
1957 }
1958 }
1959
1960 if ($idtype > 0) {
1961 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
1962 $sql = "SELECT rowid, code, libelle as label, coder";
1963 $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1964 $sql .= " WHERE rowid = ".((int) $idtype);
1965 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1966 $resql = $this->db->query($sql);
1967 if ($resql) {
1968 $obj = $this->db->fetch_object($resql);
1969 $this->barcode_type = $obj->rowid;
1970 $this->barcode_type_code = $obj->code;
1971 $this->barcode_type_label = $obj->label;
1972 $this->barcode_type_coder = $obj->coder;
1973 return 1;
1974 } else {
1975 dol_print_error($this->db);
1976 return -1;
1977 }
1978 }
1979 }
1980 return 0;
1981 }
1982
1983 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1989 public function fetch_project()
1990 {
1991 // phpcs:enable
1992 return $this->fetch_projet();
1993 }
1994
1995 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2001 public function fetch_projet()
2002 {
2003 // phpcs:enable
2004 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
2005
2006 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2007 $this->fk_project = $this->fk_projet; // For backward compatibility
2008 }
2009 if (empty($this->fk_project)) {
2010 return 0;
2011 }
2012
2013 $project = new Project($this->db);
2014 $result = $project->fetch($this->fk_project);
2015
2016 $this->projet = $project; // deprecated
2017 $this->project = $project;
2018 return $result;
2019 }
2020
2021 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2027 public function fetch_product()
2028 {
2029 // phpcs:enable
2030 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2031
2032 // @phan-suppress-next-line PhanUndeclaredProperty
2033 if (empty($this->fk_product)) {
2034 return 0;
2035 }
2036
2037 $product = new Product($this->db);
2038 // @phan-suppress-next-line PhanUndeclaredProperty
2039 $result = $product->fetch($this->fk_product);
2040
2041 $this->product = $product;
2042 return $result;
2043 }
2044
2045 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2052 public function fetch_user($userid)
2053 {
2054 // phpcs:enable
2055 $user = new User($this->db);
2056 $result = $user->fetch($userid);
2057 $this->user = $user;
2058 return $result;
2059 }
2060
2061 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2068 public function fetch_origin()
2069 {
2070 // phpcs:enable
2071 $origin = $this->origin ? $this->origin : $this->origin_type;
2072
2073 // Manage classes with non standard name
2074 if ($origin == 'shipping') {
2075 $origin = 'expedition';
2076 }
2077 if ($origin == 'delivery') {
2078 $origin = 'livraison';
2079 }
2080 if ($origin == 'order_supplier' || $origin == 'supplier_order') {
2081 $origin = 'commandeFournisseur';
2082 }
2083
2084 $classname = ucfirst($origin);
2085 $this->origin_object = new $classname($this->db);
2086 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
2087 $this->origin_object->fetch($this->origin_id);
2088 }
2089
2099 public function fetchObjectFrom($table, $field, $key, $element = null)
2100 {
2101 global $conf;
2102
2103 $result = false;
2104
2105 $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
2106 $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
2107 if (!empty($element)) {
2108 $sql .= " AND entity IN (".getEntity($element).")";
2109 } else {
2110 $sql .= " AND entity = ".((int) $conf->entity);
2111 }
2112
2113 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
2114 $resql = $this->db->query($sql);
2115 if ($resql) {
2116 $obj = $this->db->fetch_object($resql);
2117 // Test for avoid error -1
2118 if ($obj) {
2119 if (method_exists($this, 'fetch')) {
2120 $result = $this->fetch($obj->rowid);
2121 } else {
2122 $this->error = 'fetch() method not implemented on '.get_class($this);
2123 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2124 array_push($this->errors, $this->error);
2125 $result = -1;
2126 }
2127 }
2128 }
2129
2130 return $result;
2131 }
2132
2141 public function getValueFrom($table, $id, $field)
2142 {
2143 $result = false;
2144 if (!empty($id) && !empty($field) && !empty($table)) {
2145 $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
2146 $sql .= " WHERE rowid = ".((int) $id);
2147
2148 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2149 $resql = $this->db->query($sql);
2150 if ($resql) {
2151 $row = $this->db->fetch_row($resql);
2152 $result = $row[0];
2153 }
2154 }
2155 return $result;
2156 }
2157
2174 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2175 {
2176 global $user;
2177
2178 if (empty($table)) {
2179 $table = $this->table_element;
2180 }
2181 if (empty($id)) {
2182 $id = $this->id;
2183 }
2184 if (empty($format)) {
2185 $format = 'text';
2186 }
2187 if (empty($id_field)) {
2188 $id_field = 'rowid';
2189 }
2190
2191 // Special case
2192 if ($table == 'product' && $field == 'note_private') {
2193 $field = 'note';
2194 }
2195
2196 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2197 $fk_user_field = 'fk_user_mod';
2198 }
2199 if (in_array($table, array('prelevement_bons'))) { // TODO Add a field fk_user_modif into llx_prelevement_bons
2200 $fk_user_field = '';
2201 }
2202
2203 $oldvalue = null;
2204 if ($trigkey) {
2205 $sql = "SELECT " . $field;
2206 $sql .= " FROM " . MAIN_DB_PREFIX . $table;
2207 $sql .= " WHERE " . $id_field . " = " . ((int) $id);
2208
2209 $resql = $this->db->query($sql);
2210 if ($resql) {
2211 if ($obj = $this->db->fetch_object($resql)) {
2212 if ($format == 'date') {
2213 $oldvalue = $this->db->jdate($obj->$field);
2214 } else {
2215 $oldvalue = $obj->$field;
2216 }
2217 }
2218 } else {
2219 $this->error = $this->db->lasterror();
2220 return -1;
2221 }
2222 }
2223
2224 $error = 0;
2225
2226 dol_syslog(__METHOD__, LOG_DEBUG);
2227
2228 $this->db->begin();
2229
2230 $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2231
2232 if ($format == 'text') {
2233 $sql .= $field." = '".$this->db->escape($value)."'";
2234 } elseif ($format == 'int') {
2235 $sql .= $field." = ".((int) $value);
2236 } elseif ($format == 'date') {
2237 $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2238 } elseif ($format == 'dategmt') {
2239 $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
2240 }
2241
2242 if ($fk_user_field) {
2243 if (!empty($fuser) && is_object($fuser)) {
2244 $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2245 } elseif (empty($fuser) || $fuser != 'none') {
2246 $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2247 }
2248 }
2249
2250 $sql .= " WHERE ".$id_field." = ".((int) $id);
2251
2252 $resql = $this->db->query($sql);
2253 if ($resql) {
2254 if ($trigkey) {
2255 // call trigger with updated object values
2256 if (method_exists($this, 'fetch')) {
2257 $result = $this->fetch($id);
2258 } else {
2259 $result = $this->fetchCommon($id);
2260 }
2261 $this->oldcopy = clone $this;
2262 if (property_exists($this->oldcopy, $field)) {
2263 $this->oldcopy->$field = $oldvalue;
2264 }
2265
2266 if ($result >= 0) {
2267 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2268 }
2269 if ($result < 0) {
2270 $error++;
2271 }
2272 }
2273
2274 if (!$error) {
2275 if (property_exists($this, $field)) {
2276 $this->$field = $value;
2277 }
2278 $this->db->commit();
2279 return 1;
2280 } else {
2281 $this->db->rollback();
2282 return -2;
2283 }
2284 } else {
2285 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2286 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2287 } else {
2288 $this->error = $this->db->lasterror();
2289 }
2290 $this->db->rollback();
2291 return -1;
2292 }
2293 }
2294
2295 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2306 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2307 {
2308 // phpcs:enable
2309 global $conf, $user;
2310
2311 if (!$this->table_element) {
2312 dol_print_error(null, get_class($this)."::load_previous_next_ref was called on object with property table_element not defined");
2313 return -1;
2314 }
2315 if ($fieldid == 'none') {
2316 return 1;
2317 }
2318
2319 // For backward compatibility
2320 if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2321 $fieldid = 'titre';
2322 }
2323
2324 // Security on socid
2325 $socid = 0;
2326 if ($user->socid > 0) {
2327 $socid = $user->socid;
2328 }
2329
2330 // this->ismultientitymanaged contains
2331 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2332 $aliastablesociete = 's';
2333 if ($this->element == 'societe') {
2334 $aliastablesociete = 'te'; // te as table_element
2335 }
2336 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2337 $sql = "SELECT MAX(te.".$fieldid.")";
2338 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2339 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2340 $tmparray = explode('@', $this->ismultientitymanaged);
2341 $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
2342 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2343 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2344 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2345 $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
2346 }
2347 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2348 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2349 }
2350 if ($fieldid == 'rowid') {
2351 $sql .= " WHERE te.".$fieldid." < ".((int) $this->id);
2352 } else {
2353 $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2354 }
2355 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2356 $sql .= " AND sc.fk_user = ".((int) $user->id);
2357 }
2358 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2359 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2360 }
2361
2362 $filtermax = $filter;
2363
2364 // Manage filter
2365 $errormessage = '';
2366 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermax, $errormessage);
2367 if ($errormessage) {
2368 if (!preg_match('/^\s*AND/i', $filtermax)) {
2369 $sql .= " AND ";
2370 }
2371 $sql .= $filtermax;
2372 } else {
2373 $sql .= $tmpsql;
2374 }
2375
2376 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2377 $tmparray = explode('@', $this->ismultientitymanaged);
2378 $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2379 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2380 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2381 }
2382 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2383 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2384 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2385 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2386 } else {
2387 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2388 }
2389 } else {
2390 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2391 }
2392 }
2393 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2394 $tmparray = explode('@', $this->ismultientitymanaged);
2395 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2396 }
2397 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2398 $sql .= ' AND te.fk_soc = '.((int) $socid);
2399 }
2400 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2401 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2402 }
2403 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2404 $sql .= ' AND te.rowid = '.((int) $socid);
2405 }
2406 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2407
2408 $result = $this->db->query($sql);
2409 if (!$result) {
2410 $this->error = $this->db->lasterror();
2411 return -1;
2412 }
2413 $row = $this->db->fetch_row($result);
2414 $this->ref_previous = $row[0];
2415
2416 $sql = "SELECT MIN(te.".$fieldid.")";
2417 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2418 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2419 $tmparray = explode('@', $this->ismultientitymanaged);
2420 $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
2421 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2422 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2423 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2424 $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
2425 }
2426 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2427 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2428 }
2429 if ($fieldid == 'rowid') {
2430 $sql .= " WHERE te.".$fieldid." > ".((int) $this->id);
2431 } else {
2432 $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2433 }
2434 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2435 $sql .= " AND (sc.fk_user = ".((int) $user->id);
2436 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
2437 $userschilds = $user->getAllChildIds();
2438 $sql .= " OR sc.fk_user IN (".$this->db->sanitize(implode(',', $userschilds)).")";
2439 }
2440 $sql .= ')';
2441 }
2442 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2443 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2444 }
2445
2446 $filtermin = $filter;
2447
2448 // Manage filter
2449 $errormessage = '';
2450 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermin, $errormessage);
2451 if ($errormessage) {
2452 if (!preg_match('/^\s*AND/i', $filtermin)) {
2453 $sql .= " AND ";
2454 }
2455 $sql .= $filtermin;
2456
2457 $filtermin = '';
2458 } else {
2459 $sql .= $tmpsql;
2460 }
2461
2462 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2463 $tmparray = explode('@', $this->ismultientitymanaged);
2464 $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2465 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2466 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2467 }
2468 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2469 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2470 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2471 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2472 } else {
2473 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2474 }
2475 } else {
2476 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2477 }
2478 }
2479 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2480 $tmparray = explode('@', $this->ismultientitymanaged);
2481 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2482 }
2483 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2484 $sql .= ' AND te.fk_soc = '.((int) $socid);
2485 }
2486 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2487 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2488 }
2489 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2490 $sql .= ' AND te.rowid = '.((int) $socid);
2491 }
2492 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2493 // 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
2494
2495 $result = $this->db->query($sql);
2496 if (!$result) {
2497 $this->error = $this->db->lasterror();
2498 return -2;
2499 }
2500 $row = $this->db->fetch_row($result);
2501 $this->ref_next = $row[0];
2502
2503 return 1;
2504 }
2505
2506
2514 public function getListContactId($source = 'external')
2515 {
2516 $contactAlreadySelected = array();
2517 $tab = $this->liste_contact(-1, $source);
2518 $num = count($tab);
2519 $i = 0;
2520 while ($i < $num) {
2521 if ($source == 'thirdparty') {
2522 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2523 } else {
2524 $contactAlreadySelected[$i] = $tab[$i]['id'];
2525 }
2526 $i++;
2527 }
2528 return $contactAlreadySelected;
2529 }
2530
2531
2539 public function setProject($projectid, $notrigger = 0)
2540 {
2541 global $user;
2542 $error = 0;
2543
2544 if (!$this->table_element) {
2545 dol_syslog(get_class($this)."::setProject was called on object with property table_element not defined", LOG_ERR);
2546 return -1;
2547 }
2548
2549 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2550 if (!empty($this->fields['fk_project'])) { // Common case
2551 if ($projectid) {
2552 $sql .= " SET fk_project = ".((int) $projectid);
2553 } else {
2554 $sql .= " SET fk_project = NULL";
2555 }
2556 $sql .= ' WHERE rowid = '.((int) $this->id);
2557 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2558 if ($projectid) {
2559 $sql .= " SET fk_project = ".((int) $projectid);
2560 } else {
2561 $sql .= " SET fk_project = NULL";
2562 }
2563 $sql .= ' WHERE id = '.((int) $this->id);
2564 } else { // Special case for old architecture objects
2565 if ($projectid) {
2566 $sql .= ' SET fk_projet = '.((int) $projectid);
2567 } else {
2568 $sql .= ' SET fk_projet = NULL';
2569 }
2570 $sql .= " WHERE rowid = ".((int) $this->id);
2571 }
2572
2573 $this->db->begin();
2574
2575 dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2576 if ($this->db->query($sql)) {
2577 $this->fk_project = ((int) $projectid);
2578 } else {
2579 dol_print_error($this->db);
2580 $error++;
2581 }
2582
2583 // Triggers
2584 if (!$error && !$notrigger) {
2585 // Call triggers
2586 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2587 if ($result < 0) {
2588 $error++;
2589 } //Do also here what you must do to rollback action if trigger fail
2590 // End call triggers
2591 }
2592
2593 // Commit or rollback
2594 if ($error) {
2595 $this->db->rollback();
2596 return -1;
2597 } else {
2598 $this->db->commit();
2599 return 1;
2600 }
2601 }
2602
2609 public function setPaymentMethods($id)
2610 {
2611 global $user;
2612
2613 $error = 0;
2614 $notrigger = 0;
2615
2616 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2617
2618 if ($this->status >= 0 || $this->element == 'societe') {
2619 // TODO uniformize field name
2620 $fieldname = 'fk_mode_reglement';
2621 if ($this->element == 'societe') {
2622 $fieldname = 'mode_reglement';
2623 }
2624 if (get_class($this) == 'Fournisseur') {
2625 $fieldname = 'mode_reglement_supplier';
2626 }
2627 if (get_class($this) == 'Tva') {
2628 $fieldname = 'fk_typepayment';
2629 }
2630 if (get_class($this) == 'Salary') {
2631 $fieldname = 'fk_typepayment';
2632 }
2633
2634 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2635 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2636 $sql .= ' WHERE rowid='.((int) $this->id);
2637
2638 if ($this->db->query($sql)) {
2639 $this->mode_reglement_id = $id;
2640 // for supplier
2641 if (get_class($this) == 'Fournisseur') {
2642 $this->mode_reglement_supplier_id = $id;
2643 }
2644 // Triggers
2645 if (!$error && !$notrigger) {
2646 // Call triggers
2647 if (get_class($this) == 'Commande') {
2648 $result = $this->call_trigger('ORDER_MODIFY', $user);
2649 } else {
2650 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2651 }
2652 if ($result < 0) {
2653 $error++;
2654 }
2655 // End call triggers
2656 }
2657 return 1;
2658 } else {
2659 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2660 $this->error = $this->db->error();
2661 return -1;
2662 }
2663 } else {
2664 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2665 $this->error = 'Status of the object is incompatible '.$this->status;
2666 return -2;
2667 }
2668 }
2669
2676 public function setMulticurrencyCode($code)
2677 {
2678 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2679 if ($this->status >= 0 || $this->element == 'societe') {
2680 $fieldname = 'multicurrency_code';
2681
2682 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2683 $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2684 $sql .= ' WHERE rowid='.((int) $this->id);
2685
2686 if ($this->db->query($sql)) {
2687 $this->multicurrency_code = $code;
2688
2689 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2690 if ($rate) {
2691 $this->setMulticurrencyRate($rate, 2);
2692 }
2693
2694 return 1;
2695 } else {
2696 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2697 $this->error = $this->db->error();
2698 return -1;
2699 }
2700 } else {
2701 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2702 $this->error = 'Status of the object is incompatible '.$this->status;
2703 return -2;
2704 }
2705 }
2706
2714 public function setMulticurrencyRate($rate, $mode = 1)
2715 {
2716 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.', '.$mode.')');
2717 if ($this->status >= 0 || $this->element == 'societe') {
2718 $fieldname = 'multicurrency_tx';
2719
2720 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2721 $sql .= " SET ".$fieldname." = ".((float) $rate);
2722 $sql .= ' WHERE rowid='.((int) $this->id);
2723
2724 if ($this->db->query($sql)) {
2725 $this->multicurrency_tx = $rate;
2726
2727 // Update line price
2728 if (!empty($this->lines)) {
2729 foreach ($this->lines as &$line) {
2730 // Amounts in company currency will be recalculated
2731 if ($mode == 1) {
2732 $line->subprice = 0;
2733 }
2734
2735 // Amounts in foreign currency will be recalculated
2736 if ($mode == 2) {
2737 $line->multicurrency_subprice = 0;
2738 }
2739
2740 switch ($this->element) {
2741 case 'propal':
2744 $this->updateline(
2745 $line->id,
2746 $line->subprice,
2747 $line->qty,
2748 $line->remise_percent,
2749 $line->tva_tx,
2750 $line->localtax1_tx,
2751 $line->localtax2_tx,
2752 ($line->description ? $line->description : $line->desc),
2753 'HT',
2754 $line->info_bits,
2755 $line->special_code,
2756 $line->fk_parent_line,
2757 $line->skip_update_total,
2758 $line->fk_fournprice,
2759 $line->pa_ht,
2760 $line->label,
2761 $line->product_type,
2762 $line->date_start,
2763 $line->date_end,
2764 $line->array_options,
2765 $line->fk_unit,
2766 $line->multicurrency_subprice
2767 );
2768 break;
2769 case 'commande':
2772 $this->updateline(
2773 $line->id,
2774 ($line->description ? $line->description : $line->desc),
2775 $line->subprice,
2776 $line->qty,
2777 $line->remise_percent,
2778 $line->tva_tx,
2779 $line->localtax1_tx,
2780 $line->localtax2_tx,
2781 'HT',
2782 $line->info_bits,
2783 $line->date_start,
2784 $line->date_end,
2785 $line->product_type,
2786 $line->fk_parent_line,
2787 $line->skip_update_total,
2788 $line->fk_fournprice,
2789 $line->pa_ht,
2790 $line->label,
2791 $line->special_code,
2792 $line->array_options,
2793 $line->fk_unit,
2794 $line->multicurrency_subprice
2795 );
2796 break;
2797 case 'facture':
2800 $this->updateline(
2801 $line->id,
2802 ($line->description ? $line->description : $line->desc),
2803 $line->subprice,
2804 $line->qty,
2805 $line->remise_percent,
2806 $line->date_start,
2807 $line->date_end,
2808 $line->tva_tx,
2809 $line->localtax1_tx,
2810 $line->localtax2_tx,
2811 'HT',
2812 $line->info_bits,
2813 $line->product_type,
2814 $line->fk_parent_line,
2815 $line->skip_update_total,
2816 $line->fk_fournprice,
2817 $line->pa_ht,
2818 $line->label,
2819 $line->special_code,
2820 $line->array_options,
2821 $line->situation_percent,
2822 $line->fk_unit,
2823 $line->multicurrency_subprice
2824 );
2825 break;
2826 case 'supplier_proposal':
2829 $this->updateline(
2830 $line->id,
2831 $line->subprice,
2832 $line->qty,
2833 $line->remise_percent,
2834 $line->tva_tx,
2835 $line->localtax1_tx,
2836 $line->localtax2_tx,
2837 ($line->description ? $line->description : $line->desc),
2838 'HT',
2839 $line->info_bits,
2840 $line->special_code,
2841 $line->fk_parent_line,
2842 $line->skip_update_total,
2843 $line->fk_fournprice,
2844 $line->pa_ht,
2845 $line->label,
2846 $line->product_type,
2847 $line->array_options,
2848 $line->ref_fourn,
2849 $line->multicurrency_subprice
2850 );
2851 break;
2852 case 'order_supplier':
2855 $this->updateline(
2856 $line->id,
2857 ($line->description ? $line->description : $line->desc),
2858 $line->subprice,
2859 $line->qty,
2860 $line->remise_percent,
2861 $line->tva_tx,
2862 $line->localtax1_tx,
2863 $line->localtax2_tx,
2864 'HT',
2865 $line->info_bits,
2866 $line->product_type,
2867 false,
2868 $line->date_start,
2869 $line->date_end,
2870 $line->array_options,
2871 $line->fk_unit,
2872 $line->multicurrency_subprice,
2873 $line->ref_supplier
2874 );
2875 break;
2876 case 'invoice_supplier':
2879 $this->updateline(
2880 $line->id,
2881 ($line->description ? $line->description : $line->desc),
2882 $line->subprice,
2883 $line->tva_tx,
2884 $line->localtax1_tx,
2885 $line->localtax2_tx,
2886 $line->qty,
2887 0,
2888 'HT',
2889 $line->info_bits,
2890 $line->product_type,
2891 $line->remise_percent,
2892 false,
2893 $line->date_start,
2894 $line->date_end,
2895 $line->array_options,
2896 $line->fk_unit,
2897 $line->multicurrency_subprice,
2898 $line->ref_supplier
2899 );
2900 break;
2901 default:
2902 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2903 break;
2904 }
2905 }
2906 }
2907
2908 return 1;
2909 } else {
2910 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2911 $this->error = $this->db->error();
2912 return -1;
2913 }
2914 } else {
2915 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2916 $this->error = 'Status of the object is incompatible '.$this->status;
2917 return -2;
2918 }
2919 }
2920
2928 public function setPaymentTerms($id, $deposit_percent = null)
2929 {
2930 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2931 if ($this->status >= 0 || $this->element == 'societe') {
2932 // TODO uniformize field name
2933 $fieldname = 'fk_cond_reglement';
2934 if ($this->element == 'societe') {
2935 $fieldname = 'cond_reglement';
2936 }
2937 if (get_class($this) == 'Fournisseur') {
2938 $fieldname = 'cond_reglement_supplier';
2939 }
2940
2941 if (empty($deposit_percent) || $deposit_percent < 0) {
2942 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2943 }
2944
2945 if ($deposit_percent > 100) {
2946 $deposit_percent = 100;
2947 }
2948
2949 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2950 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2951 if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
2952 $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2953 }
2954 $sql .= ' WHERE rowid='.((int) $this->id);
2955
2956 if ($this->db->query($sql)) {
2957 $this->cond_reglement_id = $id;
2958 // for supplier
2959 if (get_class($this) == 'Fournisseur') {
2960 $this->cond_reglement_supplier_id = $id;
2961 }
2962 $this->cond_reglement = $id; // for compatibility
2963 $this->deposit_percent = $deposit_percent;
2964 return 1;
2965 } else {
2966 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2967 $this->error = $this->db->error();
2968 return -1;
2969 }
2970 } else {
2971 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2972 $this->error = 'Status of the object is incompatible '.$this->status;
2973 return -2;
2974 }
2975 }
2976
2983 public function setTransportMode($id)
2984 {
2985 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
2986 if ($this->status >= 0 || $this->element == 'societe') {
2987 $fieldname = 'fk_transport_mode';
2988 if ($this->element == 'societe') {
2989 $fieldname = 'transport_mode';
2990 }
2991 if (get_class($this) == 'Fournisseur') {
2992 $fieldname = 'transport_mode_supplier';
2993 }
2994
2995 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2996 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2997 $sql .= ' WHERE rowid='.((int) $this->id);
2998
2999 if ($this->db->query($sql)) {
3000 $this->transport_mode_id = $id;
3001 // for supplier
3002 if (get_class($this) == 'Fournisseur') {
3003 $this->transport_mode_supplier_id = $id;
3004 }
3005 return 1;
3006 } else {
3007 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
3008 $this->error = $this->db->error();
3009 return -1;
3010 }
3011 } else {
3012 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
3013 $this->error = 'Status of the object is incompatible '.$this->status;
3014 return -2;
3015 }
3016 }
3017
3025 {
3026 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
3027 if ($this->status >= 0 || $this->element == 'societe') {
3028 $fieldname = 'retained_warranty_fk_cond_reglement';
3029
3030 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3031 $sql .= " SET ".$fieldname." = ".((int) $id);
3032 $sql .= ' WHERE rowid='.((int) $this->id);
3033
3034 if ($this->db->query($sql)) {
3035 $this->retained_warranty_fk_cond_reglement = $id;
3036 return 1;
3037 } else {
3038 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
3039 $this->error = $this->db->error();
3040 return -1;
3041 }
3042 } else {
3043 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3044 $this->error = 'Status of the object is incompatible '.$this->status;
3045 return -2;
3046 }
3047 }
3048
3056 public function setDeliveryAddress($id)
3057 {
3058 $fieldname = 'fk_delivery_address';
3059 if ($this->element == 'delivery' || $this->element == 'shipping') {
3060 $fieldname = 'fk_address';
3061 }
3062
3063 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
3064 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
3065
3066 if ($this->db->query($sql)) {
3067 $this->fk_delivery_address = $id;
3068 return 1;
3069 } else {
3070 $this->error = $this->db->error();
3071 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
3072 return -1;
3073 }
3074 }
3075
3076
3085 public function setShippingMethod($shipping_method_id, $notrigger = 0, $userused = null)
3086 {
3087 global $user;
3088
3089 if (empty($userused)) {
3090 $userused = $user;
3091 }
3092
3093 $error = 0;
3094
3095 if (!$this->table_element) {
3096 dol_syslog(get_class($this)."::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3097 return -1;
3098 }
3099
3100 $this->db->begin();
3101
3102 if ($shipping_method_id < 0) {
3103 $shipping_method_id = 'NULL';
3104 }
3105 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
3106
3107 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3108 $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
3109 $sql .= " WHERE rowid=".((int) $this->id);
3110 $resql = $this->db->query($sql);
3111 if (!$resql) {
3112 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
3113 $this->error = $this->db->lasterror();
3114 $error++;
3115 } else {
3116 if (!$notrigger) {
3117 // Call trigger
3118 $this->context = array('shippingmethodupdate' => 1);
3119 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3120 if ($result < 0) {
3121 $error++;
3122 }
3123 // End call trigger
3124 }
3125 }
3126 if ($error) {
3127 $this->db->rollback();
3128 return -1;
3129 } else {
3130 $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id;
3131 $this->db->commit();
3132 return 1;
3133 }
3134 }
3135
3136
3143 public function setWarehouse($warehouse_id)
3144 {
3145 if (!$this->table_element) {
3146 dol_syslog(get_class($this)."::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3147 return -1;
3148 }
3149 if ($warehouse_id < 0) {
3150 $warehouse_id = 'NULL';
3151 }
3152 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
3153
3154 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3155 $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
3156 $sql .= " WHERE rowid=".((int) $this->id);
3157
3158 if ($this->db->query($sql)) {
3159 $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id;
3160 return 1;
3161 } else {
3162 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
3163 $this->error = $this->db->error();
3164 return 0;
3165 }
3166 }
3167
3168
3176 public function setDocModel($user, $modelpdf)
3177 {
3178 if (!$this->table_element) {
3179 dol_syslog(get_class($this)."::setDocModel was called on object with property table_element not defined", LOG_ERR);
3180 return -1;
3181 }
3182
3183 $newmodelpdf = dol_trunc($modelpdf, 255);
3184
3185 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3186 $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
3187 $sql .= " WHERE rowid = ".((int) $this->id);
3188
3189 dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
3190 $resql = $this->db->query($sql);
3191 if ($resql) {
3192 $this->model_pdf = $modelpdf;
3193 return 1;
3194 } else {
3195 dol_print_error($this->db);
3196 return 0;
3197 }
3198 }
3199
3200
3209 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
3210 {
3211 global $user;
3212
3213 if (empty($userused)) {
3214 $userused = $user;
3215 }
3216
3217 $error = 0;
3218
3219 if (!$this->table_element) {
3220 dol_syslog(get_class($this)."::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3221 return -1;
3222 }
3223 $this->db->begin();
3224
3225 if ($fk_account < 0) {
3226 $fk_account = 'NULL';
3227 }
3228 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3229
3230 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3231 $sql .= " SET fk_account = ".((int) $fk_account);
3232 $sql .= " WHERE rowid=".((int) $this->id);
3233
3234 $resql = $this->db->query($sql);
3235 if (!$resql) {
3236 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3237 $this->error = $this->db->lasterror();
3238 $error++;
3239 } else {
3240 if (!$notrigger) {
3241 // Call trigger
3242 $this->context['bankaccountupdate'] = 1;
3243 $triggerName = strtoupper(get_class($this)).'_MODIFY';
3244 // Special cases
3245 if ($triggerName == 'FACTUREREC_MODIFY') {
3246 $triggerName = 'BILLREC_MODIFY';
3247 }
3248 $result = $this->call_trigger($triggerName, $userused);
3249 if ($result < 0) {
3250 $error++;
3251 }
3252 // End call trigger
3253 }
3254 }
3255 if ($error) {
3256 $this->db->rollback();
3257 return -1;
3258 } else {
3259 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
3260 $this->db->commit();
3261 return 1;
3262 }
3263 }
3264
3265
3266 // TODO: Move line related operations to CommonObjectLine?
3267
3268 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3278 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3279 {
3280 // phpcs:enable
3281 if (!$this->table_element_line) {
3282 dol_syslog(get_class($this)."::line_order was called on object with property table_element_line not defined", LOG_ERR);
3283 return -1;
3284 }
3285 if (!$this->fk_element) {
3286 dol_syslog(get_class($this)."::line_order was called on object with property fk_element not defined", LOG_ERR);
3287 return -1;
3288 }
3289
3290 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3291 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3292 $fieldposition = 'position';
3293 }
3294
3295 // Count number of lines to reorder (according to choice $renum)
3296 $nl = 0;
3297 $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3298 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3299 if (!$renum) {
3300 $sql .= " AND " . $fieldposition . " = 0";
3301 }
3302 if ($renum) {
3303 $sql .= " AND " . $fieldposition . " <> 0";
3304 }
3305
3306 dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3307 $resql = $this->db->query($sql);
3308 if ($resql) {
3309 $row = $this->db->fetch_row($resql);
3310 $nl = $row[0];
3311 } else {
3312 dol_print_error($this->db);
3313 }
3314 if ($nl > 0) {
3315 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3316 $rows = array();
3317
3318 // We first search all lines that are parent lines (for multilevel details lines)
3319 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3320 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3321 if ($fk_parent_line) {
3322 $sql .= ' AND fk_parent_line IS NULL';
3323 }
3324 $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3325
3326 dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3327 $resql = $this->db->query($sql);
3328 if ($resql) {
3329 $i = 0;
3330 $num = $this->db->num_rows($resql);
3331 while ($i < $num) {
3332 $row = $this->db->fetch_row($resql);
3333 $rows[] = $row[0]; // Add parent line into array rows
3334 $children = $this->getChildrenOfLine($row[0]);
3335 if (!empty($children)) {
3336 foreach ($children as $child) {
3337 array_push($rows, $child);
3338 }
3339 }
3340 $i++;
3341 }
3342
3343 // Now we set a new number for each lines (parent and children with children included into parent tree)
3344 if (!empty($rows)) {
3345 foreach ($rows as $key => $row) {
3346 $this->updateRangOfLine($row, ($key + 1));
3347 }
3348 }
3349 } else {
3350 dol_print_error($this->db);
3351 }
3352 }
3353 return 1;
3354 }
3355
3363 public function getChildrenOfLine($id, $includealltree = 0)
3364 {
3365 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3366 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3367 $fieldposition = 'position';
3368 }
3369
3370 $rows = array();
3371
3372 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3373 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3374 $sql .= ' AND fk_parent_line = '.((int) $id);
3375 $sql .= " ORDER BY " . $fieldposition . " ASC";
3376
3377 dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3378 $resql = $this->db->query($sql);
3379 if ($resql) {
3380 if ($this->db->num_rows($resql) > 0) {
3381 while ($row = $this->db->fetch_row($resql)) {
3382 $rows[] = $row[0];
3383 if (!empty($includealltree)) {
3384 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree));
3385 }
3386 }
3387 }
3388 }
3389 return $rows;
3390 }
3391
3392 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3400 public function line_up($rowid, $fk_parent_line = true)
3401 {
3402 // phpcs:enable
3403 $this->line_order(false, 'ASC', $fk_parent_line);
3404
3405 // Get rang of line
3406 $rang = $this->getRangOfLine($rowid);
3407
3408 // Update position of line
3409 $this->updateLineUp($rowid, $rang);
3410 }
3411
3412 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3420 public function line_down($rowid, $fk_parent_line = true)
3421 {
3422 // phpcs:enable
3423 $this->line_order(false, 'ASC', $fk_parent_line);
3424
3425 // Get rang of line
3426 $rang = $this->getRangOfLine($rowid);
3427
3428 // Get max value for rang
3429 $max = $this->line_max();
3430
3431 // Update position of line
3432 $this->updateLineDown($rowid, $rang, $max);
3433 }
3434
3442 public function updateRangOfLine($rowid, $rang)
3443 {
3444 global $hookmanager;
3445 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3446 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3447 $fieldposition = 'position';
3448 }
3449
3450 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3451 $sql .= ' WHERE rowid = '.((int) $rowid);
3452
3453 dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3454 if (!$this->db->query($sql)) {
3455 dol_print_error($this->db);
3456 return -1;
3457 } else {
3458 $parameters = array('rowid' => $rowid, 'rang' => $rang, 'fieldposition' => $fieldposition);
3459 $action = '';
3460 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3461 return 1;
3462 }
3463 }
3464
3465 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3472 public function line_ajaxorder($rows)
3473 {
3474 // phpcs:enable
3475 $num = count($rows);
3476 for ($i = 0; $i < $num; $i++) {
3477 $this->updateRangOfLine($rows[$i], ($i + 1));
3478 }
3479 }
3480
3488 public function updateLineUp($rowid, $rang)
3489 {
3490 if ($rang > 1) {
3491 $fieldposition = 'rang';
3492 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3493 $fieldposition = 'position';
3494 }
3495
3496 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3497 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3498 $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3499 if ($this->db->query($sql)) {
3500 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3501 $sql .= ' WHERE rowid = '.((int) $rowid);
3502 if (!$this->db->query($sql)) {
3503 dol_print_error($this->db);
3504 }
3505 } else {
3506 dol_print_error($this->db);
3507 }
3508 }
3509 }
3510
3519 public function updateLineDown($rowid, $rang, $max)
3520 {
3521 if ($rang < $max) {
3522 $fieldposition = 'rang';
3523 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3524 $fieldposition = 'position';
3525 }
3526
3527 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3528 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3529 $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3530 if ($this->db->query($sql)) {
3531 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3532 $sql .= ' WHERE rowid = '.((int) $rowid);
3533 if (!$this->db->query($sql)) {
3534 dol_print_error($this->db);
3535 }
3536 } else {
3537 dol_print_error($this->db);
3538 }
3539 }
3540 }
3541
3548 public function getRangOfLine($rowid)
3549 {
3550 $fieldposition = 'rang';
3551 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3552 $fieldposition = 'position';
3553 }
3554
3555 $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3556 $sql .= " WHERE rowid = ".((int) $rowid);
3557
3558 dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3559 $resql = $this->db->query($sql);
3560 if ($resql) {
3561 $row = $this->db->fetch_row($resql);
3562 return $row[0];
3563 }
3564
3565 return 0;
3566 }
3567
3574 public function getIdOfLine($rang)
3575 {
3576 $fieldposition = 'rang';
3577 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3578 $fieldposition = 'position';
3579 }
3580
3581 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3582 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3583 $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3584 $resql = $this->db->query($sql);
3585 if ($resql) {
3586 $row = $this->db->fetch_row($resql);
3587 return $row[0];
3588 }
3589
3590 return 0;
3591 }
3592
3593 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3600 public function line_max($fk_parent_line = 0)
3601 {
3602 // phpcs:enable
3603 $positionfield = 'rang';
3604 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3605 $positionfield = 'position';
3606 }
3607
3608 // Search the last rang with fk_parent_line
3609 if ($fk_parent_line) {
3610 $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3611 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3612 $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3613
3614 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3615 $resql = $this->db->query($sql);
3616 if ($resql) {
3617 $row = $this->db->fetch_row($resql);
3618 if (!empty($row[0])) {
3619 return $row[0];
3620 } else {
3621 return $this->getRangOfLine($fk_parent_line);
3622 }
3623 }
3624 } else {
3625 // If not, search the last rang of element
3626 $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3627 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3628
3629 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3630 $resql = $this->db->query($sql);
3631 if ($resql) {
3632 $row = $this->db->fetch_row($resql);
3633 return $row[0];
3634 }
3635 }
3636
3637 return 0;
3638 }
3639
3640 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3647 public function update_ref_ext($ref_ext)
3648 {
3649 // phpcs:enable
3650 if (!$this->table_element) {
3651 dol_syslog(get_class($this)."::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3652 return -1;
3653 }
3654
3655 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3656 $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3657 $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3658
3659 dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3660 if ($this->db->query($sql)) {
3661 $this->ref_ext = $ref_ext;
3662 return 1;
3663 } else {
3664 $this->error = $this->db->error();
3665 return -1;
3666 }
3667 }
3668
3669 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3678 public function update_note($note, $suffix = '', $notrigger = 0)
3679 {
3680 // phpcs:enable
3681 global $user;
3682
3683 if (!$this->table_element) {
3684 $this->error = 'update_note was called on object with property table_element not defined';
3685 dol_syslog(get_class($this)."::update_note was called on object with property table_element not defined", LOG_ERR);
3686 return -1;
3687 }
3688 if (!in_array($suffix, array('', '_public', '_private'))) {
3689 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3690 dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3691 return -2;
3692 }
3693
3694 $newsuffix = $suffix;
3695
3696 // Special case
3697 if ($this->table_element == 'product' && $newsuffix == '_private') {
3698 $newsuffix = '';
3699 }
3700 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3701 $fieldusermod = "fk_user_mod";
3702 } elseif ($this->table_element == 'ecm_files') {
3703 $fieldusermod = "fk_user_m";
3704 } else {
3705 $fieldusermod = "fk_user_modif";
3706 }
3707 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3708 $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3709 $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3710 $sql .= " WHERE rowid = ".((int) $this->id);
3711
3712 dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3713 if ($this->db->query($sql)) {
3714 if ($suffix == '_public') {
3715 $this->note_public = $note;
3716 } elseif ($suffix == '_private') {
3717 $this->note_private = $note;
3718 } else {
3719 $this->note = $note; // deprecated
3720 $this->note_private = $note;
3721 }
3722 if (empty($notrigger)) {
3723 switch ($this->element) {
3724 case 'societe':
3725 $trigger_name = 'COMPANY_MODIFY';
3726 break;
3727 case 'commande':
3728 $trigger_name = 'ORDER_MODIFY';
3729 break;
3730 case 'facture':
3731 $trigger_name = 'BILL_MODIFY';
3732 break;
3733 case 'invoice_supplier':
3734 $trigger_name = 'BILL_SUPPLIER_MODIFY';
3735 break;
3736 case 'facturerec':
3737 $trigger_name = 'BILLREC_MODIFIY';
3738 break;
3739 case 'expensereport':
3740 $trigger_name = 'EXPENSE_REPORT_MODIFY';
3741 break;
3742 default:
3743 $trigger_name = strtoupper($this->element) . '_MODIFY';
3744 }
3745 $ret = $this->call_trigger($trigger_name, $user);
3746 if ($ret < 0) {
3747 return -1;
3748 }
3749 }
3750 return 1;
3751 } else {
3752 $this->error = $this->db->lasterror();
3753 return -1;
3754 }
3755 }
3756
3757 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3766 public function update_note_public($note)
3767 {
3768 // phpcs:enable
3769 return $this->update_note($note, '_public');
3770 }
3771
3772 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3783 public function update_price($exclspec = 0, $roundingadjust = 'auto', $nodatabaseupdate = 0, $seller = null)
3784 {
3785 // phpcs:enable
3786 global $conf, $hookmanager, $action;
3787
3788 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3789 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3790 if ($reshook > 0) {
3791 return 1; // replacement code
3792 } elseif ($reshook < 0) {
3793 return -1; // failure
3794 } // reshook = 0 => execute normal code
3795
3796 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3797 $isElementForSupplier = false;
3798 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND'; // const for customer by default
3799 $MODULE = "";
3800 if ($this->element == 'propal') {
3801 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3802 } elseif ($this->element == 'commande' || $this->element == 'order') {
3803 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3804 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3805 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3806 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3807 $isElementForSupplier = true;
3808 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3809 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3810 $isElementForSupplier = true;
3811 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3812 } elseif ($this->element == 'supplier_proposal') {
3813 $isElementForSupplier = true;
3814 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3815 }
3816 if ($isElementForSupplier) {
3817 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER'; // const for supplier
3818 }
3819
3820 if (!empty($MODULE)) {
3821 if (getDolGlobalString($MODULE)) {
3822 $modsactivated = explode(',', getDolGlobalString($MODULE));
3823 foreach ($modsactivated as $mod) {
3824 if (isModEnabled($mod)) {
3825 return 1; // update was disabled by specific setup
3826 }
3827 }
3828 }
3829 }
3830
3831 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3832
3833 $forcedroundingmode = $roundingadjust;
3834 if ($forcedroundingmode == 'auto' && isset($conf->global->{$roundTotalConstName})) {
3835 $forcedroundingmode = getDolGlobalString($roundTotalConstName);
3836 } elseif ($forcedroundingmode == 'auto') {
3837 $forcedroundingmode = '0';
3838 }
3839
3840 $error = 0;
3841
3842 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3843
3844 // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3845 $fieldtva = 'total_tva';
3846 $fieldlocaltax1 = 'total_localtax1';
3847 $fieldlocaltax2 = 'total_localtax2';
3848 $fieldup = 'subprice';
3849 $base_price_type = 'HT';
3850 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3851 $fieldtva = 'tva';
3852 $fieldup = 'pu_ht';
3853 }
3854 if ($this->element == 'invoice_supplier_rec') {
3855 $fieldup = 'pu_ht';
3856 }
3857 if ($this->element == 'expensereport') {
3858 $fieldup = 'value_unit';
3859 $base_price_type = 'TTC';
3860 }
3861
3862 $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,";
3863 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3864 if ($this->table_element_line == 'facturedet') {
3865 $sql .= ', situation_percent';
3866 }
3867 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3868 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3869 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3870 if ($exclspec) {
3871 $product_field = 'product_type';
3872 if ($this->table_element_line == 'contratdet') {
3873 $product_field = ''; // contratdet table has no product_type field
3874 }
3875 if ($product_field) {
3876 $sql .= " AND ".$product_field." <> 9";
3877 }
3878 }
3879 $sql .= ' ORDER by rowid'; // We want to be certain to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
3880
3881 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3882
3883 $resql = $this->db->query($sql);
3884 if ($resql) {
3885 $this->total_ht = 0;
3886 $this->total_tva = 0;
3887 $this->total_localtax1 = 0;
3888 $this->total_localtax2 = 0;
3889 $this->total_ttc = 0;
3890 $total_ht_by_vats = array();
3891 $total_tva_by_vats = array();
3892 $total_ttc_by_vats = array();
3893 $this->multicurrency_total_ht = 0;
3894 $this->multicurrency_total_tva = 0;
3895 $this->multicurrency_total_ttc = 0;
3896
3897 $this->db->begin();
3898
3899 $num = $this->db->num_rows($resql);
3900 $i = 0;
3901 while ($i < $num) {
3902 $obj = $this->db->fetch_object($resql);
3903
3904 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
3905 $parameters = array('fk_element' => $obj->rowid);
3906 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3907
3908 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'
3909 // This part of code is to fix data. We should not call it too often.
3910 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3911 $tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, $base_price_type, $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
3912
3913 $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.
3914 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3915 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3916 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3917
3918 if ($diff_on_current_total) {
3919 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3920 $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);
3921 dol_syslog('We found inconsistent 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);
3922 $resqlfix = $this->db->query($sqlfix);
3923 if (!$resqlfix) {
3924 dol_print_error($this->db, 'Failed to update line');
3925 }
3926 $obj->total_tva = $tmpcal[1];
3927 $obj->total_ttc = $tmpcal[2];
3928 } elseif ($diff_when_using_price_ht) {
3929 // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3930 // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3931 $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);
3932 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);
3933 $resqlfix = $this->db->query($sqlfix);
3934 if (!$resqlfix) {
3935 dol_print_error($this->db, 'Failed to update line');
3936 }
3937 $obj->total_tva = $tmpcal[1];
3938 $obj->total_ttc = $tmpcal[2];
3939 }
3940 }
3941
3942 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3943 $this->total_tva += $obj->total_tva;
3944 $this->total_localtax1 += $obj->total_localtax1;
3945 $this->total_localtax2 += $obj->total_localtax2;
3946 $this->total_ttc += $obj->total_ttc;
3947 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3948 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3949 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3950
3951 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3952 $total_ht_by_vats[$obj->vatrate] = 0;
3953 }
3954 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3955 $total_tva_by_vats[$obj->vatrate] = 0;
3956 }
3957 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3958 $total_ttc_by_vats[$obj->vatrate] = 0;
3959 }
3960 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3961 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3962 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3963
3964 if ($forcedroundingmode == '1') { // Check if we need adjustment onto line for vat. TODO This works on the company currency but not on foreign currency
3965 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3966 $diff = price2num($total_tva_by_vats[$obj->vatrate] - (float) $tmpvat, 'MT', 1);
3967 //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";
3968 if ($diff) {
3969 $maxdiff = (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)));
3970 if (abs((float) $diff) > $maxdiff) {
3971 // If error is more than 10 times the accuracy of rounding. This should not happen.
3972 $errmsg = 'We found a rounding difference after line '.($obj->rowid).' between HT*VAT='.$tmpvat.' and total in database='.$total_tva_by_vats[$obj->vatrate].' (calculated with UP*qty) but diff='.$diff.' is too high (> '.$maxdiff.') to be corrected. Some data in your lines may be corrupted. Try to edit each line manually to fix this before restarting.';
3973 dol_syslog($errmsg, LOG_WARNING);
3974 $this->error = $errmsg;
3975 $error++;
3976 break;
3977 }
3978 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - (float) $diff).", total_ttc = ".price2num($obj->total_ttc - (float) $diff)." WHERE rowid = ".((int) $obj->rowid);
3979 dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.' between TotalHT('.$total_ht_by_vats[$obj->vatrate].')*VATrate('.$obj->vatrate.')='.$tmpvat.' and total in database='.$total_tva_by_vats[$obj->vatrate]." (calculated with UP*qty). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3980
3981 $resqlfix = $this->db->query($sqlfix);
3982
3983 if (!$resqlfix) {
3984 dol_print_error($this->db, 'Failed to update line');
3985 }
3986
3987 $this->total_tva = (float) price2num($this->total_tva - (float) $diff, '', 1);
3988 $this->total_ttc = (float) price2num($this->total_ttc - (float) $diff, '', 1);
3989 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - (float) $diff, '', 1);
3990 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - (float) $diff, '', 1);
3991 }
3992 }
3993
3994 $i++;
3995 }
3996
3997 // Add revenue stamp to total
3998 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
3999 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4000
4001 // Situations totals
4002 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) {
4003 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
4004 if ($this->type != Facture::TYPE_CREDIT_NOTE) { // @phpstan-ignore-line
4005 if (getDolGlobalInt('INVOICE_USE_SITUATION') != 2) {
4006 $prev_sits = $this->get_prev_sits();
4007
4008 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
4009 $this->total_ht -= $sit->total_ht;
4010 $this->total_tva -= $sit->total_tva;
4011 $this->total_localtax1 -= $sit->total_localtax1;
4012 $this->total_localtax2 -= $sit->total_localtax2;
4013 $this->total_ttc -= $sit->total_ttc;
4014 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4015 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4016 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4017 }
4018 }
4019 }
4020 }
4021
4022 // Clean total
4023 $this->total_ht = (float) price2num($this->total_ht);
4024 $this->total_tva = (float) price2num($this->total_tva);
4025 $this->total_localtax1 = (float) price2num($this->total_localtax1);
4026 $this->total_localtax2 = (float) price2num($this->total_localtax2);
4027 $this->total_ttc = (float) price2num($this->total_ttc);
4028
4029 $this->db->free($resql);
4030
4031 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
4032 $fieldht = 'total_ht';
4033 $fieldtva = 'tva';
4034 $fieldlocaltax1 = 'localtax1';
4035 $fieldlocaltax2 = 'localtax2';
4036 $fieldttc = 'total_ttc';
4037 // Specific code for backward compatibility with old field names
4038 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
4039 $fieldtva = 'total_tva';
4040 }
4041
4042 if (!$error && empty($nodatabaseupdate)) {
4043 $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
4044 $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
4045 $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
4046 $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
4047 $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
4048 $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
4049 $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
4050 $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
4051 $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
4052 $sql .= " WHERE rowid = ".((int) $this->id);
4053
4054 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4055 $resql = $this->db->query($sql);
4056
4057 if (!$resql) {
4058 $error++;
4059 $this->error = $this->db->lasterror();
4060 $this->errors[] = $this->db->lasterror();
4061 }
4062 }
4063
4064 if (!$error) {
4065 $this->db->commit();
4066 return 1;
4067 } else {
4068 $this->db->rollback();
4069 return -1;
4070 }
4071 } else {
4072 dol_print_error($this->db, 'Bad request in update_price');
4073 return -1;
4074 }
4075 }
4076
4077 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4088 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
4089 {
4090 // phpcs:enable
4091 global $user, $hookmanager, $action;
4092 $origin = (!empty($origin) ? $origin : $this->origin);
4093 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4094 $f_user = isset($f_user) ? $f_user : $user;
4095
4096 // Special case
4097 if ($origin == 'order') {
4098 $origin = 'commande';
4099 }
4100 if ($origin == 'invoice') {
4101 $origin = 'facture';
4102 }
4103 if ($origin == 'invoice_template') {
4104 $origin = 'facturerec';
4105 }
4106 if ($origin == 'supplierorder') {
4107 $origin = 'order_supplier';
4108 }
4109
4110 // Add module part to target type
4111 $targettype = $this->getElementType();
4112
4113 $parameters = array('targettype' => $targettype);
4114 // Hook for explicitly set the targettype if it must be different than $this->element
4115 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4116 if ($reshook > 0) {
4117 if (!empty($hookmanager->resArray['targettype'])) {
4118 $targettype = $hookmanager->resArray['targettype'];
4119 }
4120 }
4121
4122 $this->db->begin();
4123 $error = 0;
4124
4125 $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
4126 $sql .= "fk_source";
4127 $sql .= ", sourcetype";
4128 $sql .= ", fk_target";
4129 $sql .= ", targettype";
4130 $sql .= ") VALUES (";
4131 $sql .= ((int) $origin_id);
4132 $sql .= ", '" . $this->db->escape($origin) . "'";
4133 $sql .= ", " . ((int) $this->id);
4134 $sql .= ", '" . $this->db->escape($targettype) . "'";
4135 $sql .= ")";
4136
4137 dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
4138 if ($this->db->query($sql)) {
4139 if (!$notrigger) {
4140 // Call trigger
4141 $this->context['link_origin'] = $origin;
4142 $this->context['link_origin_id'] = $origin_id;
4143 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
4144 if ($result < 0) {
4145 $error++;
4146 }
4147 // End call triggers
4148 }
4149 } else {
4150 $this->error = $this->db->lasterror();
4151 $error++;
4152 }
4153
4154 if (!$error) {
4155 $this->db->commit();
4156 return 1;
4157 } else {
4158 $this->db->rollback();
4159 return 0;
4160 }
4161 }
4162
4168 public function getElementType()
4169 {
4170 // Elements of the core modules having a `$module` property but for which we may not want to prefix the element name with the module name for finding the linked object in llx_element_element.
4171 // It's because existing llx_element_element entries inserted prior to this modification (version <=14.2) may already use the element name alone in fk_source or fk_target (without the module name prefix).
4172 $coreModule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
4173 // Add module part to target type if object has $module property and isn't in core modules.
4174 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.'_' : '').$this->element;
4175 }
4176
4177
4200 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
4201 {
4202 global $conf, $hookmanager, $action;
4203
4204 // Important for pdf generation time reduction
4205 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
4206 // If you need to force the reload, you can call clearObjectLinkedCache() before calling fetchObjectLinked()
4207 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4208 return 1;
4209 }
4210
4211 $this->linkedObjectsIds = array();
4212 $this->linkedObjects = array();
4213
4214 $justsource = false;
4215 $justtarget = false;
4216 $withtargettype = false;
4217 $withsourcetype = false;
4218
4219 $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
4220 // Hook for explicitly set the targettype if it must be differtent than $this->element
4221 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4222 if ($reshook > 0) {
4223 if (!empty($hookmanager->resArray['sourcetype'])) {
4224 $sourcetype = $hookmanager->resArray['sourcetype'];
4225 }
4226 if (!empty($hookmanager->resArray['sourceid'])) {
4227 $sourceid = $hookmanager->resArray['sourceid'];
4228 }
4229 if (!empty($hookmanager->resArray['targettype'])) {
4230 $targettype = $hookmanager->resArray['targettype'];
4231 }
4232 if (!empty($hookmanager->resArray['targetid'])) {
4233 $targetid = $hookmanager->resArray['targetid'];
4234 }
4235 }
4236
4237 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4238 $justsource = true; // the source (id and type) is a search criteria
4239 if (!empty($targettype)) {
4240 $withtargettype = true;
4241 }
4242 }
4243 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4244 $justtarget = true; // the target (id and type) is a search criteria
4245 if (!empty($sourcetype)) {
4246 $withsourcetype = true;
4247 }
4248 }
4249
4250 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4251 $targetid = (!empty($targetid) ? $targetid : $this->id);
4252 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4253 $targettype = (!empty($targettype) ? $targettype : $this->element);
4254
4255 /*if (empty($sourceid) && empty($targetid))
4256 {
4257 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
4258 return -1;
4259 }*/
4260
4261 // Links between objects are stored in table element_element
4262 $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4263 $sql .= " FROM ".$this->db->prefix()."element_element";
4264 $sql .= " WHERE ";
4265 if ($justsource || $justtarget) {
4266 if ($justsource) {
4267 $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
4268 if ($withtargettype) {
4269 $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
4270 }
4271 } elseif ($justtarget) {
4272 $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
4273 if ($withsourcetype) {
4274 $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
4275 }
4276 }
4277 } else {
4278 $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
4279 $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
4280 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
4281 $this->linkedObjectsFullLoaded[$this->id] = true;
4282 }
4283 }
4284 $sql .= " ORDER BY ".$orderby;
4285
4286 dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
4287 $resql = $this->db->query($sql);
4288 if ($resql) {
4289 $num = $this->db->num_rows($resql);
4290 $i = 0;
4291 while ($i < $num) {
4292 $obj = $this->db->fetch_object($resql);
4293 if ($justsource || $justtarget) {
4294 if ($justsource) {
4295 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4296 } elseif ($justtarget) {
4297 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4298 }
4299 } else {
4300 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4301 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4302 }
4303 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4304 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4305 }
4306 }
4307 $i++;
4308 }
4309
4310 if (!empty($this->linkedObjectsIds)) {
4311 $tmparray = $this->linkedObjectsIds;
4312 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4313 $element_properties = getElementProperties($objecttype);
4314 $element = $element_properties['element'];
4315 $classPath = $element_properties['classpath'];
4316 $classFile = $element_properties['classfile'];
4317 $className = $element_properties['classname'];
4318 $module = $element_properties['module'];
4319
4320 // Here $module, $classFile and $className are set, we can use them.
4321 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4322 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4323 dol_include_once('/'.$classPath.'/'.$classFile.'.class.php');
4324 if (class_exists($className)) {
4325 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4326 $object = new $className($this->db);
4327 $ret = $object->fetch($objectid);
4328 if ($ret >= 0) {
4329 $this->linkedObjects[$objecttype][$i] = $object;
4330 }
4331 }
4332 }
4333 }
4334 } else {
4335 unset($this->linkedObjectsIds[$objecttype]);
4336 }
4337 }
4338 }
4339 return 1;
4340 } else {
4341 dol_print_error($this->db);
4342 return -1;
4343 }
4344 }
4345
4352 public function clearObjectLinkedCache()
4353 {
4354 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4355 unset($this->linkedObjectsFullLoaded[$this->id]);
4356 }
4357
4358 return 1;
4359 }
4360
4373 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4374 {
4375 global $user;
4376 $updatesource = false;
4377 $updatetarget = false;
4378 $f_user = isset($f_user) ? $f_user : $user;
4379
4380 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4381 $updatesource = true;
4382 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4383 $updatetarget = true;
4384 }
4385
4386 $this->db->begin();
4387 $error = 0;
4388
4389 $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4390 if ($updatesource) {
4391 $sql .= "fk_source = " . ((int) $sourceid);
4392 $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4393 $sql .= " WHERE fk_target = " . ((int) $this->id);
4394 $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4395 } elseif ($updatetarget) {
4396 $sql .= "fk_target = " . ((int) $targetid);
4397 $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4398 $sql .= " WHERE fk_source = " . ((int) $this->id);
4399 $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4400 }
4401
4402 dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4403 if ($this->db->query($sql)) {
4404 if (!$notrigger) {
4405 // Call trigger
4406 $this->context['link_source_id'] = $sourceid;
4407 $this->context['link_source_type'] = $sourcetype;
4408 $this->context['link_target_id'] = $targetid;
4409 $this->context['link_target_type'] = $targettype;
4410 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4411 if ($result < 0) {
4412 $error++;
4413 }
4414 // End call triggers
4415 }
4416 } else {
4417 $this->error = $this->db->lasterror();
4418 $error++;
4419 }
4420
4421 if (!$error) {
4422 $this->db->commit();
4423 return 1;
4424 } else {
4425 $this->db->rollback();
4426 return -1;
4427 }
4428 }
4429
4443 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0)
4444 {
4445 global $user;
4446 $deletesource = false;
4447 $deletetarget = false;
4448 $f_user = isset($f_user) ? $f_user : $user;
4449
4450 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4451 $deletesource = true;
4452 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4453 $deletetarget = true;
4454 }
4455
4456 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4457 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4458 $targetid = (!empty($targetid) ? $targetid : $this->id);
4459 $targettype = (!empty($targettype) ? $targettype : $this->element);
4460 $this->db->begin();
4461 $error = 0;
4462
4463 if (!$notrigger) {
4464 // Call trigger
4465 $this->context['link_id'] = $rowid;
4466 $this->context['link_source_id'] = $sourceid;
4467 $this->context['link_source_type'] = $sourcetype;
4468 $this->context['link_target_id'] = $targetid;
4469 $this->context['link_target_type'] = $targettype;
4470 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4471 if ($result < 0) {
4472 $error++;
4473 }
4474 // End call triggers
4475 }
4476
4477 if (!$error) {
4478 $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4479 $sql .= " WHERE";
4480 if ($rowid > 0) {
4481 $sql .= " rowid = " . ((int) $rowid);
4482 } else {
4483 if ($deletesource) {
4484 $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4485 $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4486 } elseif ($deletetarget) {
4487 $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4488 $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4489 } else {
4490 $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4491 $sql .= " OR";
4492 $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4493 }
4494 }
4495
4496 dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4497 if (!$this->db->query($sql)) {
4498 $this->error = $this->db->lasterror();
4499 $this->errors[] = $this->error;
4500 $error++;
4501 }
4502 }
4503
4504 if (!$error) {
4505 $this->db->commit();
4506 return 1;
4507 } else {
4508 $this->db->rollback();
4509 return 0;
4510 }
4511 }
4512
4522 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4523 {
4524 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4525 return -1;
4526 }
4527 if (!preg_match('/^[_a-zA-Z0-9]+$/', $field_select)) {
4528 dol_syslog('Invalid value $field_select for parameter '.$field_select.' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4529 }
4530
4531 global $db;
4532
4533 $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4534 $resql = $db->query($sql);
4535
4536 $TRes = array();
4537 if (!empty($resql)) {
4538 while ($res = $db->fetch_object($resql)) {
4539 $TRes[] = $res->{$field_select};
4540 }
4541 }
4542
4543 return $TRes;
4544 }
4545
4554 public static function getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4555 {
4556 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4557 return -1;
4558 }
4559
4560 global $db;
4561
4562 $sql = "SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4563 $resql = $db->query($sql);
4564 $n = 0;
4565 if ($resql) {
4566 $res = $db->fetch_object($resql);
4567 if ($res) {
4568 $n = $res->nb;
4569 }
4570 }
4571
4572 return $n;
4573 }
4574
4583 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4584 {
4585 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4586 return -1;
4587 }
4588
4589 global $db;
4590
4591 $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4592 $resql = $db->query($sql);
4593
4594 if (empty($resql)) {
4595 return 0;
4596 }
4597
4598 return 1;
4599 }
4600
4611 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4612 {
4613 global $user;
4614
4615 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4616
4617 $elementId = (!empty($elementId) ? $elementId : $this->id);
4618 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4619
4620 $this->db->begin();
4621
4622 if ($elementTable == 'facture_rec') {
4623 $fieldstatus = "suspended";
4624 }
4625 if ($elementTable == 'mailing') {
4626 $fieldstatus = "statut";
4627 }
4628 if ($elementTable == 'cronjob') {
4629 $fieldstatus = "status";
4630 }
4631 if ($elementTable == 'user') {
4632 $fieldstatus = "statut";
4633 }
4634 if ($elementTable == 'expensereport') {
4635 $fieldstatus = "fk_statut";
4636 }
4637 if ($elementTable == 'receptiondet_batch') {
4638 $fieldstatus = "status";
4639 }
4640 if ($elementTable == 'prelevement_bons') {
4641 $fieldstatus = "statut";
4642 }
4643 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4644 $fieldstatus = 'status';
4645 }
4646
4647 $sql = "UPDATE ".$this->db->prefix().$elementTable;
4648 $sql .= " SET ".$fieldstatus." = ".((int) $status);
4649 // If status = 1 = validated, update also fk_user_valid
4650 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4651 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4652 $sql .= ", fk_user_valid = ".((int) $user->id);
4653 }
4654 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4655 $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4656 }
4657 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4658 $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4659 }
4660 $sql .= " WHERE rowid = ".((int) $elementId);
4661 $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4662
4663 dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4664 $resql = $this->db->query($sql);
4665 if ($resql) {
4666 $error = 0;
4667
4668 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4669
4670 if ($nb_rows_affected > 0) {
4671 if (empty($trigkey)) {
4672 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4673 if ($this->element == 'supplier_proposal' && $status == 2) {
4674 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4675 }
4676 if ($this->element == 'supplier_proposal' && $status == 3) {
4677 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4678 }
4679 if ($this->element == 'supplier_proposal' && $status == 4) {
4680 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4681 }
4682 if ($this->element == 'fichinter' && $status == 3) {
4683 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4684 }
4685 if ($this->element == 'fichinter' && $status == 2) {
4686 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4687 }
4688 if ($this->element == 'fichinter' && $status == 1) {
4689 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4690 }
4691 }
4692
4693 if ($trigkey) {
4694 // Call trigger
4695 $result = $this->call_trigger($trigkey, $user);
4696 if ($result < 0) {
4697 $error++;
4698 }
4699 // End call triggers
4700 }
4701 } else {
4702 // The status was probably already good. We do nothing more, no triggers.
4703 }
4704
4705 if (!$error) {
4706 $this->db->commit();
4707
4708 if (empty($savElementId)) {
4709 // If the element we update is $this (so $elementId was provided as null)
4710 if ($fieldstatus == 'tosell') {
4711 $this->status = $status;
4712 } elseif ($fieldstatus == 'tobuy') {
4713 $this->status_buy = $status; // @phpstan-ignore-line
4714 } else {
4715 $this->status = $status;
4716 }
4717 }
4718
4719 return 1;
4720 } else {
4721 $this->db->rollback();
4722 dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4723 return -1;
4724 }
4725 } else {
4726 $this->error = $this->db->lasterror();
4727 $this->db->rollback();
4728 return -1;
4729 }
4730 }
4731
4732
4740 public function getCanvas($id = 0, $ref = '')
4741 {
4742 global $conf;
4743
4744 if (empty($id) && empty($ref)) {
4745 return 0;
4746 }
4747 if (getDolGlobalString('MAIN_DISABLE_CANVAS')) {
4748 return 0; // To increase speed. Not enabled by default.
4749 }
4750
4751 // Clean parameters
4752 $ref = trim($ref);
4753
4754 $sql = "SELECT rowid, canvas";
4755 $sql .= " FROM ".$this->db->prefix().$this->table_element;
4756 $sql .= " WHERE entity IN (".getEntity($this->element).")";
4757 if (!empty($id)) {
4758 $sql .= " AND rowid = ".((int) $id);
4759 }
4760 if (!empty($ref)) {
4761 $sql .= " AND ref = '".$this->db->escape($ref)."'";
4762 }
4763
4764 $resql = $this->db->query($sql);
4765 if ($resql) {
4766 $obj = $this->db->fetch_object($resql);
4767 if ($obj) {
4768 $this->canvas = $obj->canvas;
4769 return 1;
4770 } else {
4771 return 0;
4772 }
4773 } else {
4774 dol_print_error($this->db);
4775 return -1;
4776 }
4777 }
4778
4779
4786 public function getSpecialCode($lineid)
4787 {
4788 $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4789 $sql .= " WHERE rowid = ".((int) $lineid);
4790 $resql = $this->db->query($sql);
4791 if ($resql) {
4792 $row = $this->db->fetch_row($resql);
4793 return (!empty($row[0]) ? $row[0] : 0);
4794 }
4795
4796 return 0;
4797 }
4798
4807 public function isObjectUsed($id = 0, $entity = 0)
4808 {
4809 global $langs;
4810
4811 if (empty($id)) {
4812 $id = $this->id;
4813 }
4814
4815 // Check parameters
4816 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4817 dol_print_error(null, 'Called isObjectUsed on a class with property this->childtables not defined');
4818 return -1;
4819 }
4820
4821 $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
4822 // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
4823 $tmparray = array_keys($this->childtables);
4824 if (is_numeric($tmparray[0])) {
4825 $arraytoscan = array_flip($this->childtables);
4826 }
4827
4828 // Test if child exists
4829 $haschild = 0;
4830 foreach ($arraytoscan as $table => $element) {
4831 //print $id.'-'.$table.'-'.$elementname.'<br>';
4832 // Check if element can be deleted
4833 $sql = "SELECT COUNT(*) as nb";
4834 $sql .= " FROM ".$this->db->prefix().$table." as c";
4835 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4836 $sql .= ", ".$this->db->prefix().$element['parent']." as p";
4837 }
4838 if (!empty($element['fk_element'])) {
4839 $sql .= " WHERE c.".$element['fk_element']." = ".((int) $id);
4840 } else {
4841 $sql .= " WHERE c.".$this->fk_element." = ".((int) $id);
4842 }
4843 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4844 $sql .= " AND c.".$element['parentkey']." = p.rowid";
4845 }
4846 if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
4847 $sql .= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'";
4848 }
4849 if (!empty($entity)) {
4850 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4851 $sql .= " AND p.entity = ".((int) $entity);
4852 } else {
4853 $sql .= " AND c.entity = ".((int) $entity);
4854 }
4855 }
4856
4857 $resql = $this->db->query($sql);
4858 if ($resql) {
4859 $obj = $this->db->fetch_object($resql);
4860 if ($obj->nb > 0) {
4861 $langs->load("errors");
4862 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4863 $haschild += $obj->nb;
4864 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4865 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4866 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4867 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4868 } else { // new usage: $element['name']=Translation key
4869 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4870 }
4871 break; // We found at least one, we stop here
4872 }
4873 } else {
4874 $this->errors[] = $this->db->lasterror();
4875 return -1;
4876 }
4877 }
4878 if ($haschild > 0) {
4879 $this->errors[] = "ErrorRecordHasChildren";
4880 return $haschild;
4881 } else {
4882 return 0;
4883 }
4884 }
4885
4892 public function hasProductsOrServices($predefined = -1)
4893 {
4894 $nb = 0;
4895
4896 foreach ($this->lines as $key => $val) {
4897 $qualified = 0;
4898 if ($predefined == -1) {
4899 $qualified = 1;
4900 }
4901 if ($predefined == 1 && $val->fk_product > 0) {
4902 $qualified = 1;
4903 }
4904 if ($predefined == 0 && $val->fk_product <= 0) {
4905 $qualified = 1;
4906 }
4907 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4908 $qualified = 1;
4909 }
4910 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4911 $qualified = 1;
4912 }
4913 if ($qualified) {
4914 $nb++;
4915 }
4916 }
4917 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4918 return $nb;
4919 }
4920
4926 public function getTotalDiscount()
4927 {
4928 if (!empty($this->table_element_line)) {
4929 $total_discount = 0.00;
4930
4931 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4932 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4933 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4934
4935 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4936 $resql = $this->db->query($sql);
4937 if ($resql) {
4938 $num = $this->db->num_rows($resql);
4939 $i = 0;
4940 while ($i < $num) {
4941 $obj = $this->db->fetch_object($resql);
4942
4943 $pu_ht = $obj->pu_ht;
4944 $qty = $obj->qty;
4945 $total_ht = $obj->total_ht;
4946
4947 $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT');
4948 $total_discount += $total_discount_line;
4949
4950 $i++;
4951 }
4952 }
4953
4954 //print $total_discount; exit;
4955 return (float) price2num($total_discount);
4956 }
4957
4958 return null;
4959 }
4960
4961
4968 public function getTotalWeightVolume()
4969 {
4970 $totalWeight = 0;
4971 $totalVolume = 0;
4972 // defined for shipment only
4973 $totalOrdered = 0;
4974 // defined for shipment only
4975 $totalToShip = 0;
4976
4977 if (empty($this->lines)) {
4978 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
4979 }
4980
4981 foreach ($this->lines as $line) {
4982 if (isset($line->qty_asked)) {
4983 $totalOrdered += $line->qty_asked; // defined for shipment only
4984 }
4985 if (isset($line->qty_shipped)) {
4986 $totalToShip += $line->qty_shipped; // defined for shipment only
4987 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
4988 if (empty($totalToShip)) {
4989 $totalToShip = 0;
4990 }
4991 $totalToShip += $line->qty; // defined for reception only
4992 }
4993
4994 // Define qty, weight, volume, weight_units, volume_units
4995 if ($this->element == 'shipping') {
4996 // for shipments
4997 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
4998 } else {
4999 $qty = $line->qty ? $line->qty : 0;
5000 }
5001
5002 $weight = !empty($line->weight) ? $line->weight : 0;
5003 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5004 $volume = !empty($line->volume) ? $line->volume : 0;
5005 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5006
5007 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5008 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5009 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5010 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5011
5012 $weightUnit = 0;
5013 $volumeUnit = 0;
5014 if (!empty($weight_units)) {
5015 $weightUnit = $weight_units;
5016 }
5017 if (!empty($volume_units)) {
5018 $volumeUnit = $volume_units;
5019 }
5020
5021 if (empty($totalWeight)) {
5022 $totalWeight = 0; // Avoid warning because $totalWeight is ''
5023 }
5024 if (empty($totalVolume)) {
5025 $totalVolume = 0; // Avoid warning because $totalVolume is ''
5026 }
5027
5028 //var_dump($line->volume_units);
5029 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5030 $trueWeightUnit = pow(10, $weightUnit);
5031 $totalWeight += $weight * $qty * $trueWeightUnit;
5032 } else {
5033 if ($weight_units == 99) {
5034 // conversion 1 Pound = 0.45359237 KG
5035 $trueWeightUnit = 0.45359237;
5036 $totalWeight += $weight * $qty * $trueWeightUnit;
5037 } elseif ($weight_units == 98) {
5038 // conversion 1 Ounce = 0.0283495 KG
5039 $trueWeightUnit = 0.0283495;
5040 $totalWeight += $weight * $qty * $trueWeightUnit;
5041 } else {
5042 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
5043 }
5044 }
5045 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5046 //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
5047 $trueVolumeUnit = pow(10, $volumeUnit);
5048 //print $line->volume;
5049 $totalVolume += $volume * $qty * $trueVolumeUnit;
5050 } else {
5051 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
5052 }
5053 }
5054
5055 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5056 }
5057
5058
5064 public function setExtraParameters()
5065 {
5066 $this->db->begin();
5067
5068 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
5069
5070 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
5071 $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
5072 $sql .= " WHERE rowid = ".((int) $this->id);
5073
5074 dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
5075 $resql = $this->db->query($sql);
5076 if (!$resql) {
5077 $this->error = $this->db->lasterror();
5078 $this->db->rollback();
5079 return -1;
5080 } else {
5081 $this->db->commit();
5082 return 1;
5083 }
5084 }
5085
5086
5087 // --------------------
5088 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
5089 // --------------------
5090
5091 /* This is to show add lines */
5092
5102 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
5103 {
5104 global $conf, $user, $langs, $object, $hookmanager, $extrafields, $form;
5105
5106 // Line extrafield
5107 if (!is_object($extrafields)) {
5108 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5109 $extrafields = new ExtraFields($this->db);
5110 }
5111 $extrafields->fetch_name_optionals_label($this->table_element_line);
5112
5113 // Output template part (modules that overwrite templates must declare this into descriptor)
5114 // Use global variables + $dateSelector + $seller and $buyer
5115 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
5116 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5117 foreach ($dirtpls as $module => $reldir) {
5118 if (!empty($module)) {
5119 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
5120 } else {
5121 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
5122 }
5123
5124 if (empty($conf->file->strict_mode)) {
5125 $res = @include $tpl;
5126 } else {
5127 $res = include $tpl; // for debug
5128 }
5129 if ($res) {
5130 break;
5131 }
5132 }
5133 }
5134
5135
5136
5137 /* This is to show array of line of details */
5138
5139
5154 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
5155 {
5156 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
5157 // TODO We should not use global var for this
5158 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5159
5160 // Define $usemargins (used by objectline_xxx.tpl.php files)
5161 $usemargins = 0;
5162 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
5163 $usemargins = 1;
5164 }
5165
5166 $num = count($this->lines);
5167
5168 // Line extrafield
5169 if (!is_object($extrafields)) {
5170 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5171 $extrafields = new ExtraFields($this->db);
5172 }
5173 $extrafields->fetch_name_optionals_label($this->table_element_line);
5174
5175 $parameters = array('num' => $num, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
5176 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5177 if (empty($reshook)) {
5178 // Output template part (modules that overwrite templates must declare this into descriptor)
5179 // Use global variables + $dateSelector + $seller and $buyer
5180 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
5181 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5182 foreach ($dirtpls as $module => $reldir) {
5183 $res = 0;
5184 if (!empty($module)) {
5185 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
5186 } else {
5187 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
5188 }
5189 if (file_exists($tpl)) {
5190 if (empty($conf->file->strict_mode)) {
5191 $res = @include $tpl;
5192 } else {
5193 $res = include $tpl; // for debug
5194 }
5195 }
5196 if ($res) {
5197 break;
5198 }
5199 }
5200 }
5201
5202 $i = 0;
5203
5204 print "<!-- begin printObjectLines() --><tbody>\n";
5205 foreach ($this->lines as $line) {
5206 //Line extrafield
5207 $line->fetch_optionals();
5208
5209 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
5210 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5211 if (empty($line->fk_parent_line)) {
5212 $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element, 'defaulttpldir' => $defaulttpldir);
5213 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5214 } else {
5215 $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, 'defaulttpldir' => $defaulttpldir);
5216 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5217 }
5218 }
5219 if (empty($reshook)) {
5220 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5221 }
5222
5223 $i++;
5224 }
5225 print "</tbody><!-- end printObjectLines() -->\n";
5226 }
5227
5245 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
5246 {
5247 global $conf, $langs, $user, $object, $hookmanager;
5248 global $form;
5249 global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
5250
5251 $object_rights = $this->getRights();
5252
5253 // var used into tpl
5254 $text = '';
5255 $description = '';
5256
5257 // Line in view mode
5258 if ($action != 'editline' || $selected != $line->id) {
5259 // Product
5260 if (!empty($line->fk_product) && $line->fk_product > 0) {
5261 $product_static = new Product($this->db);
5262 $product_static->fetch($line->fk_product);
5263
5264 $product_static->ref = $line->ref; //can change ref in hook
5265 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5266
5267 $text = $product_static->getNomUrl(1);
5268
5269 // Define output language and label
5270 if (getDolGlobalInt('MAIN_MULTILANGS')) {
5271 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5272 dol_print_error(null, 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5273 return;
5274 }
5275
5276 $prod = new Product($this->db);
5277 $prod->fetch($line->fk_product);
5278
5279 $outputlangs = $langs;
5280 $newlang = '';
5281 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5282 $newlang = GETPOST('lang_id', 'aZ09');
5283 }
5284 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5285 $newlang = $this->thirdparty->default_lang; // To use language of customer
5286 }
5287 if (!empty($newlang)) {
5288 $outputlangs = new Translate("", $conf);
5289 $outputlangs->setDefaultLang($newlang);
5290 }
5291
5292 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5293 } else {
5294 $label = $line->product_label;
5295 }
5296
5297 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5298 $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.
5299 }
5300
5301 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5302
5303 // Output template part (modules that overwrite templates must declare this into descriptor)
5304 // Use global variables + $dateSelector + $seller and $buyer
5305 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5306 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5307 foreach ($dirtpls as $module => $reldir) {
5308 $res = 0;
5309 if (!empty($module)) {
5310 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5311 } else {
5312 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5313 }
5314 //var_dump($tpl);
5315 if (file_exists($tpl)) {
5316 if (empty($conf->file->strict_mode)) {
5317 $res = @include $tpl;
5318 } else {
5319 $res = include $tpl; // for debug
5320 }
5321 }
5322 if ($res) {
5323 break;
5324 }
5325 }
5326 }
5327
5328 // Line in update mode
5329 if ($this->status == 0 && $action == 'editline' && $selected == $line->id) {
5330 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5331
5332 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5333
5334 // Output template part (modules that overwrite templates must declare this into descriptor)
5335 // Use global variables + $dateSelector + $seller and $buyer
5336 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5337 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5338 foreach ($dirtpls as $module => $reldir) {
5339 if (!empty($module)) {
5340 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5341 } else {
5342 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5343 }
5344
5345 if (empty($conf->file->strict_mode)) {
5346 $res = @include $tpl;
5347 } else {
5348 $res = include $tpl; // for debug
5349 }
5350 if ($res) {
5351 break;
5352 }
5353 }
5354 }
5355 }
5356
5357
5358 /* This is to show array of line of details of source object */
5359
5360
5371 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5372 {
5373 global $langs, $hookmanager, $form, $action;
5374
5375 print '<tr class="liste_titre">';
5376 print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5377 print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5378 print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5379 print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5380 if (isModEnabled("multicurrency")) {
5381 print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5382 }
5383 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5384 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5385 print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5386 }
5387 print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5388 print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5389 print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5390 print '</tr>';
5391 $i = 0;
5392
5393 if (!empty($this->lines)) {
5394 foreach ($this->lines as $line) {
5395 $reshook = 0;
5396 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5397 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5398 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
5399 if (!empty($line->fk_parent_line)) {
5400 $parameters['fk_parent_line'] = $line->fk_parent_line;
5401 }
5402 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5403 }
5404 if (empty($reshook)) {
5405 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5406 }
5407
5408 $i++;
5409 }
5410 }
5411 }
5412
5426 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5427 {
5428 global $langs, $conf;
5429
5430 //var_dump($line);
5431 if (!empty($line->date_start)) {
5432 $date_start = $line->date_start;
5433 } else {
5434 $date_start = $line->date_debut_prevue;
5435 if ($line->date_debut_reel) {
5436 $date_start = $line->date_debut_reel;
5437 }
5438 }
5439 if (!empty($line->date_end)) {
5440 $date_end = $line->date_end;
5441 } else {
5442 $date_end = $line->date_fin_prevue;
5443 if ($line->date_fin_reel) {
5444 $date_end = $line->date_fin_reel;
5445 }
5446 }
5447
5448 $this->tpl['id'] = $line->id;
5449
5450 $this->tpl['label'] = '';
5451 if (!empty($line->fk_parent_line)) {
5452 $this->tpl['label'] .= img_picto('', 'rightarrow');
5453 }
5454
5455 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5456 $discount = new DiscountAbsolute($this->db);
5457 if (property_exists($this, 'socid')) {
5458 $discount->fk_soc = $this->socid;
5459 $discount->socid = $this->socid;
5460 }
5461 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5462 } elseif (!empty($line->fk_product)) {
5463 $productstatic = new Product($this->db);
5464 $productstatic->id = $line->fk_product;
5465 $productstatic->ref = $line->ref;
5466 $productstatic->type = $line->fk_product_type;
5467 if (empty($productstatic->ref)) {
5468 $line->fetch_product();
5469 $productstatic = $line->product;
5470 }
5471
5472 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5473 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5474 // Dates
5475 if ($line->product_type == 1 && ($date_start || $date_end)) {
5476 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5477 }
5478 } else {
5479 $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5480 if (!empty($line->desc)) {
5481 $this->tpl['label'] .= $line->desc;
5482 } else {
5483 $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5484 }
5485
5486 // Dates
5487 if ($line->product_type == 1 && ($date_start || $date_end)) {
5488 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5489 }
5490 }
5491
5492 if (!empty($line->desc)) {
5493 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5494 $discount = new DiscountAbsolute($this->db);
5495 $discount->fetch($line->fk_remise_except);
5496 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5497 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5498 $discount = new DiscountAbsolute($this->db);
5499 $discount->fetch($line->fk_remise_except);
5500 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5501 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5502 $discount = new DiscountAbsolute($this->db);
5503 $discount->fetch($line->fk_remise_except);
5504 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5505 } elseif ($line->desc == '(EXCESS PAID)') {
5506 $discount = new DiscountAbsolute($this->db);
5507 $discount->fetch($line->fk_remise_except);
5508 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5509 } else {
5510 $this->tpl['description'] = dol_trunc($line->desc, 60);
5511 }
5512 } else {
5513 $this->tpl['description'] = '&nbsp;';
5514 }
5515
5516 // VAT Rate
5517 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5518 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5519 if (!empty($line->vat_src_code) && !preg_match('/\‍(/', $this->tpl['vat_rate'])) {
5520 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5521 }
5522
5523 $this->tpl['price'] = price($line->subprice);
5524 $this->tpl['total_ht'] = price($line->total_ht);
5525 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5526 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5527 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5528 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5529 }
5530 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5531
5532 // Is the line strike or not
5533 $this->tpl['strike'] = 0;
5534 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5535 $this->tpl['strike'] = 1;
5536 }
5537
5538 // Output template part (modules that overwrite templates must declare this into descriptor)
5539 // Use global variables + $dateSelector + $seller and $buyer
5540 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5541 foreach ($dirtpls as $module => $reldir) {
5542 if (!empty($module)) {
5543 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5544 } else {
5545 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5546 }
5547
5548 if (empty($conf->file->strict_mode)) {
5549 $res = @include $tpl;
5550 } else {
5551 $res = include $tpl; // for debug
5552 }
5553 if ($res) {
5554 break;
5555 }
5556 }
5557 }
5558
5559
5560 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5571 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5572 {
5573 // phpcs:enable
5574 $this->db->begin();
5575
5576 $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5577 $sql .= "resource_id";
5578 $sql .= ", resource_type";
5579 $sql .= ", element_id";
5580 $sql .= ", element_type";
5581 $sql .= ", busy";
5582 $sql .= ", mandatory";
5583 $sql .= ") VALUES (";
5584 $sql .= ((int) $resource_id);
5585 $sql .= ", '".$this->db->escape($resource_type)."'";
5586 $sql .= ", '".$this->db->escape($this->id)."'";
5587 $sql .= ", '".$this->db->escape($this->element)."'";
5588 $sql .= ", '".$this->db->escape($busy)."'";
5589 $sql .= ", '".$this->db->escape($mandatory)."'";
5590 $sql .= ")";
5591
5592 dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5593 if ($this->db->query($sql)) {
5594 $this->db->commit();
5595 return 1;
5596 } else {
5597 $this->error = $this->db->lasterror();
5598 $this->db->rollback();
5599 return 0;
5600 }
5601 }
5602
5603 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5612 public function delete_resource($rowid, $element, $notrigger = 0)
5613 {
5614 // phpcs:enable
5615 global $user;
5616
5617 $this->db->begin();
5618
5619 $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5620 $sql .= " WHERE rowid = ".((int) $rowid);
5621
5622 dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5623
5624 $resql = $this->db->query($sql);
5625 if (!$resql) {
5626 $this->error = $this->db->lasterror();
5627 $this->db->rollback();
5628 return -1;
5629 } else {
5630 if (!$notrigger) {
5631 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5632 if ($result < 0) {
5633 $this->db->rollback();
5634 return -1;
5635 }
5636 }
5637 $this->db->commit();
5638 return 1;
5639 }
5640 }
5641
5642
5648 public function __clone()
5649 {
5650 // Force a copy of this->lines, otherwise it will point to same object.
5651 if (isset($this->lines) && is_array($this->lines)) {
5652 $nboflines = count($this->lines);
5653 for ($i = 0; $i < $nboflines; $i++) {
5654 if (is_object($this->lines[$i])) {
5655 $this->lines[$i] = clone $this->lines[$i];
5656 }
5657 }
5658 }
5659 }
5660
5674 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5675 {
5676 global $conf, $langs, $user, $hookmanager, $action;
5677
5678 $srctemplatepath = '';
5679
5680 $parameters = array('modelspath' => $modelspath, 'modele' => $modele, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'hidedesc' => $hidedesc, 'hideref' => $hideref, 'moreparams' => $moreparams);
5681 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5682
5683 if (!empty($reshook)) {
5684 return $reshook;
5685 }
5686
5687 dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5688
5689 if (empty($modele)) {
5690 $this->error = 'BadValueForParameterModele';
5691 return -1;
5692 }
5693
5694 // Increase limit for PDF build
5695 $err = error_reporting();
5696 error_reporting(0);
5697 @set_time_limit(120);
5698 error_reporting($err);
5699
5700 // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5701 $tmp = explode(':', $modele, 2);
5702 $saved_model = $modele;
5703 if (!empty($tmp[1])) {
5704 $modele = $tmp[0];
5705 $srctemplatepath = $tmp[1];
5706 }
5707
5708 // Search template files
5709 $file = '';
5710 $classname = '';
5711 $filefound = '';
5712 $dirmodels = array('/');
5713 if (is_array($conf->modules_parts['models'])) {
5714 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5715 }
5716 foreach ($dirmodels as $reldir) {
5717 foreach (array('doc', 'pdf') as $prefix) {
5718 if (in_array(get_class($this), array('Adherent'))) {
5719 // Member module use prefix_modele.class.php
5720 $file = $prefix."_".$modele.".class.php";
5721 } else {
5722 // Other module use prefix_modele.modules.php
5723 $file = $prefix."_".$modele.".modules.php";
5724 }
5725
5726 $file = dol_sanitizeFileName($file);
5727
5728 // We check if the file exists
5729 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5730 if (file_exists($file)) {
5731 $filefound = $file;
5732 $classname = $prefix.'_'.$modele;
5733 break;
5734 }
5735 }
5736 if ($filefound) {
5737 break;
5738 }
5739 }
5740
5741 if ($filefound === '' || $classname === '') {
5742 $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5743 $this->errors[] = $this->error;
5744 dol_syslog($this->error, LOG_ERR);
5745 return -1;
5746 }
5747
5748 // Sanitize $filefound
5749 $filefound = dol_sanitizePathName($filefound);
5750
5751 // If generator was found
5752 global $db; // Required to solve a conception error making an include of some code that uses $db instead of $this->db just after.
5753
5754 require_once $filefound;
5755
5756 $obj = new $classname($this->db);
5757
5758 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5759 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5760 $varfortemplatedir = $obj->scandir;
5761 if ($varfortemplatedir && getDolGlobalString($varfortemplatedir)) {
5762 $dirtoscan = getDolGlobalString($varfortemplatedir);
5763
5764 $listoffiles = array();
5765
5766 // Now we add first model found in directories scanned
5767 $listofdir = explode(',', $dirtoscan);
5768 foreach ($listofdir as $key => $tmpdir) {
5769 $tmpdir = trim($tmpdir);
5770 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5771 if (!$tmpdir) {
5772 unset($listofdir[$key]);
5773 continue;
5774 }
5775 if (is_dir($tmpdir)) {
5776 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5777 if (count($tmpfiles)) {
5778 $listoffiles = array_merge($listoffiles, $tmpfiles);
5779 }
5780 }
5781 }
5782
5783 if (count($listoffiles)) {
5784 foreach ($listoffiles as $record) {
5785 $srctemplatepath = $record['fullname'];
5786 break;
5787 }
5788 }
5789 }
5790
5791 if (empty($srctemplatepath)) {
5792 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5793 return -1;
5794 }
5795 }
5796
5797 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5798 if (!dol_is_file($srctemplatepath)) {
5799 dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5800 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5801 return -1;
5802 }
5803 }
5804
5805 // We save charset_output to restore it because write_file can change it if needed for
5806 // output format that does not support UTF8.
5807 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5808
5809 // update model_pdf in object
5810 $this->model_pdf = $saved_model;
5811
5812 if (in_array(get_class($this), array('Adherent'))) {
5813 '@phan-var-force Adherent $this';
5814 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards', $moreparams);
5815 } else {
5816 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5817 }
5818 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5819
5820 if ($resultwritefile > 0) {
5821 $outputlangs->charset_output = $sav_charset_output;
5822
5823 // We delete old preview
5824 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5825 dol_delete_preview($this);
5826
5827 // Index file in database
5828 if (!empty($obj->result['fullpath'])) {
5829 $destfull = $obj->result['fullpath'];
5830
5831 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5832 $update_main_doc_field = 0;
5833 if (!empty($obj->update_main_doc_field)) {
5834 $update_main_doc_field = 1;
5835 }
5836
5837 // Check that the file exists, before indexing it.
5838 // Hint: It does not exist, if we create a PDF and auto delete the ODT File
5839 if (dol_is_file($destfull)) {
5840 $this->indexFile($destfull, $update_main_doc_field);
5841 }
5842 } else {
5843 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);
5844 }
5845
5846 // Success in building document. We build meta file.
5847 dol_meta_create($this);
5848
5849 return 1;
5850 } else {
5851 $outputlangs->charset_output = $sav_charset_output;
5852 $this->error = $obj->error;
5853 $this->errors = $obj->errors;
5854 dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5855 return -1;
5856 }
5857 }
5858
5868 public function indexFile($destfull, $update_main_doc_field)
5869 {
5870 global $conf, $user;
5871
5872 $upload_dir = dirname($destfull);
5873 $destfile = basename($destfull);
5874 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5875
5876 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5877 $filename = basename($destfile);
5878 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5879 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5880
5881 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5882 $ecmfile = new EcmFiles($this->db);
5883 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5884
5885 // Set the public "share" key
5886 $setsharekey = false;
5887 if ($this->element == 'propal' || $this->element == 'proposal') {
5888 if (getDolGlobalInt("PROPOSAL_ALLOW_ONLINESIGN")) {
5889 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5890 }
5891 if (getDolGlobalInt("PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
5892 $setsharekey = true;
5893 }
5894 }
5895 if ($this->element == 'commande' && getDolGlobalInt("ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
5896 $setsharekey = true;
5897 }
5898 if ($this->element == 'facture' && getDolGlobalInt("INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
5899 $setsharekey = true;
5900 }
5901 if ($this->element == 'bank_account' && getDolGlobalInt("BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
5902 $setsharekey = true;
5903 }
5904 if ($this->element == 'product' && getDolGlobalInt("PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
5905 $setsharekey = true;
5906 }
5907 if ($this->element == 'contrat' && getDolGlobalInt("CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
5908 $setsharekey = true;
5909 }
5910 if ($this->element == 'fichinter' && getDolGlobalInt("FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
5911 $setsharekey = true;
5912 }
5913 if ($this->element == 'supplier_proposal' && getDolGlobalInt("SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
5914 $setsharekey = true;
5915 }
5916 if ($this->element == 'societe_rib' && getDolGlobalInt("SOCIETE_RIB_ALLOW_ONLINESIGN")) {
5917 $setsharekey = true;
5918 }
5919
5920 if ($setsharekey) {
5921 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5922 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5923 $ecmfile->share = getRandomPassword(true);
5924 }
5925 }
5926
5927 if ($result > 0) {
5928 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5929 $ecmfile->fullpath_orig = '';
5930 $ecmfile->gen_or_uploaded = 'generated';
5931 $ecmfile->description = ''; // indexed content
5932 $ecmfile->keywords = ''; // keyword content
5933 $result = $ecmfile->update($user);
5934 if ($result < 0) {
5935 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5936 return -1;
5937 }
5938 } else {
5939 $ecmfile->entity = $conf->entity;
5940 $ecmfile->filepath = $rel_dir;
5941 $ecmfile->filename = $filename;
5942 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5943 $ecmfile->fullpath_orig = '';
5944 $ecmfile->gen_or_uploaded = 'generated';
5945 $ecmfile->description = ''; // indexed content
5946 $ecmfile->keywords = ''; // keyword content
5947 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
5948 $ecmfile->src_object_id = $this->id;
5949
5950 $result = $ecmfile->create($user);
5951 if ($result < 0) {
5952 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
5953 return -1;
5954 }
5955 }
5956
5957 /*$this->result['fullname']=$destfull;
5958 $this->result['filepath']=$ecmfile->filepath;
5959 $this->result['filename']=$ecmfile->filename;*/
5960 //var_dump($obj->update_main_doc_field);exit;
5961
5962 if ($update_main_doc_field && !empty($this->table_element)) {
5963 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
5964 $sql .= " WHERE rowid = ".((int) $this->id);
5965
5966 $resql = $this->db->query($sql);
5967 if (!$resql) {
5968 dol_print_error($this->db);
5969 return -1;
5970 } else {
5971 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
5972 }
5973 }
5974 }
5975
5976 return 1;
5977 }
5978
5986 public function addThumbs($file)
5987 {
5988 $file_osencoded = dol_osencode($file);
5989
5990 if (file_exists($file_osencoded)) {
5991 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
5992
5993 $tmparraysize = getDefaultImageSizes();
5994 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
5995 $maxheightsmall = $tmparraysize['maxheightsmall'];
5996 $maxwidthmini = $tmparraysize['maxwidthmini'];
5997 $maxheightmini = $tmparraysize['maxheightmini'];
5998 //$quality = $tmparraysize['quality'];
5999 $quality = 50; // For thumbs, we force quality to 50
6000
6001 // Create small thumbs for company (Ratio is near 16/9)
6002 // Used on logon for example
6003 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
6004
6005 // Create mini thumbs for company (Ratio is near 16/9)
6006 // Used on menu or for setup page for example
6007 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
6008 }
6009 }
6010
6018 public function delThumbs($file)
6019 {
6020 $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
6021 dol_delete_file($imgThumbName);
6022 $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
6023 dol_delete_file($imgThumbName);
6024 }
6025
6026
6027 /* Functions common to commonobject and commonobjectline */
6028
6029 /* For default values */
6030
6044 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
6045 {
6046 // If param here has been posted, we use this value first.
6047 if (GETPOSTISSET($fieldname)) {
6048 return GETPOST($fieldname, $type, 3);
6049 }
6050
6051 if (isset($alternatevalue)) {
6052 return $alternatevalue;
6053 }
6054
6055 $newelement = $this->element;
6056 if ($newelement == 'facture') {
6057 $newelement = 'invoice';
6058 }
6059 if ($newelement == 'commande') {
6060 $newelement = 'order';
6061 }
6062 if (empty($newelement)) {
6063 dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6064 return '';
6065 }
6066
6067 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
6068 //var_dump($keyforfieldname);
6069 if (getDolGlobalString($keyforfieldname)) {
6070 return getDolGlobalString($keyforfieldname);
6071 }
6072
6073 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
6074 // store content into $conf->cache['overwrite_default']
6075
6076 return '';
6077 }
6078
6079
6080 /* For triggers */
6081
6082
6083 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6094 public function call_trigger($triggerName, $user)
6095 {
6096 // phpcs:enable
6097 global $langs, $conf;
6098
6099 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
6100 dol_print_error(null, 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
6101 exit;
6102 }
6103 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers().
6104 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
6105 $langs = new Translate('', $conf);
6106 }
6107
6108 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
6109 $interface = new Interfaces($this->db);
6110 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
6111
6112 if ($result < 0) {
6113 if (!empty($this->errors)) {
6114 $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.
6115 } else {
6116 $this->errors = $interface->errors;
6117 }
6118 }
6119 return $result;
6120 }
6121
6122
6123 /* Functions for data in other language */
6124
6125
6134 {
6135 // To avoid SQL errors. Probably not the better solution though
6136 if (!$this->element) {
6137 return 0;
6138 }
6139 if (!($this->id > 0)) {
6140 return 0;
6141 }
6142 if (is_array($this->array_languages)) {
6143 return 1;
6144 }
6145
6146 $this->array_languages = array();
6147
6148 $element = $this->element;
6149 if ($element == 'categorie') {
6150 $element = 'categories'; // For compatibility
6151 }
6152
6153 // Request to get translation values for object
6154 $sql = "SELECT rowid, property, lang , value";
6155 $sql .= " FROM ".$this->db->prefix()."object_lang";
6156 $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
6157 $sql .= " AND fk_object = ".((int) $this->id);
6158
6159 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6160 $resql = $this->db->query($sql);
6161 if ($resql) {
6162 $numrows = $this->db->num_rows($resql);
6163 if ($numrows) {
6164 $i = 0;
6165 while ($i < $numrows) {
6166 $obj = $this->db->fetch_object($resql);
6167 $key = $obj->property;
6168 $value = $obj->value;
6169 $codelang = $obj->lang;
6170 $type = $this->fields[$key]['type'];
6171
6172 // we can add this attribute to object
6173 if (preg_match('/date/', $type)) {
6174 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6175 } else {
6176 $this->array_languages[$key][$codelang] = $value;
6177 }
6178
6179 $i++;
6180 }
6181 }
6182
6183 $this->db->free($resql);
6184
6185 if ($numrows) {
6186 return $numrows;
6187 } else {
6188 return 0;
6189 }
6190 } else {
6191 dol_print_error($this->db);
6192 return -1;
6193 }
6194 }
6195
6202 public function setValuesForExtraLanguages($onlykey = '')
6203 {
6204 // Get extra fields
6205 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6206 $tmparray = explode('-', $postfieldkey);
6207 if ($tmparray[0] != 'field') {
6208 continue;
6209 }
6210
6211 $element = $tmparray[1];
6212 $key = $tmparray[2];
6213 $codelang = $tmparray[3];
6214 //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
6215
6216 if (!empty($onlykey) && $key != $onlykey) {
6217 continue;
6218 }
6219 if ($element != $this->element) {
6220 continue;
6221 }
6222
6223 $key_type = $this->fields[$key]['type'];
6224
6225 $enabled = 1;
6226 if (isset($this->fields[$key]['enabled'])) {
6227 $enabled = (int) dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
6228 }
6229 /*$perms = 1;
6230 if (isset($this->fields[$key]['perms']))
6231 {
6232 $perms = (int) dol_eval($this->fields[$key]['perms'], 1, 1, '1');
6233 }*/
6234 if (empty($enabled)) {
6235 continue;
6236 }
6237 //if (empty($perms)) continue;
6238
6239 if (in_array($key_type, array('date'))) {
6240 // Clean parameters
6241 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6242 $value_key = dol_mktime(0, 0, 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6243 } elseif (in_array($key_type, array('datetime'))) {
6244 // Clean parameters
6245 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6246 $value_key = dol_mktime(GETPOSTINT($postfieldkey."hour"), GETPOSTINT($postfieldkey."min"), 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6247 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
6248 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
6249 if (!empty($value_arr)) {
6250 $value_key = implode(',', $value_arr);
6251 } else {
6252 $value_key = '';
6253 }
6254 } elseif (in_array($key_type, array('price', 'double'))) {
6255 $value_arr = GETPOST($postfieldkey, 'alpha');
6256 $value_key = price2num($value_arr);
6257 } else {
6258 $value_key = GETPOST($postfieldkey);
6259 if (in_array($key_type, array('link')) && $value_key == '-1') {
6260 $value_key = '';
6261 }
6262 }
6263
6264 $this->array_languages[$key][$codelang] = $value_key;
6265
6266 /*if ($nofillrequired) {
6267 $langs->load('errors');
6268 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
6269 return -1;
6270 }*/
6271 }
6272
6273 return 1;
6274 }
6275
6276
6277 /* Functions for extrafields */
6278
6285 public function fetchNoCompute($id)
6286 {
6287 global $conf;
6288
6289 $savDisableCompute = $conf->disable_compute;
6290 $conf->disable_compute = 1;
6291
6292 $ret = $this->fetch($id); /* @phpstan-ignore-line */
6293
6294 $conf->disable_compute = $savDisableCompute;
6295
6296 return $ret;
6297 }
6298
6299 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6309 public function fetch_optionals($rowid = null, $optionsArray = null)
6310 {
6311 // phpcs:enable
6312 global $conf, $extrafields;
6313
6314 if (empty($rowid)) {
6315 $rowid = $this->id;
6316 }
6317 if (empty($rowid) && isset($this->rowid)) {
6318 $rowid = $this->rowid; // deprecated
6319 }
6320
6321 // To avoid SQL errors. Probably not the better solution though
6322 if (!$this->table_element) {
6323 return 0;
6324 }
6325
6326 $this->array_options = array();
6327
6328 if (!is_array($optionsArray)) {
6329 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6330 if (!isset($extrafields) || !is_object($extrafields)) {
6331 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6332 $extrafields = new ExtraFields($this->db);
6333 }
6334
6335 // Load array of extrafields for elementype = $this->table_element
6336 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6337 $extrafields->fetch_name_optionals_label($this->table_element);
6338 }
6339 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6340 } else {
6341 global $extrafields;
6342 dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6343 }
6344
6345 $table_element = $this->table_element;
6346 if ($table_element == 'categorie') {
6347 $table_element = 'categories'; // For compatibility
6348 }
6349
6350 // Request to get complementary values
6351 if (is_array($optionsArray) && count($optionsArray) > 0) {
6352 $sql = "SELECT rowid";
6353 foreach ($optionsArray as $name => $label) {
6354 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || (!in_array($extrafields->attributes[$this->table_element]['type'][$name], ['separate', 'point', 'multipts', 'linestrg','polygon']))) {
6355 $sql .= ", ".$name;
6356 }
6357 // use geo sql fonction to read as text
6358 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'point') {
6359 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6360 }
6361 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'multipts') {
6362 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6363 }
6364 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'linestrg') {
6365 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6366 }
6367 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'polygon') {
6368 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6369 }
6370 }
6371 $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6372 $sql .= " WHERE fk_object = ".((int) $rowid);
6373
6374 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6375 $resql = $this->db->query($sql);
6376 if ($resql) {
6377 $numrows = $this->db->num_rows($resql);
6378 if ($numrows) {
6379 $tab = $this->db->fetch_array($resql);
6380
6381 foreach ($tab as $key => $value) {
6382 // 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)
6383 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6384 // we can add this attribute to object
6385 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6386 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6387 $this->array_options["options_".$key] = $this->db->jdate($value);
6388 } else {
6389 $this->array_options["options_".$key] = $value;
6390 }
6391
6392 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6393 }
6394 if (!empty($extrafields->attributes[$this->table_element]['type'][$key]) && $extrafields->attributes[$this->table_element]['type'][$key] == 'password') {
6395 if (!empty($value) && preg_match('/^dolcrypt:/', $value)) {
6396 $this->array_options["options_".$key] = dolDecrypt($value);
6397 }
6398 }
6399 }
6400 } else {
6405 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6406 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6407 $this->array_options['options_' . $key] = null;
6408 }
6409 }
6410 }
6411
6412 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6413 // in the element's extrafields table)
6414 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6415 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6416 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6417 //var_dump($conf->disable_compute);
6418 if (empty($conf->disable_compute)) {
6419 global $objectoffield; // We set a global variable to $objectoffield so
6420 $objectoffield = $this; // we can use it inside computed formula
6421 $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
6422 }
6423 }
6424 }
6425 }
6426
6427 $this->db->free($resql);
6428
6429 if ($numrows) {
6430 return $numrows;
6431 } else {
6432 return 0;
6433 }
6434 } else {
6435 $this->errors[] = $this->db->lasterror;
6436 return -1;
6437 }
6438 }
6439 return 0;
6440 }
6441
6448 public function deleteExtraFields()
6449 {
6450 global $conf;
6451
6452 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6453 return 0;
6454 }
6455
6456 $this->db->begin();
6457
6458 $table_element = $this->table_element;
6459 if ($table_element == 'categorie') {
6460 $table_element = 'categories'; // For compatibility
6461 }
6462
6463 dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6464
6465 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6466
6467 $resql = $this->db->query($sql_del);
6468 if (!$resql) {
6469 $this->error = $this->db->lasterror();
6470 $this->db->rollback();
6471 return -1;
6472 } else {
6473 $this->db->commit();
6474 return 1;
6475 }
6476 }
6477
6488 public function insertExtraFields($trigger = '', $userused = null)
6489 {
6490 global $conf, $langs, $user;
6491
6492 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6493 return 0;
6494 }
6495
6496 if (empty($userused)) {
6497 $userused = $user;
6498 }
6499
6500 $error = 0;
6501
6502 if (!empty($this->array_options)) {
6503 // Check parameters
6504 $langs->load('admin');
6505 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6506 $extrafields = new ExtraFields($this->db);
6507 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6508
6509 // Eliminate copied source object extra fields that do not exist in target object
6510 $new_array_options = array();
6511 foreach ($this->array_options as $key => $value) {
6512 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6513 $new_array_options[$key] = $value;
6514 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
6515 $new_array_options['options_'.$key] = $value;
6516 }
6517 }
6518
6519 foreach ($new_array_options as $key => $value) {
6520 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6521 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6522 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element]['label'][$attributeKey]);
6523 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6524 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6525 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6526 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6527
6528 // If we clone, we have to clean unique extrafields to prevent duplicates.
6529 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6530 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6531 $new_array_options[$key] = null;
6532 }
6533
6534 // Similar code than into insertExtraFields
6535 if ($attributeRequired) {
6536 $v = $this->array_options[$key];
6537 if (ExtraFields::isEmptyValue($v, $attributeType)) {
6538 $langs->load("errors");
6539 dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6540 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6541 return -1;
6542 }
6543 }
6544
6545 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6546 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6547
6548 if (!empty($attrfieldcomputed)) {
6549 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
6550 $value = dol_eval($attrfieldcomputed, 1, 0, '2');
6551 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
6552 $new_array_options[$key] = $value;
6553 } else {
6554 $new_array_options[$key] = null;
6555 }
6556 }
6557
6558 switch ($attributeType) {
6559 case 'int':
6560 if (!is_numeric($value) && $value != '') {
6561 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6562 return -1;
6563 } elseif ($value == '') {
6564 $new_array_options[$key] = null;
6565 }
6566 break;
6567 case 'price':
6568 case 'double':
6569 $value = price2num($value);
6570 if (!is_numeric($value) && $value != '') {
6571 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6572 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6573 return -1;
6574 } elseif ($value == '') {
6575 $value = null;
6576 }
6577 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6578 $new_array_options[$key] = $value;
6579 break;
6580 /*case 'select': // Not required, we chose value='0' for undefined values
6581 if ($value=='-1')
6582 {
6583 $this->array_options[$key] = null;
6584 }
6585 break;*/
6586 case 'password':
6587 $algo = '';
6588 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6589 // If there is an encryption choice, we use it to encrypt data before insert
6590 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6591 $algo = reset($tmparrays);
6592 if ($algo != '') {
6593 //global $action; // $action may be 'create', 'update', 'update_extras'...
6594 //var_dump($action);
6595 //var_dump($this->oldcopy);exit;
6596 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
6597 //var_dump('algo='.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
6598 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6599 // If old value encrypted in database is same than submitted new value, it means we don't change it, so we don't update.
6600 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
6601 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
6602 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6603 } else {
6604 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6605 }
6606 } else {
6607 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6608 }
6609 } else {
6610 // If value has changed
6611 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
6612 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
6613 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6614 } else {
6615 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6616 }
6617 } else {
6618 $new_array_options[$key] = dol_hash($this->array_options[$key], $algo);
6619 }
6620 }
6621 } else {
6622 //var_dump('jjj'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
6623 // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
6624 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options[$key])) { // dolibarr reversible encryption
6625 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6626 } else {
6627 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6628 }
6629 }
6630 } else {
6631 // No encryption
6632 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6633 }
6634 } else { // Common usage
6635 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6636 }
6637 break;
6638 case 'date':
6639 case 'datetime':
6640 // If data is a string instead of a timestamp, we convert it
6641 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6642 $this->array_options[$key] = strtotime($this->array_options[$key]);
6643 }
6644 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6645 break;
6646 case 'datetimegmt':
6647 // If data is a string instead of a timestamp, we convert it
6648 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6649 $this->array_options[$key] = strtotime($this->array_options[$key]);
6650 }
6651 $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
6652 break;
6653 case 'link':
6654 $param_list = array_keys($attributeParam['options']);
6655 // 0 : ObjectName
6656 // 1 : classPath
6657 $InfoFieldList = explode(":", $param_list[0]);
6658 dol_include_once($InfoFieldList[1]);
6659 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6660 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6661 $new_array_options[$key] = '';
6662 } elseif ($value) {
6663 $object = new $InfoFieldList[0]($this->db);
6664 if (is_numeric($value)) {
6665 $res = $object->fetch($value); // Common case
6666 } else {
6667 $res = $object->fetch('', $value); // For compatibility
6668 }
6669
6670 if ($res > 0) {
6671 $new_array_options[$key] = $object->id;
6672 } else {
6673 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6674 return -1;
6675 }
6676 }
6677 } else {
6678 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6679 }
6680 break;
6681 case 'checkbox':
6682 case 'chkbxlst':
6683 if (is_array($this->array_options[$key])) {
6684 $new_array_options[$key] = implode(',', $this->array_options[$key]);
6685 } else {
6686 $new_array_options[$key] = $this->array_options[$key];
6687 }
6688 break;
6689 }
6690 }
6691
6692 $this->db->begin();
6693
6694 $table_element = $this->table_element;
6695 if ($table_element == 'categorie') {
6696 $table_element = 'categories'; // For compatibility
6697 }
6698
6699 dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6700
6701 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6702 $this->db->query($sql_del);
6703
6704 $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6705 foreach ($new_array_options as $key => $value) {
6706 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6707 // Add field of attribute
6708 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6709 $sql .= ",".$attributeKey;
6710 }
6711 }
6712 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6713 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6714 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6715 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6716 $sql .= ",".$tmpkey;
6717 }
6718 }
6719 }
6720 $sql .= ") VALUES (".$this->id;
6721
6722 foreach ($new_array_options as $key => $value) {
6723 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6724 // Add field of attribute
6725 if (!in_array($extrafields->attributes[$this->table_element]['type'][$attributeKey], ['separate', 'point', 'multipts', 'linestrg', 'polygon'])) { // Only for other type than separator)
6726 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6727 $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6728 } else {
6729 $sql .= ",null";
6730 }
6731 }
6732 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'point') { // for point type
6733 if (!empty($new_array_options[$key])) {
6734 $sql .= ",ST_PointFromText('".$this->db->escape($new_array_options[$key])."')";
6735 } else {
6736 $sql .= ",null";
6737 }
6738 }
6739 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'multipts') { // for point type
6740 if (!empty($new_array_options[$key])) {
6741 $sql .= ",ST_MultiPointFromText('".$this->db->escape($new_array_options[$key])."')";
6742 } else {
6743 $sql .= ",null";
6744 }
6745 }
6746 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'linestrg') { // for linestring type
6747 if (!empty($new_array_options[$key])) {
6748 $sql .= ",ST_LineFromText('".$this->db->escape($new_array_options[$key])."')";
6749 } else {
6750 $sql .= ",null";
6751 }
6752 }
6753 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'polygon') { // for polygon type
6754 if (!empty($new_array_options[$key])) {
6755 $sql .= ",ST_PolyFromText('".$this->db->escape($new_array_options[$key])."')";
6756 } else {
6757 $sql .= ",null";
6758 }
6759 }
6760 }
6761 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6762 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6763 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6764 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6765 if (in_array($tmpval, array('int', 'double', 'price'))) {
6766 $sql .= ", 0";
6767 } else {
6768 $sql .= ", ''";
6769 }
6770 }
6771 }
6772 }
6773
6774 $sql .= ")";
6775
6776 $resql = $this->db->query($sql);
6777 if (!$resql) {
6778 $this->error = $this->db->lasterror();
6779 $error++;
6780 }
6781
6782 if (!$error && $trigger) {
6783 // Call trigger
6784 $this->context = array('extrafieldaddupdate' => 1);
6785 $result = $this->call_trigger($trigger, $userused);
6786 if ($result < 0) {
6787 $error++;
6788 }
6789 // End call trigger
6790 }
6791
6792 if ($error) {
6793 $this->db->rollback();
6794 return -1;
6795 } else {
6796 $this->db->commit();
6797 return 1;
6798 }
6799 } else {
6800 return 0;
6801 }
6802 }
6803
6814 public function insertExtraLanguages($trigger = '', $userused = null)
6815 {
6816 global $conf, $langs, $user;
6817
6818 if (empty($userused)) {
6819 $userused = $user;
6820 }
6821
6822 $error = 0;
6823
6824 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
6825 return 0; // For avoid conflicts if trigger used
6826 }
6827
6828 if (is_array($this->array_languages)) {
6829 $new_array_languages = $this->array_languages;
6830
6831 foreach ($new_array_languages as $key => $value) {
6832 $attributeKey = $key;
6833 $attributeType = $this->fields[$attributeKey]['type'];
6834 $attributeLabel = $this->fields[$attributeKey]['label'];
6835
6836 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6837 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6838
6839 switch ($attributeType) {
6840 case 'int':
6841 if (is_array($value) || (!is_numeric($value) && $value != '')) {
6842 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6843 return -1;
6844 } elseif ($value == '') {
6845 $new_array_languages[$key] = null;
6846 }
6847 break;
6848 case 'double':
6849 $value = price2num($value);
6850 if (!is_numeric($value) && $value != '') {
6851 dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6852 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6853 return -1;
6854 } elseif ($value == '') {
6855 $new_array_languages[$key] = null;
6856 } else {
6857 $new_array_languages[$key] = $value;
6858 }
6859 break;
6860 /*case 'select': // Not required, we chose value='0' for undefined values
6861 if ($value=='-1')
6862 {
6863 $this->array_options[$key] = null;
6864 }
6865 break;*/
6866 }
6867 }
6868
6869 $this->db->begin();
6870
6871 $table_element = $this->table_element;
6872 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
6873 $table_element = 'categories'; // For compatibility
6874 }
6875
6876 dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6877
6878 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6879 foreach ($langcodearray as $langcode => $value) {
6880 $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6881 $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6882 $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6883 $this->db->query($sql_del);
6884
6885 if ($value !== '') {
6886 $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6887 $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6888 $sql .= ")";
6889
6890 $resql = $this->db->query($sql);
6891 if (!$resql) {
6892 $this->error = $this->db->lasterror();
6893 $error++;
6894 break;
6895 }
6896 }
6897 }
6898 }
6899
6900 if (!$error && $trigger) {
6901 // Call trigger
6902 $this->context = array('extralanguagesaddupdate' => 1);
6903 $result = $this->call_trigger($trigger, $userused);
6904 if ($result < 0) {
6905 $error++;
6906 }
6907 // End call trigger
6908 }
6909
6910 if ($error) {
6911 $this->db->rollback();
6912 return -1;
6913 } else {
6914 $this->db->commit();
6915 return 1;
6916 }
6917 } else {
6918 return 0;
6919 }
6920 }
6921
6932 public function updateExtraField($key, $trigger = null, $userused = null)
6933 {
6934 global $conf, $langs, $user, $hookmanager;
6935
6936 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6937 return 0;
6938 }
6939
6940 if (empty($userused)) {
6941 $userused = $user;
6942 }
6943
6944 $error = 0;
6945
6946 if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
6947 // Check parameters
6948 $langs->load('admin');
6949 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6950 $extrafields = new ExtraFields($this->db);
6951 $extrafields->fetch_name_optionals_label($this->table_element);
6952
6953 $value = $this->array_options["options_".$key];
6954
6955 $attributeKey = $key;
6956 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
6957 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
6958 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
6959 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
6960 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6961 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
6962
6963 // Similar code than into insertExtraFields
6964 if ($attributeRequired) {
6965 $mandatorypb = false;
6966 if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
6967 $mandatorypb = true;
6968 }
6969 if ($this->array_options["options_".$key] === '') {
6970 $mandatorypb = true;
6971 }
6972 if ($mandatorypb) {
6973 $langs->load("errors");
6974 dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
6975 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6976 return -1;
6977 }
6978 }
6979
6980 // $new_array_options will be used for direct update, so must contains formatted data for the UPDATE.
6981 $new_array_options = $this->array_options;
6982
6983 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6984 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6985 if (!empty($attrfieldcomputed)) {
6986 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
6987 $value = dol_eval($attrfieldcomputed, 1, 0, '2');
6988 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
6989
6990 $new_array_options["options_".$key] = $value;
6991
6992 $this->array_options["options_".$key] = $new_array_options["options_".$key];
6993 } else {
6994 $new_array_options["options_".$key] = null;
6995
6996 $this->array_options["options_".$key] = $new_array_options["options_".$key];
6997 }
6998 }
6999
7000 switch ($attributeType) {
7001 case 'int':
7002 if (!is_numeric($value) && $value != '') {
7003 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7004 return -1;
7005 } elseif ($value === '') {
7006 $new_array_options["options_".$key] = null;
7007
7008 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7009 }
7010 break;
7011 case 'price':
7012 case 'double':
7013 $value = price2num($value);
7014 if (!is_numeric($value) && $value != '') {
7015 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7016 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7017 return -1;
7018 } elseif ($value === '') {
7019 $value = null;
7020 }
7021 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
7022 $new_array_options["options_".$key] = $value;
7023
7024 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7025 break;
7026 /*case 'select': // Not required, we chose value='0' for undefined values
7027 if ($value=='-1')
7028 {
7029 $new_array_options["options_".$key] = $value;
7030
7031 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7032 }
7033 break;*/
7034 case 'password':
7035 $algo = '';
7036 if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
7037 // If there is an encryption choice, we use it to encrypt data before insert
7038 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
7039 $algo = reset($tmparrays);
7040 if ($algo != '') {
7041 //global $action; // $action may be 'create', 'update', 'update_extras'...
7042 //var_dump($action);
7043 //var_dump($this->oldcopy);exit;
7044 //var_dump($key.' '.$this->array_options["options_".$key].' '.$algo);
7045 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
7046 //var_dump($this->oldcopy->array_options["options_".$key]); var_dump($this->array_options["options_".$key]);
7047 if (isset($this->oldcopy->array_options["options_".$key]) && $this->array_options["options_".$key] == $this->oldcopy->array_options["options_".$key]) { // If old value encrypted in database is same than submitted new value, it means we don't change it, so we don't update.
7048 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7049 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7050 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7051 } else {
7052 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7053 }
7054 } else {
7055 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7056 }
7057 } else {
7058 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7059 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7060 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]);
7061 } else {
7062 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7063 }
7064 } else {
7065 $new_array_options["options_".$key] = dol_hash($this->array_options["options_".$key], $algo);
7066 }
7067 }
7068 } else {
7069 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { // dolibarr reversible encryption
7070 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7071 } else {
7072 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7073 }
7074 }
7075 } else {
7076 // No encryption
7077 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7078 }
7079 } else { // Common usage
7080 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7081 }
7082
7083 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7084 break;
7085 case 'date':
7086 case 'datetime':
7087 if (empty($this->array_options["options_".$key])) {
7088 $new_array_options["options_".$key] = null;
7089
7090 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7091 } else {
7092 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
7093 }
7094 break;
7095 case 'datetimegmt':
7096 if (empty($this->array_options["options_".$key])) {
7097 $new_array_options["options_".$key] = null;
7098
7099 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7100 } else {
7101 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
7102 }
7103 break;
7104 case 'boolean':
7105 if (empty($this->array_options["options_".$key])) {
7106 $new_array_options["options_".$key] = null;
7107
7108 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7109 }
7110 break;
7111 case 'link':
7112 if ($this->array_options["options_".$key] === '') {
7113 $new_array_options["options_".$key] = null;
7114
7115 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7116 }
7117 break;
7118 /*
7119 case 'link':
7120 $param_list = array_keys($attributeParam['options']);
7121 // 0 : ObjectName
7122 // 1 : classPath
7123 $InfoFieldList = explode(":", $param_list[0]);
7124 dol_include_once($InfoFieldList[1]);
7125 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
7126 {
7127 if ($value == '-1') // -1 is key for no defined in combo list of objects
7128 {
7129 $new_array_options[$key] = '';
7130 } elseif ($value) {
7131 $object = new $InfoFieldList[0]($this->db);
7132 if (is_numeric($value)) $res = $object->fetch($value); // Common case
7133 else $res = $object->fetch('', $value); // For compatibility
7134
7135 if ($res > 0) $new_array_options[$key] = $object->id;
7136 else {
7137 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
7138 $this->db->rollback();
7139 return -1;
7140 }
7141 }
7142 } else {
7143 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7144 }
7145 break;
7146 */
7147 case 'checkbox':
7148 case 'chkbxlst':
7149 $new_array_options = array();
7150 if (is_array($this->array_options["options_".$key])) {
7151 $new_array_options["options_".$key] = implode(',', $this->array_options["options_".$key]);
7152 } else {
7153 $new_array_options["options_".$key] = $this->array_options["options_".$key];
7154 }
7155
7156 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7157 break;
7158 }
7159
7160 $this->db->begin();
7161
7162 $linealreadyfound = 0;
7163
7164 // 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)
7165 $table_element = $this->table_element;
7166 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
7167 $table_element = 'categories'; // For compatibility
7168 }
7169
7170 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7171 $resql = $this->db->query($sql);
7172 if ($resql) {
7173 $tmpobj = $this->db->fetch_object($resql);
7174 if ($tmpobj) {
7175 $linealreadyfound = $tmpobj->nb;
7176 }
7177 }
7178
7179 //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit;
7180 if ($linealreadyfound) {
7181 if ($this->array_options["options_".$key] === null) {
7182 $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = null";
7183 } else {
7184 $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = '".$this->db->escape($new_array_options["options_".$key])."'";
7185 }
7186 $sql .= " WHERE fk_object = ".((int) $this->id);
7187
7188 $resql = $this->db->query($sql);
7189 if (!$resql) {
7190 $error++;
7191 $this->error = $this->db->lasterror();
7192 }
7193 } else {
7194 $result = $this->insertExtraFields('', $user);
7195 if ($result < 0) {
7196 $error++;
7197 }
7198 }
7199
7200 if (!$error) {
7201 $parameters = array('key' => $key);
7202 global $action;
7203 $reshook = $hookmanager->executeHooks('updateExtraFieldBeforeCommit', $parameters, $this, $action);
7204 if ($reshook < 0) {
7205 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
7206 }
7207 }
7208
7209 if (!$error && $trigger) {
7210 // Call trigger
7211 $this->context = array('extrafieldupdate' => 1);
7212 $result = $this->call_trigger($trigger, $userused);
7213 if ($result < 0) {
7214 $error++;
7215 }
7216 // End call trigger
7217 }
7218
7219 if ($error) {
7220 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7221 $this->db->rollback();
7222 return -1;
7223 } else {
7224 $this->db->commit();
7225 return 1;
7226 }
7227 } else {
7228 return 0;
7229 }
7230 }
7231
7238 public function getExtraField($key)
7239 {
7240 return $this->array_options['options_'.$key] ?? null;
7241 }
7242
7250 public function setExtraField($key, $value)
7251 {
7252 $this->array_options['options_'.$key] = $value;
7253 }
7254
7265 public function updateExtraLanguages($key, $trigger = null, $userused = null)
7266 {
7267 global $conf, $langs, $user;
7268
7269 if (empty($userused)) {
7270 $userused = $user;
7271 }
7272
7273 $error = 0;
7274
7275 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
7276 return 0; // For avoid conflicts if trigger used
7277 }
7278
7279 return 0;
7280 }
7281
7282
7298 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
7299 {
7300 global $conf, $langs, $form;
7301
7302 if (!is_object($form)) {
7303 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7304 $form = new Form($this->db);
7305 }
7306
7307 if (!empty($this->fields)) {
7308 $val = $this->fields[$key];
7309 }
7310
7311 // Validation tests and output
7312 $fieldValidationErrorMsg = '';
7313 $validationClass = '';
7314 $fieldValidationErrorMsg = $this->getFieldError($key);
7315 if (!empty($fieldValidationErrorMsg)) {
7316 $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
7317 } else {
7318 $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
7319 }
7320
7321 $valuemultiselectinput = array();
7322 $out = '';
7323 $type = '';
7324 $isDependList = 0;
7325 $param = array();
7326 $param['options'] = array();
7327 $reg = array();
7328 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7329 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
7330 // Because we work on extrafields
7331 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7332 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7333 $type = 'link';
7334 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7335 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7336 $type = 'link';
7337 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
7338 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7339 $type = 'link';
7340 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7341 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7342 $type = 'sellist';
7343 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7344 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7345 $type = 'sellist';
7346 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
7347 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7348 $type = 'sellist';
7349 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
7350 $param['options'] = array($reg[1] => 'N');
7351 $type = 'chkbxlst';
7352 } elseif (preg_match('/varchar\‍((\d+)\‍)/', $val['type'], $reg)) {
7353 $param['options'] = array();
7354 $type = 'varchar';
7355 $size = $reg[1];
7356 } elseif (preg_match('/varchar/', $val['type'])) {
7357 $param['options'] = array();
7358 $type = 'varchar';
7359 } else {
7360 $param['options'] = array();
7361 $type = $this->fields[$key]['type'];
7362 }
7363 //var_dump($type); var_dump($param['options']);
7364
7365 // Special case that force options and type ($type can be integer, varchar, ...)
7366 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
7367 $param['options'] = $this->fields[$key]['arrayofkeyval'];
7368 // Special case that prevent to force $type to have multiple input
7369 if (empty($this->fields[$key]['multiinput'])) {
7370 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
7371 }
7372 }
7373
7374 $label = $this->fields[$key]['label'];
7375 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
7376 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7377 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
7378 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7379 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
7380 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7381 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
7382 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7383 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
7384 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7385 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
7386
7387 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7388 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
7389 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7390 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
7391 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
7392
7393 $objectid = $this->id;
7394
7395 if ($computed) {
7396 if (!preg_match('/^search_/', $keyprefix)) {
7397 return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
7398 } else {
7399 return '';
7400 }
7401 }
7402
7403 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
7404 if (empty($morecss) && !empty($val['css'])) {
7405 $morecss = $val['css'];
7406 } elseif (empty($morecss)) {
7407 if ($type == 'date') {
7408 $morecss = 'minwidth100imp';
7409 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
7410 $morecss = 'minwidth200imp';
7411 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
7412 $morecss = 'maxwidth75';
7413 } elseif ($type == 'url') {
7414 $morecss = 'minwidth400';
7415 } elseif ($type == 'boolean') {
7416 $morecss = '';
7417 } else {
7418 if (is_numeric($size) && round((float) $size) < 12) {
7419 $morecss = 'minwidth100';
7420 } elseif (is_numeric($size) && round((float) $size) <= 48) {
7421 $morecss = 'minwidth200';
7422 } else {
7423 $morecss = 'minwidth400';
7424 }
7425 }
7426 }
7427
7428 // Add validation state class
7429 if (!empty($validationClass)) {
7430 $morecss .= $validationClass;
7431 }
7432
7433 if (in_array($type, array('date'))) {
7434 $tmp = explode(',', $size);
7435 $newsize = $tmp[0];
7436 $showtime = 0;
7437
7438 // Do not show current date when field not required (see selectDate() method)
7439 if (!$required && $value == '') {
7440 $value = '-1';
7441 }
7442
7443 // TODO Must also support $moreparam
7444 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
7445 } elseif (in_array($type, array('datetime'))) {
7446 $tmp = explode(',', $size);
7447 $newsize = $tmp[0];
7448 $showtime = 1;
7449
7450 // Do not show current date when field not required (see selectDate() method)
7451 if (!$required && $value == '') {
7452 $value = '-1';
7453 }
7454
7455 // TODO Must also support $moreparam
7456 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
7457 } elseif (in_array($type, array('duration'))) {
7458 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
7459 } elseif (in_array($type, array('int', 'integer'))) {
7460 $tmp = explode(',', $size);
7461 $newsize = $tmp[0];
7462 $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' : '').'>';
7463 } elseif (in_array($type, array('real'))) {
7464 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7465 } elseif (preg_match('/varchar/', (string) $type)) {
7466 $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' : '').'>';
7467 } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
7468 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7469 } elseif (preg_match('/^text/', (string) $type)) {
7470 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7471 if (!empty($param['options'])) {
7472 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
7473 //var_dump($param['options']);
7474 $out .= $form->selectarray($keyprefix.$key.$keysuffix."_multiinput", $param['options'], '', 1, 0, 0, "flat maxwidthonphone".$morecss);
7475 $out .= "<script>";
7476 $out .= '
7477 function handlemultiinputdisabling(htmlname){
7478 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7479 multiinput = $("#"+htmlname+"_multiinput");
7480 multiinput.find("option").each(function(){
7481 tmpval = $("#"+htmlname).val();
7482 tmpvalarray = tmpval.split(",");
7483 valtotest = $(this).val();
7484 if(tmpvalarray.includes(valtotest)){
7485 $(this).prop("disabled",true);
7486 } else {
7487 if($(this).prop("disabled") == true){
7488 console.log(valtotest)
7489 $(this).prop("disabled", false);
7490 }
7491 }
7492 });
7493 }
7494
7495 $(document).ready(function () {
7496 $("#'.$keyprefix.$key.$keysuffix.'_multiinput").on("change",function() {
7497 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.'");
7498 tmpval = $("#'.$keyprefix.$key.$keysuffix.'").val();
7499 tmpvalarray = tmpval.split(",");
7500 valtotest = $(this).val();
7501 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7502 if(tmpval == ""){
7503 tmpval = valtotest;
7504 } else {
7505 tmpval = tmpval + "," + valtotest;
7506 }
7507 $("#'.$keyprefix.$key.$keysuffix.'").val(tmpval);
7508 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7509 }
7510 });
7511 $("#'.$keyprefix.$key.$keysuffix.'").on("change",function(){
7512 handlemultiinputdisabling($(this).attr("id"));
7513 });
7514 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7515 })';
7516 $out .= "</script>";
7517 }
7518 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7519 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
7520 $out .= (string) $doleditor->Create(1, '', true, '', '', '', $morecss);
7521 } else {
7522 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7523 }
7524 } elseif (preg_match('/^html/', (string) $type)) {
7525 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7526 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7527 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
7528 $out = (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
7529 } else {
7530 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7531 }
7532 } elseif ($type == 'boolean') {
7533 $checked = '';
7534 if (!empty($value)) {
7535 $checked = ' checked value="1" ';
7536 } else {
7537 $checked = ' value="1" ';
7538 }
7539 $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
7540 } elseif ($type == 'price') {
7541 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7542 $value = price($value);
7543 }
7544 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
7545 } elseif (preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
7546 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7547 $value = price($value);
7548 }
7549 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
7550 } elseif ($type == 'select') { // combo list
7551 $out = '';
7552 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7553 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7554 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7555 }
7556
7557 $tmpselect = '';
7558 $nbchoice = 0;
7559 foreach ($param['options'] as $keyb => $valb) {
7560 if ((string) $keyb == '') {
7561 continue;
7562 }
7563 if (strpos($valb, "|") !== false) {
7564 list($valb, $parent) = explode('|', $valb);
7565 }
7566 $nbchoice++;
7567 $tmpselect .= '<option value="'.$keyb.'"';
7568 $tmpselect .= (((string) $value == (string) $keyb) ? ' selected' : '');
7569 if (!empty($parent)) {
7570 $isDependList = 1;
7571 }
7572 $tmpselect .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7573 $tmpselect .= '>'.$langs->trans($valb).'</option>';
7574 }
7575
7576 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7577 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1) || $nbchoice >= 2) {
7578 $out .= '<option value="0">&nbsp;</option>';
7579 }
7580 $out .= $tmpselect;
7581 $out .= '</select>';
7582 } elseif ($type == 'sellist') {
7583 $out = '';
7584 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7585 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7586 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7587 }
7588
7589 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7590 if (is_array($param['options'])) {
7591 $param_list = array_keys($param['options']);
7592 $InfoFieldList = explode(":", $param_list[0], 5);
7593 if (! empty($InfoFieldList[4])) {
7594 $pos = 0;
7595 $parenthesisopen = 0;
7596 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
7597 if (substr($InfoFieldList[4], $pos, 1) == '(') {
7598 $parenthesisopen++;
7599 }
7600 if (substr($InfoFieldList[4], $pos, 1) == ')') {
7601 $parenthesisopen--;
7602 }
7603 $pos++;
7604 }
7605 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7606 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7607 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
7608 $InfoFieldList[4] = $tmpbefore;
7609 if ($tmpafter !== '') {
7610 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
7611 }
7612 //var_dump($InfoFieldList);
7613 }
7614 $parentName = '';
7615 $parentField = '';
7616
7617 // 0 : tableName
7618 // 1 : label field name
7619 // 2 : key fields name (if differ of rowid)
7620 // 3 : key field parent (for dependent lists)
7621 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7622 // 5 : id category type
7623 // 6 : ids categories list separated by comma for category root
7624 // 7 : sort field
7625 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7626
7627 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7628 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7629 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7630 } else {
7631 $keyList = $InfoFieldList[2].' as rowid';
7632 }
7633 }
7634 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7635 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7636 $keyList .= ', '.$parentField;
7637 }
7638
7639 $filter_categorie = false;
7640 if (count($InfoFieldList) > 5) {
7641 if ($InfoFieldList[0] == 'categorie') {
7642 $filter_categorie = true;
7643 }
7644 }
7645
7646 if (!$filter_categorie) {
7647 $fields_label = explode('|', $InfoFieldList[1]);
7648 if (is_array($fields_label)) {
7649 $keyList .= ', ';
7650 $keyList .= implode(', ', $fields_label);
7651 }
7652
7653 $sqlwhere = '';
7654 $sql = "SELECT " . $keyList;
7655 $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
7656 if (!empty($InfoFieldList[4])) {
7657 // can use SELECT request
7658 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7659 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7660 }
7661
7662 // current object id can be use into filter
7663 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7664 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
7665 } else {
7666 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7667 }
7668
7669 // We have to join on extrafield table
7670 $errstr = '';
7671 if (strpos($InfoFieldList[4], 'extra') !== false) {
7672 $sql .= " as main, " . $this->db->prefix() . $InfoFieldList[0] . "_extrafields as extra";
7673 $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2];
7674 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
7675 } else {
7676 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
7677 }
7678 } else {
7679 $sqlwhere .= ' WHERE 1=1';
7680 }
7681 // Some tables may have field, some other not. For the moment we disable it.
7682 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7683 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7684 }
7685 $sql .= $sqlwhere;
7686 //print $sql;
7687
7688 // Note: $InfoFieldList can be 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:Sortfield]]]]]]'
7689 if (isset($InfoFieldList[7]) && preg_match('/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
7690 $sql .= " ORDER BY ".$this->db->escape($InfoFieldList[7]);
7691 } else {
7692 $sql .= " ORDER BY ".$this->db->sanitize(implode(', ', $fields_label));
7693 }
7694
7695 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7696 $resql = $this->db->query($sql);
7697 if ($resql) {
7698 $out .= '<option value="0">&nbsp;</option>';
7699 $num = $this->db->num_rows($resql);
7700 $i = 0;
7701 while ($i < $num) {
7702 $labeltoshow = '';
7703 $obj = $this->db->fetch_object($resql);
7704
7705 // Several field into label (eq table:code|libelle:rowid)
7706 $notrans = false;
7707 $fields_label = explode('|', $InfoFieldList[1]);
7708 if (count($fields_label) > 1) {
7709 $notrans = true;
7710 foreach ($fields_label as $field_toshow) {
7711 $labeltoshow .= $obj->$field_toshow . ' ';
7712 }
7713 } else {
7714 $labeltoshow = $obj->{$InfoFieldList[1]};
7715 }
7716 $labeltoshow = dol_trunc($labeltoshow, 45);
7717
7718 if ($value == $obj->rowid) {
7719 foreach ($fields_label as $field_toshow) {
7720 $translabel = $langs->trans($obj->$field_toshow);
7721 if ($translabel != $obj->$field_toshow) {
7722 $labeltoshow = dol_trunc($translabel) . ' ';
7723 } else {
7724 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7725 }
7726 }
7727 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7728 } else {
7729 if (!$notrans) {
7730 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7731 if ($translabel != $obj->{$InfoFieldList[1]}) {
7732 $labeltoshow = dol_trunc($translabel, 18);
7733 } else {
7734 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7735 }
7736 }
7737 if (empty($labeltoshow)) {
7738 $labeltoshow = '(not defined)';
7739 }
7740 if ($value == $obj->rowid) {
7741 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7742 }
7743
7744 if (!empty($InfoFieldList[3]) && $parentField) {
7745 $parent = $parentName . ':' . $obj->{$parentField};
7746 $isDependList = 1;
7747 }
7748
7749 $out .= '<option value="' . $obj->rowid . '"';
7750 $out .= ($value == $obj->rowid ? ' selected' : '');
7751 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7752 $out .= '>' . $labeltoshow . '</option>';
7753 }
7754
7755 $i++;
7756 }
7757 $this->db->free($resql);
7758 } else {
7759 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7760 }
7761 } else {
7762 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7763 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7764 $out .= '<option value="0">&nbsp;</option>';
7765 foreach ($data as $data_key => $data_value) {
7766 $out .= '<option value="' . $data_key . '"';
7767 $out .= ($value == $data_key ? ' selected' : '');
7768 $out .= '>' . $data_value . '</option>';
7769 }
7770 }
7771 }
7772 $out .= '</select>';
7773 } elseif ($type == 'checkbox') {
7774 $value_arr = explode(',', $value);
7775 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, 0, 0, $morecss, 0, '100%');
7776 } elseif ($type == 'radio') {
7777 $out = '';
7778 foreach ($param['options'] as $keyopt => $valopt) {
7779 $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7780 $out .= ' value="'.$keyopt.'"';
7781 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7782 $out .= ($value == $keyopt ? 'checked' : '');
7783 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7784 }
7785 } elseif ($type == 'chkbxlst') {
7786 if (is_array($value)) {
7787 $value_arr = $value;
7788 } else {
7789 $value_arr = explode(',', $value);
7790 }
7791
7792 if (is_array($param['options'])) {
7793 $param_list = array_keys($param['options']);
7794 $InfoFieldList = explode(":", $param_list[0]);
7795 $parentName = '';
7796 $parentField = '';
7797 // 0 : tableName
7798 // 1 : label field name
7799 // 2 : key fields name (if differ of rowid)
7800 // 3 : key field parent (for dependent lists)
7801 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
7802 // 5 : id category type
7803 // 6 : ids categories list separated by comma for category root
7804 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
7805
7806 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7807
7808 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7809 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7810 $keyList .= ', '.$parentField;
7811 }
7812 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7813 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7814 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7815 } else {
7816 $keyList = $InfoFieldList[2].' as rowid';
7817 }
7818 }
7819
7820 $filter_categorie = false;
7821 if (count($InfoFieldList) > 5) {
7822 if ($InfoFieldList[0] == 'categorie') {
7823 $filter_categorie = true;
7824 }
7825 }
7826
7827 if (!$filter_categorie) {
7828 $fields_label = explode('|', $InfoFieldList[1]);
7829 if (is_array($fields_label)) {
7830 $keyList .= ', ';
7831 $keyList .= implode(', ', $fields_label);
7832 }
7833
7834 $sqlwhere = '';
7835 $sql = "SELECT " . $keyList;
7836 $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7837 if (!empty($InfoFieldList[4])) {
7838 // can use SELECT request
7839 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7840 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7841 }
7842
7843 // current object id can be use into filter
7844 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7845 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
7846 } else {
7847 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7848 }
7849
7850 // We have to join on extrafield table
7851 if (strpos($InfoFieldList[4], 'extra') !== false) {
7852 $sql .= ' as main, ' . $this->db->prefix() . $InfoFieldList[0] . '_extrafields as extra';
7853 $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
7854 } else {
7855 $sqlwhere .= " WHERE " . $InfoFieldList[4];
7856 }
7857 } else {
7858 $sqlwhere .= ' WHERE 1=1';
7859 }
7860 // Some tables may have field, some other not. For the moment we disable it.
7861 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7862 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7863 }
7864 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
7865 // print $sql;
7866
7867 $sql .= $sqlwhere;
7868 dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
7869 $resql = $this->db->query($sql);
7870 if ($resql) {
7871 $num = $this->db->num_rows($resql);
7872 $i = 0;
7873
7874 $data = array();
7875
7876 while ($i < $num) {
7877 $labeltoshow = '';
7878 $obj = $this->db->fetch_object($resql);
7879
7880 $notrans = false;
7881 // Several field into label (eq table:code|libelle:rowid)
7882 $fields_label = explode('|', $InfoFieldList[1]);
7883 if (count($fields_label) > 1) {
7884 $notrans = true;
7885 foreach ($fields_label as $field_toshow) {
7886 $labeltoshow .= $obj->$field_toshow . ' ';
7887 }
7888 } else {
7889 $labeltoshow = $obj->{$InfoFieldList[1]};
7890 }
7891 $labeltoshow = dol_trunc($labeltoshow, 45);
7892
7893 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7894 foreach ($fields_label as $field_toshow) {
7895 $translabel = $langs->trans($obj->$field_toshow);
7896 if ($translabel != $obj->$field_toshow) {
7897 $labeltoshow = dol_trunc($translabel, 18) . ' ';
7898 } else {
7899 $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
7900 }
7901 }
7902
7903 $data[$obj->rowid] = $labeltoshow;
7904 } else {
7905 if (!$notrans) {
7906 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7907 if ($translabel != $obj->{$InfoFieldList[1]}) {
7908 $labeltoshow = dol_trunc($translabel, 18);
7909 } else {
7910 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
7911 }
7912 }
7913 if (empty($labeltoshow)) {
7914 $labeltoshow = '(not defined)';
7915 }
7916
7917 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
7918 $data[$obj->rowid] = $labeltoshow;
7919 }
7920
7921 if (!empty($InfoFieldList[3]) && $parentField) {
7922 $parent = $parentName . ':' . $obj->{$parentField};
7923 $isDependList = 1;
7924 }
7925
7926 $data[$obj->rowid] = $labeltoshow;
7927 }
7928
7929 $i++;
7930 }
7931 $this->db->free($resql);
7932
7933 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
7934 } else {
7935 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7936 }
7937 } else {
7938 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7939 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7940 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
7941 }
7942 }
7943 } elseif ($type == 'link') {
7944 // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
7945 // Filter can contains some ':' inside.
7946 $param_list = array_keys($param['options']);
7947 $param_list_array = explode(':', $param_list[0], 4);
7948
7949 $showempty = (($required && $default != '') ? 0 : 1);
7950
7951 if (!preg_match('/search_/', $keyprefix)) {
7952 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
7953 if (!empty($this->fields[$key]['picto'])) {
7954 $morecss .= ' widthcentpercentminusxx';
7955 } else {
7956 $morecss .= ' widthcentpercentminusx';
7957 }
7958 } else {
7959 if (!empty($this->fields[$key]['picto'])) {
7960 $morecss .= ' widthcentpercentminusx';
7961 }
7962 }
7963 }
7964 $objectfield = $this->element.($this->module ? '@'.$this->module : '').':'.$key.$keysuffix;
7965 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), '', $objectfield);
7966
7967 if (!empty($param_list_array[2])) { // If the entry into $fields is set, we must add a create button
7968 if ((!GETPOSTISSET('backtopage') || strpos(GETPOST('backtopage'), $_SERVER['PHP_SELF']) === 0) // // To avoid to open several times the 'Plus' button (we accept only one level)
7969 && empty($val['disabled']) && empty($nonewbutton)) { // and to avoid to show the button if the field is protected by a "disabled".
7970 list($class, $classfile) = explode(':', $param_list[0]);
7971 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
7972 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
7973 } else {
7974 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
7975 }
7976 $paramforthenewlink = '';
7977 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
7978 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOSTINT('id') : '');
7979 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
7980 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOSTINT('originid') : '');
7981 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
7982 // TODO Add JavaScript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
7983 $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>';
7984 }
7985 }
7986 } elseif ($type == 'password') {
7987 // If prefix is 'search_', field is used as a filter, we use a common text field.
7988 if ($keyprefix.$key.$keysuffix == 'pass_crypted') {
7989 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="pass" id="pass" value="" '.($moreparam ? $moreparam : '').'>';
7990 $out .= '<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7991 } else {
7992 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
7993 }
7994 } elseif ($type == 'array') {
7995 $newval = $val;
7996 $newval['type'] = 'varchar(256)';
7997
7998 $out = '';
7999 if (!empty($value)) {
8000 foreach ($value as $option) {
8001 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8002 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
8003 }
8004 }
8005 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8006
8007 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8008 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
8009
8010 if (!empty($conf->use_javascript_ajax)) {
8011 $out .= '
8012 <script nonce="'.getNonce().'">
8013 $(document).ready(function() {
8014 $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
8015 $("'.dol_escape_js($newInput).'").insertBefore(this);
8016 });
8017
8018 $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
8019 $(this).parent().remove();
8020 });
8021 });
8022 </script>';
8023 }
8024 }
8025 if (!empty($hidden)) {
8026 $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
8027 }
8028
8029 if ($isDependList == 1) {
8030 $out .= $this->getJSListDependancies('_common');
8031 }
8032 /* Add comments
8033 if ($type == 'date') $out.=' (YYYY-MM-DD)';
8034 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
8035 */
8036
8037 // Display error message for field
8038 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
8039 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
8040 }
8041
8042 return $out;
8043 }
8044
8058 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
8059 {
8060 global $conf, $langs, $form;
8061
8062 if (!is_object($form)) {
8063 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
8064 $form = new Form($this->db);
8065 }
8066
8067 //$label = empty($val['label']) ? '' : $val['label'];
8068 $type = empty($val['type']) ? '' : $val['type'];
8069 $size = empty($val['css']) ? '' : $val['css'];
8070 $reg = array();
8071
8072 // Convert var to be able to share same code than showOutputField of extrafields
8073 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8074 $type = 'varchar'; // convert varchar(xx) int varchar
8075 $size = $reg[1];
8076 } elseif (preg_match('/varchar/', $type)) {
8077 $type = 'varchar'; // convert varchar(xx) int varchar
8078 }
8079 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8080 if (empty($this->fields[$key]['multiinput'])) {
8081 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
8082 }
8083 }
8084 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8085 $type = 'link';
8086 }
8087
8088 $default = empty($val['default']) ? '' : $val['default'];
8089 $computed = empty($val['computed']) ? '' : $val['computed'];
8090 $unique = empty($val['unique']) ? '' : $val['unique'];
8091 $required = empty($val['required']) ? '' : $val['required'];
8092 $param = array();
8093 $param['options'] = array();
8094
8095 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8096 $param['options'] = $val['arrayofkeyval'];
8097 }
8098 if (preg_match('/^integer:([^:]*):([^:]*)/i', $val['type'], $reg)) { // ex: integer:User:user/class/user.class.php
8099 $type = 'link';
8100 $stringforoptions = $reg[1].':'.$reg[2];
8101 // Special case: Force addition of getnomurlparam1 to -1 for users
8102 if ($reg[1] == 'User') {
8103 $stringforoptions .= ':#getnomurlparam1=-1';
8104 }
8105 $param['options'] = array($stringforoptions => $stringforoptions);
8106 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8107 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8108 $type = 'sellist';
8109 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8110 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8111 $type = 'sellist';
8112 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8113 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8114 $type = 'sellist';
8115 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
8116 $param['options'] = array($reg[1] => 'N');
8117 $type = 'chkbxlst';
8118 }
8119
8120 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
8121 $list = (empty($val['list']) ? '' : $val['list']);
8122 $help = (empty($val['help']) ? '' : $val['help']);
8123 $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)
8124
8125 if ($hidden) {
8126 return '';
8127 }
8128
8129 // If field is a computed field, value must become result of compute
8130 if ($computed) {
8131 // Make the eval of compute string
8132 //var_dump($computed);
8133 $value = dol_eval($computed, 1, 0, '2');
8134 }
8135
8136 if (empty($morecss)) {
8137 if ($type == 'date') {
8138 $morecss = 'minwidth100imp';
8139 } elseif ($type == 'datetime' || $type == 'timestamp') {
8140 $morecss = 'minwidth200imp';
8141 } elseif (in_array($type, array('int', 'double', 'price'))) {
8142 $morecss = 'maxwidth75';
8143 } elseif ($type == 'url') {
8144 $morecss = 'minwidth400';
8145 } elseif ($type == 'boolean') {
8146 $morecss = '';
8147 } else {
8148 if (is_numeric($size) && round((float) $size) < 12) {
8149 $morecss = 'minwidth100';
8150 } elseif (is_numeric($size) && round((float) $size) <= 48) {
8151 $morecss = 'minwidth200';
8152 } else {
8153 $morecss = 'minwidth400';
8154 }
8155 }
8156 }
8157
8158 // Format output value differently according to properties of field
8159 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
8160 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.
8161 $value = $this->getNomUrl(1, '', 0, '', 1);
8162 }
8163 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
8164 $value = $this->getLibStatut(3);
8165 } elseif ($type == 'date') {
8166 if (!empty($value)) {
8167 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
8168 } else {
8169 $value = '';
8170 }
8171 } elseif ($type == 'datetime' || $type == 'timestamp') {
8172 if (!empty($value)) {
8173 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
8174 } else {
8175 $value = '';
8176 }
8177 } elseif ($type == 'duration') {
8178 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
8179 if (!is_null($value) && $value !== '') {
8180 $value = convertSecondToTime($value, 'allhourmin');
8181 }
8182 } elseif ($type == 'double' || $type == 'real') {
8183 if (!is_null($value) && $value !== '') {
8184 $value = price($value);
8185 }
8186 } elseif ($type == 'boolean') {
8187 $checked = '';
8188 if (!empty($value)) {
8189 $checked = ' checked ';
8190 }
8191 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
8192 $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
8193 } else {
8194 $value = yn($value ? 1 : 0);
8195 }
8196 } elseif ($type == 'mail' || $type == 'email') {
8197 $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
8198 } elseif ($type == 'url') {
8199 $value = dol_print_url($value, '_blank', 32, 1);
8200 } elseif ($type == 'phone') {
8201 $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
8202 } elseif ($type == 'ip') {
8203 $value = dol_print_ip($value, 0);
8204 } elseif ($type == 'price') {
8205 if (!is_null($value) && $value !== '') {
8206 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
8207 }
8208 } elseif ($type == 'select') {
8209 $value = isset($param['options'][(string) $value]) ? $param['options'][(string) $value] : '';
8210 if (strpos($value, "|") !== false) {
8211 $value = $langs->trans(explode('|', $value)[0]);
8212 } elseif (! is_numeric($value)) {
8213 $value = $langs->trans($value);
8214 }
8215 } elseif ($type == 'sellist') {
8216 $param_list = array_keys($param['options']);
8217 $InfoFieldList = explode(":", $param_list[0]);
8218
8219 $selectkey = "rowid";
8220 $keyList = 'rowid';
8221
8222 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8223 $selectkey = $InfoFieldList[2];
8224 $keyList = $InfoFieldList[2].' as rowid';
8225 }
8226
8227 $fields_label = explode('|', $InfoFieldList[1]);
8228 if (is_array($fields_label)) {
8229 $keyList .= ', ';
8230 $keyList .= implode(', ', $fields_label);
8231 }
8232
8233 $filter_categorie = false;
8234 if (count($InfoFieldList) > 5) {
8235 if ($InfoFieldList[0] == 'categorie') {
8236 $filter_categorie = true;
8237 }
8238 }
8239
8240 $sql = "SELECT ".$keyList;
8241 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
8242 if (strpos($InfoFieldList[4], 'extra') !== false) {
8243 $sql .= ' as main';
8244 }
8245 if ($selectkey == 'rowid' && empty($value)) {
8246 $sql .= " WHERE ".$selectkey." = 0";
8247 } elseif ($selectkey == 'rowid') {
8248 $sql .= " WHERE ".$selectkey." = ".((int) $value);
8249 } else {
8250 $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
8251 }
8252
8253 //$sql.= ' AND entity = '.$conf->entity;
8254
8255 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
8256 $resql = $this->db->query($sql);
8257 if ($resql) {
8258 if (!$filter_categorie) {
8259 $value = ''; // value was used, so now we reste it to use it to build final output
8260 $numrows = $this->db->num_rows($resql);
8261 if ($numrows) {
8262 $obj = $this->db->fetch_object($resql);
8263
8264 // Several field into label (eq table:code|libelle:rowid)
8265 $fields_label = explode('|', $InfoFieldList[1]);
8266
8267 if (is_array($fields_label) && count($fields_label) > 1) {
8268 foreach ($fields_label as $field_toshow) {
8269 $translabel = '';
8270 if (!empty($obj->$field_toshow)) {
8271 $translabel = $langs->trans($obj->$field_toshow);
8272 }
8273 if ($translabel != $field_toshow) {
8274 $value .= dol_trunc($translabel, 18) . ' ';
8275 } else {
8276 $value .= $obj->$field_toshow . ' ';
8277 }
8278 }
8279 } else {
8280 $translabel = '';
8281 if (!empty($obj->{$InfoFieldList[1]})) {
8282 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8283 }
8284 if ($translabel != $obj->{$InfoFieldList[1]}) {
8285 $value = dol_trunc($translabel, 18);
8286 } else {
8287 $value = $obj->{$InfoFieldList[1]};
8288 }
8289 }
8290 }
8291 } else {
8292 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
8293
8294 $toprint = array();
8295 $obj = $this->db->fetch_object($resql);
8296 $c = new Categorie($this->db);
8297 $c->fetch($obj->rowid);
8298 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
8299 foreach ($ways as $way) {
8300 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
8301 }
8302 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
8303 }
8304 } else {
8305 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8306 }
8307 } elseif ($type == 'radio') {
8308 $value = $param['options'][(string) $value];
8309 } elseif ($type == 'checkbox') {
8310 $value_arr = explode(',', (string) $value);
8311 $value = '';
8312 if (is_array($value_arr) && count($value_arr) > 0) {
8313 $toprint = array();
8314 foreach ($value_arr as $keyval => $valueval) {
8315 if (!empty($valueval)) {
8316 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param['options'][$valueval] . '</li>';
8317 }
8318 }
8319 if (!empty($toprint)) {
8320 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
8321 }
8322 }
8323 } elseif ($type == 'chkbxlst') {
8324 $value_arr = (isset($value) ? explode(',', $value) : array());
8325
8326 $param_list = array_keys($param['options']);
8327 $InfoFieldList = explode(":", $param_list[0]);
8328
8329 $selectkey = "rowid";
8330 $keyList = 'rowid';
8331
8332 if (count($InfoFieldList) >= 3) {
8333 $selectkey = $InfoFieldList[2];
8334 $keyList = $InfoFieldList[2].' as rowid';
8335 }
8336
8337 $fields_label = explode('|', $InfoFieldList[1]);
8338 if (is_array($fields_label)) {
8339 $keyList .= ', ';
8340 $keyList .= implode(', ', $fields_label);
8341 }
8342
8343 $filter_categorie = false;
8344 if (count($InfoFieldList) > 5) {
8345 if ($InfoFieldList[0] == 'categorie') {
8346 $filter_categorie = true;
8347 }
8348 }
8349
8350 $sql = "SELECT ".$keyList;
8351 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
8352 if (strpos($InfoFieldList[4], 'extra') !== false) {
8353 $sql .= ' as main';
8354 }
8355 // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
8356 // $sql.= ' AND entity = '.$conf->entity;
8357
8358 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
8359 $resql = $this->db->query($sql);
8360 if ($resql) {
8361 if (!$filter_categorie) {
8362 $value = ''; // value was used, so now we reset it to use it to build final output
8363 $toprint = array();
8364 while ($obj = $this->db->fetch_object($resql)) {
8365 // Several field into label (eq table:code|libelle:rowid)
8366 $fields_label = explode('|', $InfoFieldList[1]);
8367 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8368 if (is_array($fields_label) && count($fields_label) > 1) {
8369 foreach ($fields_label as $field_toshow) {
8370 $translabel = '';
8371 if (!empty($obj->$field_toshow)) {
8372 $translabel = $langs->trans($obj->$field_toshow);
8373 }
8374 if ($translabel != $field_toshow) {
8375 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
8376 } else {
8377 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
8378 }
8379 }
8380 } else {
8381 $translabel = '';
8382 if (!empty($obj->{$InfoFieldList[1]})) {
8383 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8384 }
8385 if ($translabel != $obj->{$InfoFieldList[1]}) {
8386 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
8387 } else {
8388 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
8389 }
8390 }
8391 }
8392 }
8393 } else {
8394 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
8395
8396 $toprint = array();
8397 while ($obj = $this->db->fetch_object($resql)) {
8398 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8399 $c = new Categorie($this->db);
8400 $c->fetch($obj->rowid);
8401 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
8402 foreach ($ways as $way) {
8403 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
8404 }
8405 }
8406 }
8407 }
8408 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
8409 } else {
8410 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8411 }
8412 } elseif ($type == 'link') {
8413 $out = '';
8414
8415 // only if something to display (perf)
8416 if ($value) {
8417 $param_list = array_keys($param['options']);
8418 // Example: $param_list='ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
8419 // Example: $param_list='ObjectClass:PathToClass:#getnomurlparam1=-1#getnomurlparam2=customer'
8420
8421 $InfoFieldList = explode(":", $param_list[0]);
8422
8423 $classname = $InfoFieldList[0];
8424 $classpath = $InfoFieldList[1];
8425
8426 // Set $getnomurlparam1 et getnomurlparam2
8427 $getnomurlparam = 3;
8428 $getnomurlparam2 = '';
8429 $regtmp = array();
8430 if (preg_match('/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8431 $getnomurlparam = $regtmp[1];
8432 }
8433 if (preg_match('/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8434 $getnomurlparam2 = $regtmp[1];
8435 }
8436
8437 if (!empty($classpath)) {
8438 dol_include_once($InfoFieldList[1]);
8439
8440 if ($classname && !class_exists($classname)) {
8441 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
8442 // TODO use newObjectByElement() introduce in V20 by PR #30036 for better errors management
8443 $element_prop = getElementProperties($classname);
8444 if ($element_prop) {
8445 $classname = $element_prop['classname'];
8446 }
8447 }
8448
8449
8450 if ($classname && class_exists($classname)) {
8451 $object = new $classname($this->db);
8452 if ($object->element === 'product') { // Special case for product because default valut of fetch are wrong
8453 $result = $object->fetch($value, '', '', '', 0, 1, 1);
8454 } else {
8455 $result = $object->fetch($value);
8456 }
8457 if ($result > 0) {
8458 if ($object->element === 'product') {
8459 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
8460 if (isset($val['get_name_url_params'])) {
8461 $get_name_url_params = explode(':', $val['get_name_url_params']);
8462 if (!empty($get_name_url_params)) {
8463 $param_num_max = count($get_name_url_param_arr) - 1;
8464 foreach ($get_name_url_params as $param_num => $param_value) {
8465 if ($param_num > $param_num_max) {
8466 break;
8467 }
8468 $get_name_url_param_arr[$param_num] = $param_value;
8469 }
8470 }
8471 }
8472
8476 $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]);
8477 } else {
8478 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
8479 }
8480 } else {
8481 $value = '';
8482 }
8483 }
8484 } else {
8485 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
8486 return 'Error bad setup of extrafield';
8487 }
8488 } else {
8489 $value = '';
8490 }
8491 } elseif ($type == 'password') {
8492 $value = '<span class="opacitymedium">'.$langs->trans("Encrypted").'</span>';
8493 //$value = preg_replace('/./i', '*', $value);
8494 } elseif ($type == 'array') {
8495 if (is_array($value)) {
8496 $value = implode('<br>', $value);
8497 } else {
8498 dol_syslog(__METHOD__.' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
8499 return 'Error unexpected result from code evaluation';
8500 }
8501 } else { // text|html|varchar
8502 $value = dol_htmlentitiesbr($value);
8503 }
8504
8505 //print $type.'-'.$size.'-'.$value;
8506 $out = $value;
8507
8508 return is_null($out) ? '' : $out;
8509 }
8510
8517 public function clearFieldError($fieldKey)
8518 {
8519 $this->error = '';
8520 unset($this->validateFieldsErrors[$fieldKey]);
8521 }
8522
8530 public function setFieldError($fieldKey, $msg = '')
8531 {
8532 global $langs;
8533 if (empty($msg)) {
8534 $msg = $langs->trans("UnknownError");
8535 }
8536
8537 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
8538 }
8539
8546 public function getFieldError($fieldKey)
8547 {
8548 if (!empty($this->validateFieldsErrors[$fieldKey])) {
8549 return $this->validateFieldsErrors[$fieldKey];
8550 }
8551 return '';
8552 }
8553
8562 public function validateField($fields, $fieldKey, $fieldValue)
8563 {
8564 global $langs;
8565
8566 if (!class_exists('Validate')) {
8567 require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
8568 }
8569
8570 $this->clearFieldError($fieldKey);
8571
8572 if (!isset($fields[$fieldKey]) || $fields[$fieldKey] === null) {
8573 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
8574 return false;
8575 }
8576
8577 $val = $fields[$fieldKey];
8578
8579 $param = array();
8580 $param['options'] = array();
8581 $type = $val['type'];
8582
8583 $required = false;
8584 if (isset($val['notnull']) && $val['notnull'] === 1) {
8585 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
8586 $required = true;
8587 }
8588
8589 $maxSize = 0;
8590 $minSize = 0;
8591
8592 //
8593 // PREPARE Elements
8594 //
8595 $reg = array();
8596
8597 // Convert var to be able to share same code than showOutputField of extrafields
8598 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8599 $type = 'varchar'; // convert varchar(xx) int varchar
8600 $maxSize = $reg[1];
8601 } elseif (preg_match('/varchar/', $type)) {
8602 $type = 'varchar'; // convert varchar(xx) int varchar
8603 }
8604
8605 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8606 $type = 'select';
8607 }
8608
8609 if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8610 $type = 'link';
8611 }
8612
8613 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8614 $param['options'] = $val['arrayofkeyval'];
8615 }
8616
8617 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8618 $type = 'link';
8619 $param['options'] = array($reg[1].':'.$reg[2] => $reg[1].':'.$reg[2]);
8620 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8621 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8622 $type = 'sellist';
8623 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8624 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8625 $type = 'sellist';
8626 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8627 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8628 $type = 'sellist';
8629 }
8630
8631 //
8632 // TEST Value
8633 //
8634
8635 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
8636 $validate = new Validate($this->db, $langs);
8637
8638
8639 // little trick : to perform tests with good performances sort tests by quick to low
8640
8641 //
8642 // COMMON TESTS
8643 //
8644
8645 // Required test and empty value
8646 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8647 $this->setFieldError($fieldKey, $validate->error);
8648 return false;
8649 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8650 // if no value sent and the field is not mandatory, no need to perform tests
8651 return true;
8652 }
8653
8654 // MAX Size test
8655 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8656 $this->setFieldError($fieldKey, $validate->error);
8657 return false;
8658 }
8659
8660 // MIN Size test
8661 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8662 $this->setFieldError($fieldKey, $validate->error);
8663 return false;
8664 }
8665
8666 //
8667 // TESTS for TYPE
8668 //
8669
8670 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
8671 if (!$validate->isTimestamp($fieldValue)) {
8672 $this->setFieldError($fieldKey, $validate->error);
8673 return false;
8674 } else {
8675 return true;
8676 }
8677 } elseif ($type == 'duration') {
8678 if (!$validate->isDuration($fieldValue)) {
8679 $this->setFieldError($fieldKey, $validate->error);
8680 return false;
8681 } else {
8682 return true;
8683 }
8684 } elseif (in_array($type, array('double', 'real', 'price'))) {
8685 // is numeric
8686 if (!$validate->isNumeric($fieldValue)) {
8687 $this->setFieldError($fieldKey, $validate->error);
8688 return false;
8689 } else {
8690 return true;
8691 }
8692 } elseif ($type == 'boolean') {
8693 if (!$validate->isBool($fieldValue)) {
8694 $this->setFieldError($fieldKey, $validate->error);
8695 return false;
8696 } else {
8697 return true;
8698 }
8699 } elseif ($type == 'mail') {
8700 if (!$validate->isEmail($fieldValue)) {
8701 $this->setFieldError($fieldKey, $validate->error);
8702 return false;
8703 }
8704 } elseif ($type == 'url') {
8705 if (!$validate->isUrl($fieldValue)) {
8706 $this->setFieldError($fieldKey, $validate->error);
8707 return false;
8708 } else {
8709 return true;
8710 }
8711 } elseif ($type == 'phone') {
8712 if (!$validate->isPhone($fieldValue)) {
8713 $this->setFieldError($fieldKey, $validate->error);
8714 return false;
8715 } else {
8716 return true;
8717 }
8718 } elseif ($type == 'select' || $type == 'radio') {
8719 if (!isset($param['options'][$fieldValue])) {
8720 $this->error = $langs->trans('RequireValidValue');
8721 return false;
8722 } else {
8723 return true;
8724 }
8725 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
8726 $param_list = array_keys($param['options']);
8727 $InfoFieldList = explode(":", $param_list[0]);
8728 $value_arr = explode(',', $fieldValue);
8729 $value_arr = array_map(array($this->db, 'escape'), $value_arr);
8730
8731 $selectkey = "rowid";
8732 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8733 $selectkey = $InfoFieldList[2];
8734 }
8735
8736 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8737 $this->setFieldError($fieldKey, $validate->error);
8738 return false;
8739 } else {
8740 return true;
8741 }
8742 } elseif ($type == 'link') {
8743 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
8744 $InfoFieldList = explode(":", $param_list[0]);
8745 $classname = $InfoFieldList[0];
8746 $classpath = $InfoFieldList[1];
8747 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8748 $lastIsFetchableError = $validate->error;
8749
8750 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
8751 if ($validate->isFetchableElement($fieldValue, $classname)) {
8752 return true;
8753 }
8754
8755 $this->setFieldError($fieldKey, $lastIsFetchableError);
8756 return false;
8757 } else {
8758 return true;
8759 }
8760 }
8761
8762 // if no test failed all is ok
8763 return true;
8764 }
8765
8779 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = '', $display_type = 'card')
8780 {
8781 global $db, $conf, $langs, $action, $form, $hookmanager;
8782
8783 if (!is_object($form)) {
8784 $form = new Form($db);
8785 }
8786 if (!is_object($extrafields)) {
8787 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
8788 return 'Bad parameter extrafields for showOptionals';
8789 }
8790 if (!is_array($extrafields->attributes[$this->table_element])) {
8791 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8792 }
8793
8794 $out = '';
8795
8796 $parameters = array('mode' => $mode, 'params' => $params, 'keysuffix' => $keysuffix, 'keyprefix' => $keyprefix, 'display_type' => $display_type);
8797 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
8798
8799 if (empty($reshook)) {
8800 if (is_array($extrafields->attributes[$this->table_element]) && array_key_exists('label', $extrafields->attributes[$this->table_element]) && is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) {
8801 $out .= "\n";
8802 $out .= '<!-- commonobject:showOptionals --> ';
8803 $out .= "\n";
8804
8805 $nbofextrafieldsshown = 0;
8806 $e = 0; // var to manage the modulo (odd/even)
8807
8808 $lastseparatorkeyfound = '';
8809 $extrafields_collapse_num = '';
8810 $extrafields_collapse_num_old = '';
8811 $i = 0;
8812
8813 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
8814 $i++;
8815
8816 // Show only the key field in params @phan-suppress-next-line PhanTypeArraySuspiciousNullable
8817 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
8818 continue;
8819 }
8820
8821 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
8822 $enabled = 1;
8823 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
8824 $enabled = (int) dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
8825 }
8826 if (empty($enabled)) {
8827 continue;
8828 }
8829
8830 $visibility = 1;
8831 if (isset($extrafields->attributes[$this->table_element]['list'][$key])) {
8832 $visibility = (int) dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
8833 }
8834
8835 $perms = 1;
8836 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
8837 $perms = (int) dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
8838 }
8839
8840 if (($mode == 'create') && !in_array(abs($visibility), array(1, 3))) {
8841 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
8842 } elseif (($mode == 'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
8843 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
8844 } elseif ($mode == 'view' && empty($visibility)) {
8845 continue;
8846 }
8847 if (empty($perms)) {
8848 continue;
8849 }
8850
8851 // Load language if required
8852 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
8853 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
8854 }
8855
8856 $colspan = 0;
8857 $value = null;
8858 if (is_array($params) && count($params) > 0 && $display_type == 'card') {
8859 if (array_key_exists('cols', $params)) {
8860 $colspan = $params['cols'];
8861 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
8862 $reg = array();
8863 if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
8864 $colspan = $reg[1];
8865 } else {
8866 $colspan = $params['colspan'];
8867 }
8868 }
8869 }
8870 $colspan = intval($colspan);
8871
8872 switch ($mode) {
8873 case "view":
8874 $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 formatted later
8875 break;
8876 case "create":
8877 case "edit":
8878 // We get the value of property found with GETPOST so it takes into account:
8879 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
8880 $check = 'alphanohtml';
8881 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
8882 $check = 'restricthtml';
8883 }
8884 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
8885 // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
8886 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
8887 if (is_array($getposttemp)) {
8888 // $getposttemp is an array but following code expects a comma separated string
8889 $value = implode(",", $getposttemp);
8890 } else {
8891 $value = $getposttemp;
8892 }
8893 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('int'))) {
8894 $value =( !empty($this->array_options["options_".$key]) || $this->array_options["options_".$key] === '0' ) ? $this->array_options["options_".$key] : '';
8895 } else {
8896 $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.
8897 }
8898 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
8899 break;
8900 }
8901
8902 $nbofextrafieldsshown++;
8903
8904 // Output value of the current field
8905 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
8906 $extrafields_collapse_num = $key;
8907 /*
8908 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
8909 if (!empty($extrafield_param) && is_array($extrafield_param)) {
8910 $extrafield_param_list = array_keys($extrafield_param['options']);
8911
8912 if (count($extrafield_param_list) > 0) {
8913 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
8914
8915 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
8916 //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
8917 $extrafields_collapse_num = $key;
8918 }
8919 }
8920 }
8921 */
8922
8923 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
8924 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
8925
8926 $lastseparatorkeyfound = $key;
8927 } else {
8928 $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
8929
8930 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
8931 $csstyle = '';
8932 if (is_array($params) && count($params) > 0) {
8933 if (array_key_exists('class', $params)) {
8934 $class .= $params['class'].' ';
8935 }
8936 if (array_key_exists('style', $params)) {
8937 $csstyle = $params['style'];
8938 }
8939 }
8940
8941 // add html5 elements
8942 $domData = ' data-element="extrafield"';
8943 $domData .= ' data-targetelement="'.$this->element.'"';
8944 $domData .= ' data-targetid="'.$this->id.'"';
8945
8946 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
8947 if ($display_type == 'card') {
8948 if (getDolGlobalString('MAIN_EXTRAFIELDS_USE_TWO_COLUMS') && ($e % 2) == 0) {
8949 $colspan = 0;
8950 }
8951
8952 if ($action == 'selectlines') {
8953 $colspan++;
8954 }
8955 }
8956
8957 // Convert date into timestamp format (value in memory must be a timestamp)
8958 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
8959 $datenotinstring = null;
8960 if (array_key_exists('options_'.$key, $this->array_options)) {
8961 $datenotinstring = $this->array_options['options_'.$key];
8962 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8963 $datenotinstring = $this->db->jdate($datenotinstring);
8964 }
8965 }
8966 $datekey = $keyprefix.'options_'.$key.$keysuffix;
8967 $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOSTINT($datekey.'month', 3), GETPOSTINT($datekey.'day', 3), GETPOSTINT($datekey.'year', 3)) : $datenotinstring;
8968 }
8969 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
8970 $datenotinstring = null;
8971 if (array_key_exists('options_'.$key, $this->array_options)) {
8972 $datenotinstring = $this->array_options['options_'.$key];
8973 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
8974 $datenotinstring = $this->db->jdate($datenotinstring);
8975 }
8976 }
8977 $timekey = $keyprefix.'options_'.$key.$keysuffix;
8978 $value = (GETPOSTISSET($timekey)) ? dol_mktime(GETPOSTINT($timekey.'hour', 3), GETPOSTINT($timekey.'min', 3), GETPOSTINT($timekey.'sec', 3), GETPOSTINT($timekey.'month', 3), GETPOSTINT($timekey.'day', 3), GETPOSTINT($timekey.'year', 3), 'tzuserrel') : $datenotinstring;
8979 }
8980 // Convert float submitted string into real php numeric (value in memory must be a php numeric)
8981 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
8982 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
8983 $value = price2num($value);
8984 } elseif (isset($this->array_options['options_'.$key])) {
8985 $value = $this->array_options['options_'.$key];
8986 }
8987 }
8988
8989 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
8990 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'radio', 'int', 'boolean'))) {
8991 if ($action == 'create' || $mode == 'create') {
8992 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
8993 }
8994 }
8995
8996 $labeltoshow = $langs->trans($label);
8997 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
8998 if ($display_type == 'card') {
8999 $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9000 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER') && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
9001 $out .= '<td></td>';
9002 }
9003 $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldcreate' : $params['tdclass']).' wordbreak';
9004 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'text') {
9005 $out .= ' tdtop';
9006 }
9007 } elseif ($display_type == 'line') {
9008 $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9009 $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
9010 }
9011 //$out .= "titlefield";
9012 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
9013 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
9014 $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
9015 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
9016 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9017 $out .= ' fieldrequired';
9018 }
9019 }
9020 $out .= '">';
9021 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
9022 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9023 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9024 } else {
9025 $out .= $labeltoshow;
9026 }
9027 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9028 $out .= '&nbsp;<span style="color: red">*</span>';
9029 }
9030 } else {
9031 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9032 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9033 } else {
9034 $out .= $labeltoshow;
9035 }
9036 }
9037
9038 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9039
9040 // Second column
9041 $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
9042 if ($display_type == 'card') {
9043 // 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
9044 $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key;
9045 $out .= '" '.($colspan ? ' colspan="'.$colspan.'"' : '');
9046 $out .= '>';
9047 } elseif ($display_type == 'line') {
9048 $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].'">';
9049 }
9050
9051 switch ($mode) {
9052 case "view":
9053 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
9054 break;
9055 case "create":
9056 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICOT', 'email,phone,ip,password'));
9057 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9058 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9059 }
9060 //$out .= '<!-- type = '.$extrafields->attributes[$this->table_element]['type'][$key].' -->';
9061 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
9062 break;
9063 case "edit":
9064 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICOT', 'email,phone,ip,password'));
9065 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9066 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9067 }
9068 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
9069 break;
9070 }
9071
9072 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9073 $out .= ($display_type == 'card' ? '</tr>'."\n" : '</div>');
9074 $e++;
9075 }
9076 }
9077 $out .= "\n";
9078 // Add code to manage list depending on others
9079 if (!empty($conf->use_javascript_ajax)) {
9080 $out .= $this->getJSListDependancies();
9081 }
9082
9083 $out .= '<!-- commonobject:showOptionals end --> '."\n";
9084
9085 if (empty($nbofextrafieldsshown)) {
9086 $out = '';
9087 }
9088 }
9089 }
9090
9091 $out .= $hookmanager->resPrint;
9092
9093 return $out;
9094 }
9095
9100 public function getJSListDependancies($type = '_extra')
9101 {
9102 $out = '
9103 <script nonce="'.getNonce().'">
9104 jQuery(document).ready(function() {
9105 function showOptions'.$type.'(child_list, parent_list, orig_select)
9106 {
9107 var val = $("select[name=\""+parent_list+"\"]").val();
9108 var parentVal = parent_list + ":" + val;
9109 if(typeof val == "string"){
9110 if(val != "") {
9111 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9112 $("select[name=\""+child_list+"\"] option[parent]").remove();
9113 $("select[name=\""+child_list+"\"]").append(options);
9114 } else {
9115 var options = orig_select.find("option[parent]").clone();
9116 $("select[name=\""+child_list+"\"] option[parent]").remove();
9117 $("select[name=\""+child_list+"\"]").append(options);
9118 }
9119 } else if(val > 0) {
9120 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9121 $("select[name=\""+child_list+"\"] option[parent]").remove();
9122 $("select[name=\""+child_list+"\"]").append(options);
9123 } else {
9124 var options = orig_select.find("option[parent]").clone();
9125 $("select[name=\""+child_list+"\"] option[parent]").remove();
9126 $("select[name=\""+child_list+"\"]").append(options);
9127 }
9128 }
9129 function setListDependencies'.$type.'() {
9130 jQuery("select option[parent]").parent().each(function() {
9131 var orig_select = {};
9132 var child_list = $(this).attr("name");
9133 orig_select[child_list] = $(this).clone();
9134 var parent = $(this).find("option[parent]:first").attr("parent");
9135 var infos = parent.split(":");
9136 var parent_list = infos[0];
9137
9138 //Hide daughters lists
9139 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9140 $("#"+child_list).hide();
9141 //Show mother lists
9142 } else if ($("#"+parent_list).val() != 0){
9143 $("#"+parent_list).show();
9144 }
9145 //Show the child list if the parent list value is selected
9146 $("select[name=\""+parent_list+"\"]").click(function() {
9147 if ($(this).val() != 0){
9148 $("#"+child_list).show()
9149 }
9150 });
9151
9152 //When we change parent list
9153 $("select[name=\""+parent_list+"\"]").change(function() {
9154 showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
9155 //Select the value 0 on child list after a change on the parent list
9156 $("#"+child_list).val(0).trigger("change");
9157 //Hide child lists if the parent value is set to 0
9158 if ($(this).val() == 0){
9159 $("#"+child_list).hide();
9160 }
9161 });
9162 });
9163 }
9164
9165 setListDependencies'.$type.'();
9166 });
9167 </script>'."\n";
9168 return $out;
9169 }
9170
9176 public function getRights()
9177 {
9178 global $user;
9179
9180 $module = empty($this->module) ? '' : $this->module;
9181 $element = $this->element;
9182
9183 if ($element == 'facturerec') {
9184 $element = 'facture';
9185 } elseif ($element == 'invoice_supplier_rec') {
9186 return !$user->hasRight('fournisseur', 'facture') ? null : $user->hasRight('fournisseur', 'facture');
9187 } elseif ($module && $user->hasRight($module, $element)) {
9188 // for modules built with ModuleBuilder
9189 return $user->hasRight($module, $element);
9190 }
9191
9192 return $user->rights->$element;
9193 }
9194
9207 public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
9208 {
9209 foreach ($tables as $table) {
9210 $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
9211
9212 if (!$dbs->query($sql)) {
9213 if ($ignoreerrors) {
9214 return true; // FIXME Not enough. If there is A-B on the kept thirdparty and B-C on the old one, we must get A-B-C after merge. Not A-B.
9215 }
9216 //$this->errors = $db->lasterror();
9217 return false;
9218 }
9219 }
9220
9221 return true;
9222 }
9223
9236 public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
9237 {
9238 foreach ($tables as $table) {
9239 $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
9240
9241 if (!$dbs->query($sql)) {
9242 if ($ignoreerrors) {
9243 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.
9244 }
9245 //$this->errors = $db->lasterror();
9246 return false;
9247 }
9248 }
9249
9250 return true;
9251 }
9252
9265 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9266 {
9267 global $conf;
9268
9269 $buyPrice = 0;
9270
9271 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && getDolGlobalInt('ForceBuyingPriceIfNull') > 0)) {
9272 // When ForceBuyingPriceIfNull is set
9273 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9274 } else {
9275 // Get cost price for margin calculation
9276 if (!empty($fk_product) && $fk_product > 0) {
9277 $result = 0;
9278 if (getDolGlobalString('MARGIN_TYPE') == 'costprice') {
9279 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
9280 $product = new Product($this->db);
9281 $result = $product->fetch($fk_product);
9282 if ($result <= 0) {
9283 $this->errors[] = 'ErrorProductIdDoesNotExists';
9284 return -1;
9285 }
9286 if ($product->cost_price > 0) {
9287 $buyPrice = $product->cost_price;
9288 } elseif ($product->pmp > 0) {
9289 $buyPrice = $product->pmp;
9290 }
9291 } elseif (getDolGlobalString('MARGIN_TYPE') == 'pmp') {
9292 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
9293 $product = new Product($this->db);
9294 $result = $product->fetch($fk_product);
9295 if ($result <= 0) {
9296 $this->errors[] = 'ErrorProductIdDoesNotExists';
9297 return -1;
9298 }
9299 if ($product->pmp > 0) {
9300 $buyPrice = $product->pmp;
9301 }
9302 }
9303
9304 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
9305 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
9306 $productFournisseur = new ProductFournisseur($this->db);
9307 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9308 $buyPrice = $productFournisseur->fourn_unitprice;
9309 } elseif ($result < 0) {
9310 $this->errors[] = $productFournisseur->error;
9311 return -2;
9312 }
9313 }
9314 }
9315 }
9316 return $buyPrice;
9317 }
9318
9326 public function getDataToShowPhoto($modulepart, $imagesize)
9327 {
9328 // See getDataToShowPhoto() implemented by Product for example.
9329 return array('dir' => '', 'file' => '', 'originalfile' => '', 'altfile' => '', 'email' => '', 'capture' => '');
9330 }
9331
9332
9333 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
9353 public function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $overwritetitle = 0, $usesharelink = 0, $cache = '', $addphotorefcss = 'photoref')
9354 {
9355 // phpcs:enable
9356 global $user, $langs;
9357
9358 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
9359 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
9360
9361 $sortfield = 'position_name';
9362 $sortorder = 'asc';
9363
9364 $dir = $sdir.'/';
9365 $pdir = '/';
9366
9367 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
9368 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
9369
9370 // For backward compatibility
9371 if ($modulepart == 'product') {
9372 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
9373 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9374 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9375 }
9376 }
9377 if ($modulepart == 'category') {
9378 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9379 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9380 }
9381
9382 // Defined relative dir to DOL_DATA_ROOT
9383 $relativedir = '';
9384 if ($dir) {
9385 $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
9386 $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
9387 $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
9388 }
9389
9390 $dirthumb = $dir.'thumbs/';
9391 $pdirthumb = $pdir.'thumbs/';
9392
9393 $return = '<!-- Photo -->'."\n";
9394 $nbphoto = 0;
9395
9396 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
9397
9398 /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatibility, we scan also old dirs
9399 {
9400 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
9401 $filearray=array_merge($filearray, $filearrayold);
9402 }*/
9403
9404 completeFileArrayWithDatabaseInfo($filearray, $relativedir);
9405
9406 if (count($filearray)) {
9407 if ($sortfield && $sortorder) {
9408 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
9409 }
9410
9411 foreach ($filearray as $key => $val) {
9412 $photo = '';
9413 $file = $val['name'];
9414
9415 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
9416 if (image_format_supported($file) >= 0) {
9417 $nbphoto++;
9418 $photo = $file;
9419 $viewfilename = $file;
9420
9421 if ($size == 1 || $size == 'small') { // Format vignette
9422 // Find name of thumb file
9423 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
9424 if (!dol_is_file($dirthumb.$photo_vignette)) {
9425 // The thumb does not exists, so we will use the original file
9426 $dirthumb = $dir;
9427 $pdirthumb = $pdir;
9428 $photo_vignette = basename($file);
9429 }
9430
9431 // Get filesize of original file
9432 $imgarray = dol_getImageSize($dir.$photo);
9433
9434 if ($nbbyrow > 0) {
9435 if ($nbphoto == 1) {
9436 $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
9437 }
9438
9439 if ($nbphoto % $nbbyrow == 1) {
9440 $return .= '<tr class="center valignmiddle" style="border: 1px">';
9441 }
9442 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
9443 } elseif ($nbbyrow < 0) {
9444 $return .= '<div class="inline-block">'."\n";
9445 }
9446
9447 $relativefile = preg_replace('/^\//', '', $pdir.$photo);
9448 if (empty($nolink)) {
9449 $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
9450 if ($urladvanced) {
9451 $return .= '<a href="'.$urladvanced.'">';
9452 } else {
9453 $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
9454 }
9455 }
9456
9457 // Show image (width height=$maxHeight)
9458 // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
9459 $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
9460 $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
9461 if ($overwritetitle) {
9462 if (is_numeric($overwritetitle)) {
9463 $alt = '';
9464 } else {
9465 $alt = $overwritetitle;
9466 }
9467 }
9468 if (empty($cache) && !empty($val['label'])) {
9469 // label is md5 of file
9470 // use it in url to say we want to cache this version of the file
9471 $cache = $val['label'];
9472 }
9473 if ($usesharelink) {
9474 if (array_key_exists('share', $val) && $val['share']) {
9475 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
9476 $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
9477 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'"'.($maxHeight ? ' height="'.$maxHeight.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).($cache ? '&cache='.urlencode($cache) : '').'" title="'.dol_escape_htmltag($alt).'">';
9478 } else {
9479 $return .= '<!-- Show original file -->';
9480 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).($cache ? '&cache='.urlencode($cache) : '').'" title="'.dol_escape_htmltag($alt).'">';
9481 }
9482 } else {
9483 $return .= '<!-- Show nophoto file (because file is not shared) -->';
9484 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
9485 }
9486 } else {
9487 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
9488 $return .= '<!-- Show thumb -->';
9489 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').' maxwidth150onsmartphone maxwidth200"'.($maxHeight ? ' height="'.$maxHeight.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.($cache ? '&cache='.urlencode($cache) : '').'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
9490 } else {
9491 $return .= '<!-- Show original file -->';
9492 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.($cache ? '&cache='.urlencode($cache) : '').'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
9493 }
9494 }
9495
9496 if (empty($nolink)) {
9497 $return .= '</a>';
9498 }
9499
9500 if ($showfilename) {
9501 $return .= '<br>'.$viewfilename;
9502 }
9503 if ($showaction) {
9504 $return .= '<br>';
9505 // If $photo_vignette set, we add a link to generate thumbs if file is an image and width or height higher than limits
9506 if ($photo_vignette && (image_format_supported($photo) > 0) && ((isset($imgarray['width']) && $imgarray['width'] > $maxWidth) || (isset($imgarray['width']) && $imgarray['width'] > $maxHeight))) {
9507 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=addthumb&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
9508 }
9509 // Special case for product
9510 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
9511 // Link to resize
9512 $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> &nbsp; ';
9513
9514 // Link to delete
9515 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
9516 $return .= img_delete().'</a>';
9517 }
9518 }
9519 $return .= "\n";
9520
9521 if ($nbbyrow > 0) {
9522 $return .= '</td>';
9523 if (($nbphoto % $nbbyrow) == 0) {
9524 $return .= '</tr>';
9525 }
9526 } elseif ($nbbyrow < 0) {
9527 $return .= '</div>'."\n";
9528 }
9529 }
9530
9531 if (empty($size)) { // Format origine
9532 $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
9533
9534 if ($showfilename) {
9535 $return .= '<br>'.$viewfilename;
9536 }
9537 if ($showaction) {
9538 // Special case for product
9539 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
9540 // Link to resize
9541 $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> &nbsp; ';
9542
9543 // Link to delete
9544 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
9545 $return .= img_delete().'</a>';
9546 }
9547 }
9548 }
9549
9550 // On continue ou on arrete de boucler ?
9551 if ($nbmax && $nbphoto >= $nbmax) {
9552 break;
9553 }
9554 }
9555 }
9556
9557 if ($size == 1 || $size == 'small') {
9558 if ($nbbyrow > 0) {
9559 // Ferme tableau
9560 while ($nbphoto % $nbbyrow) {
9561 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
9562 $nbphoto++;
9563 }
9564
9565 if ($nbphoto) {
9566 $return .= '</table>';
9567 }
9568 }
9569 }
9570 }
9571
9572 $this->nbphoto = $nbphoto;
9573
9574 return $return;
9575 }
9576
9577
9584 protected function isArray($info)
9585 {
9586 if (is_array($info)) {
9587 if (isset($info['type']) && $info['type'] == 'array') {
9588 return true;
9589 } else {
9590 return false;
9591 }
9592 }
9593 return false;
9594 }
9595
9602 public function isDate($info)
9603 {
9604 if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
9605 return true;
9606 }
9607 return false;
9608 }
9609
9616 public function isDuration($info)
9617 {
9618 if (is_array($info)) {
9619 if (isset($info['type']) && ($info['type'] == 'duration')) {
9620 return true;
9621 } else {
9622 return false;
9623 }
9624 } else {
9625 return false;
9626 }
9627 }
9628
9635 public function isInt($info)
9636 {
9637 if (is_array($info)) {
9638 if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
9639 return true;
9640 } else {
9641 return false;
9642 }
9643 } else {
9644 return false;
9645 }
9646 }
9647
9654 public function isFloat($info)
9655 {
9656 if (is_array($info)) {
9657 if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
9658 return true;
9659 } else {
9660 return false;
9661 }
9662 }
9663 return false;
9664 }
9665
9672 public function isText($info)
9673 {
9674 if (is_array($info)) {
9675 if (isset($info['type']) && $info['type'] == 'text') {
9676 return true;
9677 } else {
9678 return false;
9679 }
9680 }
9681 return false;
9682 }
9683
9690 protected function canBeNull($info)
9691 {
9692 if (is_array($info)) {
9693 if (array_key_exists('notnull', $info) && $info['notnull'] != '1') {
9694 return true;
9695 } else {
9696 return false;
9697 }
9698 }
9699 return true;
9700 }
9701
9708 protected function isForcedToNullIfZero($info)
9709 {
9710 if (is_array($info)) {
9711 if (array_key_exists('notnull', $info) && $info['notnull'] == '-1') {
9712 return true;
9713 } else {
9714 return false;
9715 }
9716 }
9717 return false;
9718 }
9719
9726 protected function isIndex($info)
9727 {
9728 if (is_array($info)) {
9729 if (array_key_exists('index', $info) && $info['index'] == true) {
9730 return true;
9731 } else {
9732 return false;
9733 }
9734 }
9735 return false;
9736 }
9737
9738
9747 protected function setSaveQuery()
9748 {
9749 global $conf;
9750
9751 $queryarray = array();
9752 foreach ($this->fields as $field => $info) { // Loop on definition of fields
9753 // Depending on field type ('datetime', ...)
9754 if ($this->isDate($info)) {
9755 if (empty($this->{$field})) {
9756 $queryarray[$field] = null;
9757 } else {
9758 $queryarray[$field] = $this->db->idate($this->{$field});
9759 }
9760 } elseif ($this->isDuration($info)) {
9761 // $this->{$field} may be null, '', 0, '0', 123, '123'
9762 if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
9763 if (!isset($this->{$field})) {
9764 if (!empty($info['default'])) {
9765 $queryarray[$field] = $info['default'];
9766 } else {
9767 $queryarray[$field] = 0;
9768 }
9769 } else {
9770 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9771 }
9772 } else {
9773 $queryarray[$field] = null;
9774 }
9775 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9776 if ($field == 'entity' && is_null($this->{$field})) {
9777 $queryarray[$field] = ((int) $conf->entity);
9778 } else {
9779 // $this->{$field} may be null, '', 0, '0', 123, '123'
9780 if ((isset($this->{$field}) && ((string) $this->{$field}) != '') || !empty($info['notnull'])) {
9781 if (!isset($this->{$field})) {
9782 $queryarray[$field] = 0;
9783 } elseif ($this->isInt($info)) {
9784 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9785 } elseif ($this->isFloat($info)) {
9786 $queryarray[$field] = (float) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9787 }
9788 } else {
9789 $queryarray[$field] = null;
9790 }
9791 }
9792 } else {
9793 // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
9794 // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
9795 $queryarray[$field] = $this->{$field};
9796 }
9797
9798 if (array_key_exists('type', $info) && $info['type'] == 'timestamp' && empty($queryarray[$field])) {
9799 unset($queryarray[$field]);
9800 }
9801 if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
9802 $queryarray[$field] = null; // May force 0 to null
9803 }
9804 }
9805
9806 return $queryarray;
9807 }
9808
9815 public function setVarsFromFetchObj(&$obj)
9816 {
9817 global $db;
9818
9819 foreach ($this->fields as $field => $info) {
9820 if ($this->isDate($info)) {
9821 if (!isset($obj->$field) || is_null($obj->$field) || $obj->$field === '' || $obj->$field === '0000-00-00 00:00:00' || $obj->$field === '1000-01-01 00:00:00') {
9822 $this->$field = '';
9823 } else {
9824 $this->$field = $db->jdate($obj->$field);
9825 }
9826 } elseif ($this->isInt($info)) {
9827 if ($field == 'rowid') {
9828 $this->id = (int) $obj->$field;
9829 } else {
9830 if ($this->isForcedToNullIfZero($info)) {
9831 if (empty($obj->$field)) {
9832 $this->$field = null;
9833 } else {
9834 $this->$field = (int) $obj->$field;
9835 }
9836 } else {
9837 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
9838 $this->$field = (int) $obj->$field;
9839 } else {
9840 $this->$field = null;
9841 }
9842 }
9843 }
9844 } elseif ($this->isFloat($info)) {
9845 if ($this->isForcedToNullIfZero($info)) {
9846 if (empty($obj->$field)) {
9847 $this->$field = null;
9848 } else {
9849 $this->$field = (float) $obj->$field;
9850 }
9851 } else {
9852 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
9853 $this->$field = (float) $obj->$field;
9854 } else {
9855 $this->$field = null;
9856 }
9857 }
9858 } else {
9859 $this->$field = isset($obj->$field) ? $obj->$field : null;
9860 }
9861 }
9862
9863 // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
9864 if (!isset($this->fields['ref']) && isset($this->id)) {
9865 $this->ref = (string) $this->id;
9866 }
9867 }
9868
9873 public function emtpyObjectVars()
9874 {
9875 foreach ($this->fields as $field => $arr) {
9876 $this->$field = null;
9877 }
9878 }
9879
9887 public function getFieldList($alias = '', $excludefields = array())
9888 {
9889 $keys = array_keys($this->fields);
9890 if (!empty($alias)) {
9891 $keys_with_alias = array();
9892 foreach ($keys as $fieldname) {
9893 if (!empty($excludefields)) {
9894 if (in_array($fieldname, $excludefields)) { // The field is excluded and must not be in output
9895 continue;
9896 }
9897 }
9898 $keys_with_alias[] = $alias . '.' . $fieldname;
9899 }
9900 return implode(',', $keys_with_alias);
9901 } else {
9902 return implode(',', $keys);
9903 }
9904 }
9905
9913 protected function quote($value, $fieldsentry)
9914 {
9915 if (is_null($value)) {
9916 return 'NULL';
9917 } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
9918 return price2num((string) $value);
9919 } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
9920 return (int) $value;
9921 } elseif ($fieldsentry['type'] == 'boolean') {
9922 if ($value) {
9923 return 'true';
9924 } else {
9925 return 'false';
9926 }
9927 } else {
9928 return "'".$this->db->escape($value)."'";
9929 }
9930 }
9931
9932
9940 public function createCommon(User $user, $notrigger = 0)
9941 {
9942 global $langs;
9943
9944 dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
9945
9946 $error = 0;
9947
9948 $now = dol_now();
9949
9950 $fieldvalues = $this->setSaveQuery();
9951
9952 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
9953
9954 if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
9955 $fieldvalues['date_creation'] = $this->db->idate($now);
9956 }
9957 if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
9958 $fieldvalues['fk_user_creat'] = $user->id;
9959 $this->fk_user_creat = $user->id;
9960 }
9961 if (array_key_exists('user_creation_id', $fieldvalues) && !($fieldvalues['user_creation_id'] > 0)) {
9962 $fieldvalues['user_creation_id'] = $user->id;
9963 $this->user_creation_id = $user->id;
9964 }
9965 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass')) {
9966 // @phan-suppress-next-line PhanUndeclaredProperty
9967 $fieldvalues['pass_crypted'] = dol_hash($this->pass);
9968 }
9969 if (array_key_exists('ref', $fieldvalues)) {
9970 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
9971 }
9972
9973 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
9974
9975 $keys = array();
9976 $values = array(); // Array to store string forged for SQL syntax
9977 foreach ($fieldvalues as $k => $v) {
9978 $keys[$k] = $k;
9979 $value = $this->fields[$k];
9980 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
9981 $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
9982 }
9983
9984 // Clean and check mandatory
9985 foreach ($keys as $key) {
9986 if (!isset($this->fields[$key])) {
9987 continue;
9988 }
9989 $key_fields = $this->fields[$key];
9990
9991 // If field is an implicit foreign key field (so type = 'integer:...')
9992 if (preg_match('/^integer:/i', $key_fields['type']) && $values[$key] == '-1') {
9993 $values[$key] = '';
9994 }
9995 if (!empty($key_fields['foreignkey']) && $values[$key] == '-1') {
9996 $values[$key] = '';
9997 }
9998
9999 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && (!isset($key_fields['default']) || is_null($key_fields['default']))) {
10000 $error++;
10001 $langs->load("errors");
10002 dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
10003 $this->errors[] = $langs->trans("ErrorFieldRequired", isset($key_fields['label']) ? $key_fields['label'] : $key);
10004 }
10005
10006 // If value is null and there is a default value for field @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10007 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($key_fields['default'])) {
10008 $values[$key] = $this->quote($key_fields['default'], $key_fields);
10009 }
10010
10011 // If field is an implicit foreign key field (so type = 'integer:...')
10012 if (isset($key_fields['type']) && preg_match('/^integer:/i', $key_fields['type']) && empty($values[$key])) {
10013 if (isset($key_fields['default'])) {
10014 $values[$key] = ((int) $key_fields['default']);
10015 } else {
10016 $values[$key] = 'null';
10017 }
10018 }
10019 if (!empty($key_fields['foreignkey']) && empty($values[$key])) {
10020 $values[$key] = 'null';
10021 }
10022 }
10023
10024 if ($error) {
10025 return -1;
10026 }
10027
10028 $this->db->begin();
10029
10030 if (!$error) {
10031 $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
10032 $sql .= " (".implode(", ", $keys).')';
10033 $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
10034
10035 $res = $this->db->query($sql);
10036 if (!$res) {
10037 $error++;
10038 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
10039 $this->errors[] = "ErrorRefAlreadyExists";
10040 } else {
10041 $this->errors[] = $this->db->lasterror();
10042 }
10043 }
10044 }
10045
10046 if (!$error) {
10047 $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10048 }
10049
10050 // If we have a field ref with a default value of (PROV)
10051 if (!$error) {
10052 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10053 if (array_key_exists('ref', $this->fields) && array_key_exists('notnull', $this->fields['ref']) && $this->fields['ref']['notnull'] > 0 && array_key_exists('default', $this->fields['ref']) && $this->fields['ref']['default'] == '(PROV)') {
10054 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
10055 $resqlupdate = $this->db->query($sql);
10056
10057 if ($resqlupdate === false) {
10058 $error++;
10059 $this->errors[] = $this->db->lasterror();
10060 } else {
10061 $this->ref = '(PROV'.$this->id.')';
10062 }
10063 }
10064 }
10065
10066 // Create extrafields
10067 if (!$error) {
10068 $result = $this->insertExtraFields();
10069 if ($result < 0) {
10070 $error++;
10071 }
10072 }
10073
10074 // Create lines
10075 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
10076 foreach ($this->lines as $line) {
10077 $keyforparent = $this->fk_element;
10078 $line->$keyforparent = $this->id;
10079
10080 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
10081 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
10082 if (!is_object($line)) {
10083 $line = (object) $line;
10084 }
10085
10086 $result = 0;
10087 if (method_exists($line, 'insert')) {
10088 $result = $line->insert($user, 1);
10089 } elseif (method_exists($line, 'create')) {
10090 $result = $line->create($user, 1);
10091 }
10092 if ($result < 0) {
10093 $this->error = $line->error;
10094 $this->db->rollback();
10095 return -1;
10096 }
10097 }
10098 }
10099
10100 // Triggers
10101 if (!$error && !$notrigger) {
10102 // Call triggers
10103 $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
10104 if ($result < 0) {
10105 $error++;
10106 }
10107 // End call triggers
10108 }
10109
10110 // Commit or rollback
10111 if ($error) {
10112 $this->db->rollback();
10113 return -1;
10114 } else {
10115 $this->db->commit();
10116 return $this->id;
10117 }
10118 }
10119
10120
10130 public function fetchCommon($id, $ref = null, $morewhere = '', $noextrafields = 0)
10131 {
10132 if (empty($id) && empty($ref) && empty($morewhere)) {
10133 return -1;
10134 }
10135
10136 $fieldlist = $this->getFieldList('t');
10137 if (empty($fieldlist)) {
10138 return 0;
10139 }
10140
10141 $sql = "SELECT ".$fieldlist;
10142 $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
10143
10144 if (!empty($id)) {
10145 $sql .= ' WHERE t.rowid = '.((int) $id);
10146 } elseif (!empty($ref)) {
10147 $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
10148 } else {
10149 $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
10150 }
10151 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10152 $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
10153 }
10154 if ($morewhere) {
10155 $sql .= $morewhere;
10156 }
10157 $sql .= ' LIMIT 1'; // This is a fetch, to be certain to get only one record
10158
10159 $res = $this->db->query($sql);
10160 if ($res) {
10161 $obj = $this->db->fetch_object($res);
10162 if ($obj) {
10163 $this->setVarsFromFetchObj($obj);
10164
10165 // Retrieve all extrafield
10166 // fetch optionals attributes and labels
10167 if (empty($noextrafields)) {
10168 $result = $this->fetch_optionals();
10169 if ($result < 0) {
10170 $this->error = $this->db->lasterror();
10171 $this->errors[] = $this->error;
10172 return -4;
10173 }
10174 }
10175
10176 return $this->id;
10177 } else {
10178 return 0;
10179 }
10180 } else {
10181 $this->error = $this->db->lasterror();
10182 $this->errors[] = $this->error;
10183 return -1;
10184 }
10185 }
10186
10194 public function fetchLinesCommon($morewhere = '', $noextrafields = 0)
10195 {
10196 $objectlineclassname = get_class($this).'Line';
10197 if (!class_exists($objectlineclassname)) {
10198 $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
10199 return -1;
10200 }
10201
10202 $objectline = new $objectlineclassname($this->db);
10203 '@phan-var-force CommonObjectLine $objectline';
10204
10205 $sql = "SELECT ".$objectline->getFieldList('l');
10206 $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
10207 $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
10208 if ($morewhere) {
10209 $sql .= $morewhere;
10210 }
10211 if (isset($objectline->fields['position'])) {
10212 $sql .= $this->db->order('position', 'ASC');
10213 }
10214
10215 $resql = $this->db->query($sql);
10216 if ($resql) {
10217 $num_rows = $this->db->num_rows($resql);
10218 $i = 0;
10219 while ($i < $num_rows) {
10220 $obj = $this->db->fetch_object($resql);
10221 if ($obj) {
10222 $newline = new $objectlineclassname($this->db);
10223 '@phan-var-force CommonObjectLine $newline';
10224 $newline->setVarsFromFetchObj($obj);
10225
10226 // Note: extrafields load of line not yet supported
10227 /*
10228 if (empty($noextrafields)) {
10229 // Load extrafields of line
10230 }*/
10231
10232 $this->lines[] = $newline;
10233 }
10234 $i++;
10235 }
10236
10237 return 1;
10238 } else {
10239 $this->error = $this->db->lasterror();
10240 $this->errors[] = $this->error;
10241 return -1;
10242 }
10243 }
10244
10252 public function updateCommon(User $user, $notrigger = 0)
10253 {
10254 dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
10255
10256 $error = 0;
10257
10258 $now = dol_now();
10259
10260 // $this->oldcopy should have been set by the caller of update
10261 //if (empty($this->oldcopy)) {
10262 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
10263 // $this->oldcopy = dol_clone($this, 2);
10264 //}
10265
10266 $fieldvalues = $this->setSaveQuery();
10267
10268 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
10269
10270 if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
10271 $fieldvalues['date_modification'] = $this->db->idate($now);
10272 }
10273 if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
10274 $fieldvalues['fk_user_modif'] = $user->id;
10275 }
10276 if (array_key_exists('user_modification_id', $fieldvalues) && !($fieldvalues['user_modification_id'] > 0)) {
10277 $fieldvalues['user_modification_id'] = $user->id;
10278 }
10279 if (array_key_exists('ref', $fieldvalues)) {
10280 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
10281 }
10282
10283 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
10284
10285 // Add quotes and escape on fields with type string
10286 $keys = array();
10287 $values = array();
10288 $tmp = array();
10289 foreach ($fieldvalues as $k => $v) {
10290 $keys[$k] = $k;
10291 $value = $this->fields[$k];
10292 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10293 $values[$k] = $this->quote($v, $value);
10294 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10295 $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
10296 }
10297
10298 // Clean and check mandatory fields
10299 foreach ($keys as $key) {
10300 if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
10301 $values[$key] = ''; // This is an implicit foreign key field
10302 }
10303 if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
10304 $values[$key] = ''; // This is an explicit foreign key field
10305 }
10306
10307 //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
10308 /*
10309 if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
10310 {
10311 $error++;
10312 $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
10313 }*/
10314 }
10315
10316 $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
10317
10318 $this->db->begin();
10319
10320 if (!$error) {
10321 $res = $this->db->query($sql);
10322 if (!$res) {
10323 $error++;
10324 $this->errors[] = $this->db->lasterror();
10325 }
10326 }
10327
10328 // Update extrafield
10329 if (!$error) {
10330 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
10331 if ($result < 0) {
10332 $error++;
10333 }
10334 }
10335
10336 // Triggers
10337 if (!$error && !$notrigger) {
10338 // Call triggers
10339 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
10340 if ($result < 0) {
10341 $error++;
10342 } //Do also here what you must do to rollback action if trigger fail
10343 // End call triggers
10344 }
10345
10346 // Commit or rollback
10347 if ($error) {
10348 $this->db->rollback();
10349 return -1;
10350 } else {
10351 $this->db->commit();
10352 return $this->id;
10353 }
10354 }
10355
10364 public function deleteCommon(User $user, $notrigger = 0, $forcechilddeletion = 0)
10365 {
10366 dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
10367
10368 $error = 0;
10369
10370 $this->db->begin();
10371
10372 if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
10373 foreach ($this->childtables as $table) {
10374 $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
10375 $resql = $this->db->query($sql);
10376 if (!$resql) {
10377 $this->error = $this->db->lasterror();
10378 $this->errors[] = $this->error;
10379 $this->db->rollback();
10380 return -1;
10381 }
10382 }
10383 } elseif (!empty($this->childtables)) { // If object has children linked with a foreign key field, we check all child tables.
10384 $objectisused = $this->isObjectUsed($this->id);
10385 if (!empty($objectisused)) {
10386 dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10387 $this->error = 'ErrorRecordHasChildren';
10388 $this->errors[] = $this->error;
10389 $this->db->rollback();
10390 return 0;
10391 }
10392 }
10393
10394 // Delete cascade first
10395 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10396 foreach ($this->childtablesoncascade as $tabletodelete) {
10397 $deleteFromObject = explode(':', $tabletodelete, 4);
10398 if (count($deleteFromObject) >= 2) {
10399 $className = str_replace('@', '', $deleteFromObject[0]);
10400 $filePath = $deleteFromObject[1];
10401 $columnName = $deleteFromObject[2];
10402 $filter = '';
10403 if (!empty($deleteFromObject[3])) {
10404 $filter = $deleteFromObject[3];
10405 }
10406 if (dol_include_once($filePath)) {
10407 $childObject = new $className($this->db);
10408 if (method_exists($childObject, 'deleteByParentField')) {
10409 '@phan-var-force CommonObject $childObject';
10410 $result = $childObject->deleteByParentField($this->id, $columnName, $filter);
10411 if ($result < 0) {
10412 $error++;
10413 $this->errors[] = $childObject->error;
10414 break;
10415 }
10416 } else {
10417 $error++;
10418 $this->errors[] = "You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
10419 break;
10420 }
10421 } else {
10422 $error++;
10423 $this->errors[] = 'Cannot include child class file '.$filePath;
10424 break;
10425 }
10426 } else {
10427 // Delete record in child table
10428 $sql = "DELETE FROM ".$this->db->prefix().$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
10429
10430 $resql = $this->db->query($sql);
10431 if (!$resql) {
10432 $error++;
10433 $this->error = $this->db->lasterror();
10434 $this->errors[] = $this->error;
10435 break;
10436 }
10437 }
10438 }
10439 }
10440
10441 if (!$error) {
10442 if (!$notrigger) {
10443 // Call triggers
10444 $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
10445 if ($result < 0) {
10446 $error++;
10447 } // Do also here what you must do to rollback action if trigger fail
10448 // End call triggers
10449 }
10450 }
10451
10452 // Delete llx_ecm_files
10453 if (!$error) {
10454 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
10455 if (!$res) {
10456 $error++;
10457 }
10458 }
10459
10460 // Delete linked object
10461 $res = $this->deleteObjectLinked();
10462 if ($res < 0) {
10463 $error++;
10464 }
10465
10466 if (!$error && !empty($this->isextrafieldmanaged)) {
10467 $result = $this->deleteExtraFields();
10468 if ($result < 0) {
10469 $error++;
10470 }
10471 }
10472
10473 if (!$error) {
10474 $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
10475
10476 $resql = $this->db->query($sql);
10477 if (!$resql) {
10478 $error++;
10479 $this->errors[] = $this->db->lasterror();
10480 }
10481 }
10482
10483 // Commit or rollback
10484 if ($error) {
10485 $this->db->rollback();
10486 return -1;
10487 } else {
10488 $this->db->commit();
10489 return 1;
10490 }
10491 }
10492
10504 public function deleteByParentField($parentId = 0, $parentField = '', $filter = '', $filtermode = "AND")
10505 {
10506 global $user;
10507
10508 $error = 0;
10509 $deleted = 0;
10510
10511 if (!empty($parentId) && !empty($parentField)) {
10512 $this->db->begin();
10513
10514 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
10515 $sql .= " WHERE ".$this->db->sanitize($parentField)." = ".(int) $parentId;
10516
10517 // Manage filter
10518 $errormessage = '';
10519 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
10520 if ($errormessage) {
10521 $this->errors[] = $errormessage;
10522 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
10523 return -1;
10524 }
10525
10526 $resql = $this->db->query($sql);
10527 if (!$resql) {
10528 $this->errors[] = $this->db->lasterror();
10529 $error++;
10530 } else {
10531 while ($obj = $this->db->fetch_object($resql)) {
10532 $result = $this->fetch($obj->rowid); // @phpstan-ignore-line
10533 if ($result < 0) {
10534 $error++;
10535 $this->errors[] = $this->error;
10536 } else {
10537 $result = $this->delete($user); // @phpstan-ignore-line
10538 if ($result < 0) {
10539 $error++;
10540 $this->errors[] = $this->error;
10541 } else {
10542 $deleted++;
10543 }
10544 }
10545 }
10546 }
10547
10548 if (empty($error)) {
10549 $this->db->commit();
10550 return $deleted;
10551 } else {
10552 $this->error = implode(', ', $this->errors);
10553 $this->db->rollback();
10554 return $error * -1;
10555 }
10556 }
10557
10558 return $deleted;
10559 }
10560
10569 public function deleteLineCommon(User $user, $idline, $notrigger = 0)
10570 {
10571 $error = 0;
10572
10573 $tmpforobjectclass = get_class($this);
10574 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
10575
10576 $this->db->begin();
10577
10578 // Call trigger
10579 $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
10580 if ($result < 0) {
10581 $error++;
10582 }
10583 // End call triggers
10584
10585 if (empty($error)) {
10586 $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
10587 $sql .= " WHERE rowid = ".((int) $idline);
10588
10589 $resql = $this->db->query($sql);
10590 if (!$resql) {
10591 $this->error = "Error ".$this->db->lasterror();
10592 $error++;
10593 }
10594 }
10595
10596 if (empty($error)) {
10597 // Remove extrafields
10598 $tmpobjectline = new $tmpforobjectlineclass($this->db);
10599 '@phan-var-force CommonObjectLine $tmpobjectline';
10600 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
10601 $tmpobjectline->id = $idline;
10602 $result = $tmpobjectline->deleteExtraFields();
10603 if ($result < 0) {
10604 $error++;
10605 $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
10606 }
10607 }
10608 }
10609
10610 if (empty($error)) {
10611 $this->db->commit();
10612 return 1;
10613 } else {
10614 dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
10615 $this->db->rollback();
10616 return -1;
10617 }
10618 }
10619
10620
10630 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
10631 {
10632 $error = 0;
10633
10634 $this->db->begin();
10635
10636 $statusfield = 'status';
10637 if (in_array($this->element, array('don', 'donation', 'shipping'))) {
10638 $statusfield = 'fk_statut';
10639 }
10640
10641 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
10642 $sql .= " SET ".$statusfield." = ".((int) $status);
10643 $sql .= " WHERE rowid = ".((int) $this->id);
10644
10645 if ($this->db->query($sql)) {
10646 if (!$error) {
10647 $this->oldcopy = clone $this;
10648 }
10649
10650 if (!$error && !$notrigger) {
10651 // Call trigger
10652 $result = $this->call_trigger($triggercode, $user);
10653 if ($result < 0) {
10654 $error++;
10655 }
10656 }
10657
10658 if (!$error) {
10659 $this->status = $status;
10660 if (property_exists($this, 'statut')) { // For backward compatibility
10661 $this->statut = $status;
10662 }
10663 $this->db->commit();
10664 return 1;
10665 } else {
10666 $this->db->rollback();
10667 return -1;
10668 }
10669 } else {
10670 $this->error = $this->db->error();
10671 $this->db->rollback();
10672 return -1;
10673 }
10674 }
10675
10685 public function setSignedStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
10686 {
10687 $error = 0;
10688
10689 $this->db->begin();
10690
10691 $statusfield = 'signed_status';
10692
10693 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
10694 $sql .= " SET ".$statusfield." = ".((int) $status);
10695 $sql .= " WHERE rowid = ".((int) $this->id);
10696
10697 if ($this->db->query($sql)) {
10698 if (!$error) {
10699 $this->oldcopy = clone $this;
10700 }
10701
10702 if (!$error && !$notrigger) {
10703 // Call trigger
10704 $result = $this->call_trigger($triggercode, $user);
10705 if ($result < 0) {
10706 $error++;
10707 }
10708 }
10709
10710 if (!$error) {
10711 $this->status = $status;
10712 $this->db->commit();
10713 return 1;
10714 } else {
10715 $this->db->rollback();
10716 return -1;
10717 }
10718 } else {
10719 $this->error = $this->db->error();
10720 $this->db->rollback();
10721 return -1;
10722 }
10723 }
10724
10725
10732 public function initAsSpecimenCommon()
10733 {
10734 global $user;
10735
10736 $this->id = 0;
10737 $this->specimen = 1;
10738 $fields = array(
10739 'label' => 'This is label',
10740 'ref' => 'ABCD1234',
10741 'description' => 'This is a description',
10742 'qty' => 123.12,
10743 'note_public' => 'Public note',
10744 'note_private' => 'Private note',
10745 'date_creation' => (dol_now() - 3600 * 48),
10746 'date_modification' => (dol_now() - 3600 * 24),
10747 'fk_user_creat' => $user->id,
10748 'fk_user_modif' => $user->id,
10749 'date' => dol_now(),
10750 );
10751 foreach ($fields as $key => $value) {
10752 if (array_key_exists($key, $this->fields)) {
10753 $this->{$key} = $value; // @phpstan-ignore-line
10754 }
10755 }
10756
10757 // Force values to default values when known
10758 if (property_exists($this, 'fields')) {
10759 foreach ($this->fields as $key => $value) {
10760 // If fields are already set, do nothing
10761 if (array_key_exists($key, $fields)) {
10762 continue;
10763 }
10764
10765 if (!empty($value['default'])) {
10766 $this->$key = $value['default'];
10767 }
10768 }
10769 }
10770
10771 return 1;
10772 }
10773
10774
10775 /* Part for comments */
10776
10782 public function fetchComments()
10783 {
10784 require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
10785
10786 $comment = new Comment($this->db);
10787 $result = $comment->fetchAllFor($this->element, $this->id);
10788 if ($result < 0) {
10789 $this->errors = array_merge($this->errors, $comment->errors);
10790 return -1;
10791 } else {
10792 $this->comments = $comment->comments;
10793 }
10794 return count($this->comments);
10795 }
10796
10802 public function getNbComments()
10803 {
10804 return count($this->comments);
10805 }
10806
10813 public function trimParameters($parameters)
10814 {
10815 if (!is_array($parameters)) {
10816 return;
10817 }
10818 foreach ($parameters as $parameter) {
10819 if (isset($this->$parameter)) {
10820 $this->$parameter = trim($this->$parameter);
10821 }
10822 }
10823 }
10824
10825 /* Part for categories/tags */
10826
10837 public function getCategoriesCommon($type_categ)
10838 {
10839 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
10840
10841 // Get current categories
10842 $c = new Categorie($this->db);
10843 $existing = $c->containing($this->id, $type_categ, 'id');
10844
10845 return $existing;
10846 }
10847
10860 public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
10861 {
10862 // Handle single category
10863 if (!is_array($categories)) {
10864 $categories = array($categories);
10865 }
10866
10867 dol_syslog(get_class($this)."::setCategoriesCommon Object Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
10868
10869 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
10870
10871 if (empty($type_categ)) {
10872 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
10873 return -1;
10874 }
10875
10876 // Get current categories
10877 $c = new Categorie($this->db);
10878 $existing = $c->containing($this->id, $type_categ, 'id');
10879 if ($remove_existing) {
10880 // Diff
10881 if (is_array($existing)) {
10882 $to_del = array_diff($existing, $categories);
10883 $to_add = array_diff($categories, $existing);
10884 } else {
10885 $to_del = array(); // Nothing to delete
10886 $to_add = $categories;
10887 }
10888 } else {
10889 $to_del = array(); // Nothing to delete
10890 $to_add = array_diff($categories, $existing);
10891 }
10892
10893 $error = 0;
10894 $ok = 0;
10895
10896 // Process
10897 foreach ($to_del as $del) {
10898 if ($c->fetch($del) > 0) {
10899 $result = $c->del_type($this, $type_categ);
10900 if ($result < 0) {
10901 $error++;
10902 $this->error = $c->error;
10903 $this->errors = $c->errors;
10904 break;
10905 } else {
10906 $ok += $result;
10907 }
10908 }
10909 }
10910 foreach ($to_add as $add) {
10911 if ($c->fetch($add) > 0) {
10912 $result = $c->add_type($this, $type_categ);
10913 if ($result < 0) {
10914 $error++;
10915 $this->error = $c->error;
10916 $this->errors = $c->errors;
10917 break;
10918 } else {
10919 $ok += $result;
10920 }
10921 }
10922 }
10923
10924 return $error ? (-1 * $error) : $ok;
10925 }
10926
10935 public function cloneCategories($fromId, $toId, $type = '')
10936 {
10937 $this->db->begin();
10938
10939 if (empty($type)) {
10940 $type = $this->table_element;
10941 }
10942
10943 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
10944 $categorystatic = new Categorie($this->db);
10945
10946 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
10947 $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
10948 $sql .= " WHERE fk_product = ".((int) $fromId);
10949
10950 if (!$this->db->query($sql)) {
10951 $this->error = $this->db->lasterror();
10952 $this->db->rollback();
10953 return -1;
10954 }
10955
10956 $this->db->commit();
10957 return 1;
10958 }
10959
10966 public function deleteEcmFiles($mode = 0)
10967 {
10968 global $conf;
10969
10970 $this->db->begin();
10971
10972 // Delete in database with mode 0
10973 if ($mode == 0) {
10974 switch ($this->element) {
10975 case 'propal':
10976 $element = 'propale';
10977 break;
10978 case 'product':
10979 $element = 'produit';
10980 break;
10981 case 'order_supplier':
10982 $element = 'fournisseur/commande';
10983 break;
10984 case 'invoice_supplier':
10985 // Special cases that need to use get_exdir to get real dir of object
10986 // In future, all object should use this to define path of documents.
10987 $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
10988 break;
10989 case 'shipping':
10990 $element = 'expedition/sending';
10991 break;
10992 case 'task':
10993 case 'project_task':
10994 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
10995
10996 $project_result = $this->fetch_projet();
10997 if ($project_result >= 0) {
10998 $element = 'projet/'.dol_sanitizeFileName($this->project->ref).'/';
10999 }
11000 // no break
11001 default:
11002 $element = $this->element;
11003 }
11004 '@phan-var-force string $element';
11005
11006 // Delete ecm_files_extrafields with mode 0 (using name)
11007 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
11008 $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
11009 $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
11010 $sql .= ")";
11011
11012 if (!$this->db->query($sql)) {
11013 $this->error = $this->db->lasterror();
11014 $this->db->rollback();
11015 return false;
11016 }
11017
11018 // Delete ecm_files with mode 0 (using name)
11019 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
11020 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
11021 $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
11022
11023 if (!$this->db->query($sql)) {
11024 $this->error = $this->db->lasterror();
11025 $this->db->rollback();
11026 return false;
11027 }
11028 }
11029
11030 // Delete in database with mode 1
11031 if ($mode == 1) {
11032 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
11033 $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).")";
11034 $resql = $this->db->query($sql);
11035 if (!$resql) {
11036 $this->error = $this->db->lasterror();
11037 $this->db->rollback();
11038 return false;
11039 }
11040
11041 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
11042 $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
11043 $resql = $this->db->query($sql);
11044 if (!$resql) {
11045 $this->error = $this->db->lasterror();
11046 $this->db->rollback();
11047 return false;
11048 }
11049 }
11050
11051 $this->db->commit();
11052 return true;
11053 }
11054}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:636
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:456
$object ref
Definition info.php:79
Class to manage categories.
Class to manage comment.
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.
indexFile($destfull, $update_main_doc_field)
Index a file into the ECM database.
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.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
isEmpty()
isEmpty We consider CommonObject isEmpty if this->id is empty
clearFieldError($fieldKey)
clear validation message result for a field
static getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Count items linked to an object id in association table.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
Return the link of last main doc file for direct public download.
liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
Return array with list of possible values for type of contacts.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
swapContactStatus($rowid)
Update status of a contact linked to object.
getFieldError($fieldKey)
get field error message
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
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...
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
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.
updateCommon(User $user, $notrigger=0)
Update object into database.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
addThumbs($file)
Build thumb.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms)
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
setSignedStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a signed status.
setRetainedWarrantyPaymentTerms($id)
Change the retained warranty payments terms.
delThumbs($file)
Delete thumbs.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
getRangOfLine($rowid)
Get position of line (rang)
showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0, $nonewbutton=0)
Return HTML string to put an input field into a page Code very similar with showInputField of extra f...
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
Update a link to contact line.
getElementType()
Return an element type string formatted like element_element target_type and source_type.
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.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetch_origin()
Read linked origin object.
getIdOfLine($rang)
Get rowid of the line relative to its position.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
deleteByParentField($parentId=0, $parentField='', $filter='', $filtermode="AND")
Delete all child object from a parent ID.
static getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
Function used to get an array with all items linked to an object id in association table.
__clone()
Overwrite magic function to solve problem of cloning object that are kept as references.
setPaymentMethods($id)
Change the payments methods.
updateLineDown($rowid, $rang, $max)
Update position of line down (rang)
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data to show into a tooltip.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
canBeNull($info)
Function test if field can be null.
listeTypeContacts($source='internal', $option=0, $activeonly=0, $code='', $element='', $excludeelement='')
Return array with list of possible values for type of contacts.
call_trigger($triggerName, $user)
Call trigger based on this instance.
getRights()
Returns the rights used for this class.
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.
fetch_barcode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
Class to manage ECM files.
Class to manage standard extra fields.
static isEmptyValue($v, string $type)
Return if a value is "empty" for a mandatory vision.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage generation of HTML components Only common components must be here.
Class to manage triggers.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_SERVICE
Service.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:241
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='')
Format phone numbers according to country.
dol_print_ip($ip, $mode=0)
Return an IP formatted to be shown on screen.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getPictoForType($key, $morecss='')
Return the picto for a data type.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0)
Show EMail link formatted for HTML output.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:88
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:143
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:139
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e e e e e statut
Definition invoice.php:1991
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e rowid
Definition invoice.php:1991