dolibarr 24.0.3
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-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
11 * Copyright (C) 2016 Bahfir abbes <bafbes@gmail.com>
12 * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13 * Copyright (C) 2017-2026 Nicolas ZABOURI <info@inovea-conseil.com>
14 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15 * Copyright (C) 2018-2026 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-2026 MDW <mdeweerd@users.noreply.github.com>
21 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
22 * Copyright (C) 2025 Alexandre Janniaux <alexandre.janniaux@gmail.com>
23 * Copyright (C) 2025 Vincent Maury <vmaury@timgroup.fr>
24 * Copyright (C) 2026 Pierre Ardoin <developpeur@lesmetiersdubatiment.fr>
25*
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 3 of the License, or
29 * (at your option) any later version.
30 *
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
35 *
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <https://www.gnu.org/licenses/>.
38 */
39
46require_once DOL_DOCUMENT_ROOT.'/core/class/doldeprecationhandler.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/commontrigger.class.php';
48
54abstract class CommonObject
55{
56 use DolDeprecationHandler;
57 use CommonTrigger;
58
62 public $module;
63
67 public $db;
68
72 public $id;
73
77 public $entity;
78
83 public $error;
84
88 public $errorhidden;
89
93 public $errors = array();
94
99 public $warning;
100
104 public $warnings = array();
105
109 private $validateFieldsErrors = array();
110
114 public $element;
115
120 public $fk_element;
121
127 public $element_for_permission;
128
132 public $table_element;
133
137 public $table_rowid;
138
142 public $table_element_line = '';
143
148 public $ismultientitymanaged;
149
153 public $import_key;
154
158 public $array_options = array();
159
160
239 public $fields = array();
240
246 public $array_languages = null; // Value is array() when load already tried
247
251 public $contacts_ids;
252
256 public $contacts_ids_internal;
257
261 public $linked_objects;
262
266 public $linkedObjectsIds;
267
271 public $linkedObjects;
272
276 private $linkedObjectsFullLoaded = array();
277
281 public $oldcopy;
282
286 public $oldref;
287
291 protected $table_ref_field = '';
292
296 public $restrictiononfksoc = 0;
297
298
299 // The following vars are used by some objects only.
300 // We keep these properties in CommonObject in order to provide common methods using them.
301
305 public $context = array();
306
310 public $actionmsg;
314 public $actionmsg2;
315
319 public $canvas;
320
325 public $project;
326
331 public $fk_project;
332
338 public $fk_projet;
339
344 public $contact;
345
350 public $contact_id;
351
356 public $thirdparty;
357
362 public $user;
363
368 public $product;
369
374 public $origin_type;
375
380 public $origin_id;
381
386
392 public $origin;
393
402 private $expedition;
403
409 private $livraison;
410
416 private $commandeFournisseur;
417
418
422 public $ref;
423
427 public $ref_ext;
428
432 public $ref_previous;
433
437 public $ref_next;
438
442 public $newref;
443
450 public $statut;
451
460 public $status;
461
466 public $country;
467
472 public $country_id;
473
478 public $country_code;
479
484 public $state;
485
490 public $state_id;
491
496 public $state_code;
497
502 public $region_id;
503
508 public $region_code;
509
514 public $region;
515
516
521 public $barcode_type;
522
527 public $barcode_type_code;
528
533 public $barcode_type_label;
534
539 public $barcode_type_coder;
540
545 public $mode_reglement_id;
546
551 public $cond_reglement_id;
552
556 public $demand_reason_id;
557
562 public $transport_mode_id;
563
571 private $cond_reglement; // Private to call DolDeprecationHandler
575 protected $depr_cond_reglement; // Internal value for deprecation
576
582 public $fk_delivery_address;
583
588 public $shipping_method_id;
589
594 public $shipping_method;
595
596 // Multicurrency
600 public $fk_multicurrency;
601
606 public $multicurrency_code;
607
612 public $multicurrency_tx;
613
617 public $multicurrency_total_ht;
618
622 public $multicurrency_total_tva;
623
627 public $multicurrency_total_localtax1; // not in database
628
632 public $multicurrency_total_localtax2; // not in database
633
637 public $multicurrency_total_ttc;
638
639
644 public $model_pdf;
645
650 public $last_main_doc;
651
657 public $fk_bank;
658
663 public $fk_account;
664
669 public $note_public;
670
675 public $note_private;
676
682 public $note;
683
688 public $total_ht;
689
694 public $total_tva;
695
700 public $total_localtax1;
701
706 public $total_localtax2;
707
712 public $total_ttc;
713
714
718 public $lines;
719
723 public $actiontypecode;
724
729 public $comments = array();
730
734 public $name;
735
739 public $lastname;
740
744 public $firstname;
745
750 public $civility_id;
751
755 public $civility_code;
756
757 // Dates
761 public $date_creation;
762
766 public $date_validation;
767
771 public $date_modification;
772
778 public $tms;
779
785 private $date_update;
786
790 public $date_cloture;
791
795 public $user_creation_id;
796
800 public $user_validation_id;
801
805 public $user_closing_id;
806
810 public $user_modification_id;
811
816 public $fk_user_creat;
817
822 public $fk_user_modif;
823
824
828 public $next_prev_filter;
829
833 public $specimen = 0;
834
838 public $sendtoid;
839
840
845 public $alreadypaid;
846
851 public $totalpaid;
852
857 public $totalpaid_multicurrency;
858
859
863 public $labelStatus = array();
864
868 public $labelStatusShort = array();
869
873 public $tpl;
874
875
879 public $showphoto_on_popup;
880
884 public $nb = array();
885
889 public $nbphoto;
890
894 public $output;
895
899 public $extraparams = array();
900
904 protected $childtables = array();
905
911 protected $childtablesoncascade = array();
912
916 public $cond_reglement_supplier_id;
917
923 public $deposit_percent;
924
925
929 public $warehouse_id;
930
934 public $isextrafieldmanaged = 0;
935
944 public $attachedfiles;
945
946
947
948 // No constructor as it is an abstract class
949
955 protected function deprecatedProperties()
956 {
957 return array(
958 'alreadypaid' => 'totalpaid',
959 'cond_reglement' => 'depr_cond_reglement',
960 //'note' => 'note_private', // Some classes needs ->note and others need ->note_public/private so we can't manage deprecation for this field with dolDeprecationHandler
961 'commandeFournisseur' => 'origin_object',
962 'expedition' => 'origin_object',
963 'fk_project' => 'fk_project',
964 'livraison' => 'origin_object',
965 'projet' => 'project',
966 'statut' => 'status',
967 );
968 }
969
970
981 public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
982 {
983 global $db, $conf;
984
985 $sql = "SELECT rowid";
986 $sql .= " FROM ".$db->prefix().$element;
987 $sql .= " WHERE entity IN (".getEntity($element).")";
988
989 if ($id > 0) {
990 $sql .= " AND rowid = ".((int) $id);
991 } elseif ($ref) {
992 $sql .= " AND ref = '".$db->escape($ref)."'";
993 } elseif ($ref_ext) {
994 $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
995 } else {
996 $error = 'ErrorWrongParameters';
997 dol_syslog(get_class()."::isExistingObject ".$error, LOG_ERR);
998 return -1;
999 }
1000 if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
1001 $sql .= " AND entity = ".((int) $conf->entity);
1002 }
1003
1004 dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
1005 $resql = $db->query($sql);
1006 if ($resql) {
1007 $num = $db->num_rows($resql);
1008 if ($num > 0) {
1009 return 1;
1010 } else {
1011 return 0;
1012 }
1013 }
1014 return -1;
1015 }
1016
1023 public function isEmpty()
1024 {
1025 return (empty($this->id));
1026 }
1027
1035 {
1036 if (!empty($object->error)) {
1037 $this->error = $object->error;
1038 }
1039 if (!empty($object->errors)) {
1040 $this->errors = array_merge($this->errors, $object->errors);
1041 }
1042 }
1043
1051 public function getTooltipContentArray($params)
1052 {
1053 return [];
1054 }
1055
1063 public function getTooltipContent($params)
1064 {
1065 global $action, $extrafields, $langs, $hookmanager;
1066
1067 // If there is too much extrafields, we do not include them into tooltip
1068 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1069
1070 $data = $this->getTooltipContentArray($params);
1071 $count = 0;
1072
1073 // Add extrafields
1074 if (!empty($extrafields->attributes[$this->table_element]['label'])) {
1075 $data['opendivextra'] = '<div class="centpercent wordbreak divtooltipextra">';
1076 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
1077 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
1078 continue;
1079 }
1080
1081 if (empty($extrafields->attributes[$this->table_element]['showintooltip'][$key])) {
1082 continue;
1083 }
1084
1085
1086 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1087 $data['more_extrafields'] = '<br>...';
1088 break;
1089 }
1090 $enabled = 1;
1091 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
1092 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
1093 }
1094 if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
1095 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
1096 }
1097 $perms = 1;
1098 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
1099 $perms = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
1100 }
1101 if (empty($enabled)) {
1102 continue; // 0 = Never visible field
1103 }
1104 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1105 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation
1106 }
1107 if (empty($perms)) {
1108 continue; // 0 = Not visible
1109 }
1110 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
1111 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
1112 }
1113 $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
1114 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
1115 $data[$key] = '<br><b><u>'. $labelextra . '</u></b>';
1116 } else {
1117 $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
1118 $data[$key] = '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
1119 $count++;
1120 }
1121 }
1122 $data['closedivextra'] = '</div>';
1123 }
1124
1125 $hookmanager->initHooks(array($this->element . 'dao'));
1126 $parameters = array(
1127 'tooltipcontentarray' => &$data,
1128 'params' => $params,
1129 );
1130 // Note that $action and $object may have been modified by some hooks
1131 $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
1132
1133 //var_dump($data);
1134 $label = implode($data);
1135
1136 return $label;
1137 }
1138
1139
1145 public function errorsToString()
1146 {
1147 return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').implode(', ', $this->errors)) : '');
1148 }
1149
1150
1157 public function getFormatedCustomerRef($objref)
1158 {
1159 global $hookmanager;
1160
1161 $parameters = array('objref' => $objref);
1162 $action = '';
1163 $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1164 if ($reshook > 0) {
1165 return $hookmanager->resArray['objref'];
1166 }
1167 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1168 }
1169
1176 public function getFormatedSupplierRef($objref)
1177 {
1178 global $hookmanager;
1179
1180 $parameters = array('objref' => $objref);
1181 $action = '';
1182 $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1183 if ($reshook > 0) {
1184 return $hookmanager->resArray['objref'];
1185 }
1186 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1187 }
1188
1198 public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
1199 {
1200 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1201 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1202 $tmparray = getCountry($this->country_id, 'all');
1203 $this->country_code = $tmparray['code'];
1204 $this->country = $tmparray['label'];
1205 }
1206
1207 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1208 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1209 $tmparray = getState($this->state_id, 'all', null, 1);
1210 $this->state_code = $tmparray['code'];
1211 $this->state = $tmparray['label'];
1212 $this->region_code = $tmparray['region_code'];
1213 $this->region = $tmparray['region'];
1214 }
1215
1216 return dol_format_address($this, $withcountry, $sep, null, 0, $extralangcode);
1217 }
1218
1219
1228 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1229 {
1230 global $user, $dolibarr_main_url_root;
1231
1232 if (empty($this->last_main_doc)) {
1233 return ''; // No way to known which document name to use
1234 }
1235
1236 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1237 $ecmfile = new EcmFiles($this->db);
1238 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1239 if ($result < 0) {
1240 $this->error = $ecmfile->error;
1241 $this->errors = $ecmfile->errors;
1242 return -1;
1243 }
1244
1245 if (empty($ecmfile->id)) { // No entry into file index already exists, we should initialize the shared key manually.
1246 // Add entry into index
1247 if ($initsharekey) {
1248 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1249
1250 // 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
1251 /*
1252 $ecmfile->filepath = $rel_dir;
1253 $ecmfile->filename = $filename;
1254 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1255 $ecmfile->fullpath_orig = '';
1256 $ecmfile->gen_or_uploaded = 'generated';
1257 $ecmfile->description = ''; // indexed content
1258 $ecmfile->keywords = ''; // keyword content
1259 $ecmfile->share = getRandomPassword(true);
1260 $result = $ecmfile->create($user);
1261 if ($result < 0)
1262 {
1263 $this->error = $ecmfile->error;
1264 $this->errors = $ecmfile->errors;
1265 }
1266 */
1267 } else {
1268 return '';
1269 }
1270 } elseif (empty($ecmfile->share)) { // Entry into file index already exists but no share key is defined.
1271 // Add entry into index
1272 if ($initsharekey) {
1273 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1274 $ecmfile->share = getRandomPassword(true);
1275 $ecmfile->update($user);
1276 } else {
1277 return '';
1278 }
1279 }
1280 // Define $urlwithroot
1281 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1282 // This is to use external domain name found into config file
1283 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1284 //else
1285 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1286 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1287
1288 $forcedownload = 0;
1289
1290 $paramlink = '';
1291 //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1292 //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1293 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1294 if (!empty($ecmfile->share)) {
1295 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1296 }
1297 if ($forcedownload) {
1298 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1299 }
1300
1301 if ($relativelink) {
1302 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1303 } else {
1304 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1305 }
1306
1307 // Here $ecmfile->share is defined
1308 return $linktoreturn;
1309 }
1310
1311
1312 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1322 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1323 {
1324 // phpcs:enable
1325 global $user, $langs;
1326
1327 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1328
1329 // Check parameters
1330 if ($fk_socpeople <= 0) {
1331 $langs->load("errors");
1332 $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1333 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1334 return -1;
1335 }
1336
1337 // Check that the contact actually exists in database
1338 $sql_check = "SELECT rowid FROM ".$this->db->prefix().($source == 'internal' ? "user" : "socpeople")." WHERE rowid = ".((int) $fk_socpeople);
1339 $resql_check = $this->db->query($sql_check);
1340 if ($resql_check) {
1341 if (!$this->db->num_rows($resql_check)) {
1342 $langs->load("errors");
1343 $this->error = $langs->trans("ErrorRecordNotFound");
1344 dol_syslog(get_class($this)."::add_contact Contact/user id ".$fk_socpeople." does not exist", LOG_ERR);
1345 return -1;
1346 }
1347 } else {
1348 $this->error = $this->db->lasterror();
1349 return -1;
1350 }
1351
1352 if (!$type_contact) {
1353 $langs->load("errors");
1354 $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1355 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1356 return -2;
1357 }
1358
1359 if ($this->restrictiononfksoc && property_exists($this, 'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight('societe', 'client', 'voir')) {
1360 $sql_allowed_contacts = 'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().'societe_commerciaux as sc';
1361 $sql_allowed_contacts .= ' WHERE sc.fk_soc = '.(int) $this->socid;
1362 $sql_allowed_contacts .= ' AND sc.fk_user = '.(int) $user->id;
1363
1364 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1365
1366 if (!$resql_allowed_contacts) {
1367 $this->errors[] = $this->db->lasterror();
1368 return -3;
1369 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1370 if ($obj->cnt == 0) {
1371 $langs->load("companies");
1372 $this->error = $langs->trans("ErrorCommercialNotAllowedForThirdparty", $user->id);
1373 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1374 return -4;
1375 }
1376 }
1377 }
1378
1379 $id_type_contact = 0;
1380 if (is_numeric($type_contact)) {
1381 $id_type_contact = $type_contact;
1382 } else {
1383 // We look for id type_contact
1384 $sql = "SELECT tc.rowid";
1385 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1386 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1387 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1388 $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1389 //print $sql;
1390 $resql = $this->db->query($sql);
1391 if ($resql) {
1392 $obj = $this->db->fetch_object($resql);
1393 if ($obj) {
1394 $id_type_contact = $obj->rowid;
1395 }
1396 }
1397 }
1398 if ($id_type_contact == 0) {
1399 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");
1400 return 0;
1401 }
1402
1403 $datecreate = dol_now();
1404
1405 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1406 $TListeContacts = $this->liste_contact(-1, $source);
1407 $already_added = false;
1408 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1409 foreach ($TListeContacts as $array_contact) {
1410 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1411 $already_added = true;
1412 break;
1413 }
1414 }
1415 }
1416
1417 if (!$already_added) {
1418 $this->db->begin();
1419
1420 // Insert into database
1421 $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1422 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1423 $sql .= " VALUES (".((int) $this->id).", ".((int) $fk_socpeople)." , ";
1424 $sql .= "'".$this->db->idate($datecreate)."'";
1425 $sql .= ", 4, ".((int) $id_type_contact);
1426 $sql .= ")";
1427
1428 $resql = $this->db->query($sql);
1429 if ($resql) {
1430 if (!$notrigger) {
1431 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1432 $result = $this->call_trigger($triggerPrefix.'_ADD_CONTACT', $user);
1433 if ($result < 0) {
1434 $this->db->rollback();
1435 return -5;
1436 }
1437 }
1438
1439 $this->db->commit();
1440 return 1;
1441 } else {
1442 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1443 $this->error = $this->db->errno();
1444 $this->db->rollback();
1445 return -6;
1446 } else {
1447 $this->error = $this->db->lasterror();
1448 $this->db->rollback();
1449 return -7;
1450 }
1451 }
1452 } else {
1453 return 0;
1454 }
1455 }
1456
1457 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1465 public function copy_linked_contact($objFrom, $source = 'internal')
1466 {
1467 // phpcs:enable
1468 $contacts = $objFrom->liste_contact(-1, $source);
1469 foreach ($contacts as $contact) {
1470 // Type code, not id: the type id belongs to the source element and is wrong on another element type
1471 if ($this->add_contact($contact['id'], $contact['code'], $contact['source']) < 0) {
1472 return -1;
1473 }
1474 }
1475 return 1;
1476 }
1477
1478 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1488 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1489 {
1490 // phpcs:enable
1491 // Insert into database
1492 $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1493 $sql .= " statut = ".((int) $statut);
1494 if ($type_contact_id) {
1495 $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1496 }
1497 if ($fk_socpeople) {
1498 $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1499 }
1500 $sql .= " where rowid = ".((int) $rowid);
1501
1502 $resql = $this->db->query($sql);
1503 if ($resql) {
1504 return 0;
1505 } else {
1506 $this->error = $this->db->lasterror();
1507 return -1;
1508 }
1509 }
1510
1511 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1519 public function delete_contact($rowid, $notrigger = 0)
1520 {
1521 // phpcs:enable
1522 global $user;
1523
1524 $error = 0;
1525
1526 // When called on a loaded object, the link must be one of its own contacts (same filter as liste_contact())
1527 if ($this->id > 0) {
1528 $sql = "SELECT ec.rowid FROM ".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc";
1529 $sql .= " WHERE ec.rowid = ".((int) $rowid)." AND ec.element_id = ".((int) $this->id);
1530 $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element)."'";
1531 $resql = $this->db->query($sql);
1532 if (!$resql || !$this->db->num_rows($resql)) {
1533 $this->error = 'ErrorRecordNotFound';
1534 return -1;
1535 }
1536 }
1537
1538 $this->db->begin();
1539
1540 if (!$error && empty($notrigger)) {
1541 // Call trigger
1542 $this->context['contact_id'] = ((int) $rowid);
1543 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1544 $result = $this->call_trigger($triggerPrefix.'_DELETE_CONTACT', $user);
1545 if ($result < 0) {
1546 $error++;
1547 }
1548 // End call triggers
1549 }
1550
1551 if (!$error) {
1552 dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1553
1554 $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1555 $sql .= " WHERE rowid = ".((int) $rowid);
1556
1557 $result = $this->db->query($sql);
1558 if (!$result) {
1559 $error++;
1560 $this->errors[] = $this->db->lasterror();
1561 }
1562 }
1563
1564 if (!$error) {
1565 $this->db->commit();
1566 return 1;
1567 } else {
1568 $this->error = $this->db->lasterror();
1569 $this->db->rollback();
1570 return -1;
1571 }
1572 }
1573
1574 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1582 public function delete_linked_contact($source = '', $code = '')
1583 {
1584 // phpcs:enable
1585 $listId = '';
1586 $temp = array();
1587 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1588
1589 if (!empty($typeContact)) {
1590 foreach ($typeContact as $key => $value) {
1591 array_push($temp, $key);
1592 }
1593 $listId = implode(",", $temp);
1594 }
1595
1596 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1597 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1598 if (empty($listId)) {
1599 return 0;
1600 }
1601
1602 $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1603 $sql .= " WHERE element_id = ".((int) $this->id);
1604 $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1605
1606 dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1607 if ($this->db->query($sql)) {
1608 return 1;
1609 } else {
1610 $this->error = $this->db->lasterror();
1611 return -1;
1612 }
1613 }
1614
1615 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1627 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1628 {
1629 // phpcs:enable
1630 global $langs;
1631
1632 $tab = array();
1633
1634 $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
1635 if ($source == 'internal') {
1636 $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1637 }
1638 if ($source == 'external' || $source == 'thirdparty') {
1639 $sql .= ", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1640 }
1641 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1642 if (empty($arrayoftcids)) {
1643 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1644 }
1645 $sql .= " FROM";
1646 if (empty($arrayoftcids)) {
1647 $sql .= " ".$this->db->prefix()."c_type_contact as tc,";
1648 }
1649 $sql .= " ".$this->db->prefix()."element_contact as ec";
1650 if ($source == 'internal') { // internal contact (user)
1651 $sql .= " LEFT JOIN ".$this->db->prefix()."user as t on ec.fk_socpeople = t.rowid";
1652 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as co ON co.rowid = t.fk_country";
1653 }
1654 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1655 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople as t on ec.fk_socpeople = t.rowid";
1656 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as co ON co.rowid = t.fk_pays";
1657 }
1658 $sql .= " WHERE ec.element_id = ".((int) $this->id);
1659 if (empty($arrayoftcids)) {
1660 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1661 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1662 if ($code) {
1663 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1664 }
1665 if ($source == 'internal') {
1666 $sql .= " AND tc.source = 'internal'";
1667 }
1668 if ($source == 'external' || $source == 'thirdparty') {
1669 $sql .= " AND tc.source = 'external'";
1670 }
1671 $sql .= " AND tc.active = 1";
1672 } else {
1673 $sql .= " AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', $arrayoftcids)).")";
1674 }
1675 if ($status >= 0) {
1676 $sql .= " AND t.statut = ".((int) $status); // t is llx_user or llx_socpeople
1677 }
1678 if ($statusoflink >= 0) {
1679 $sql .= " AND ec.statut = ".((int) $statusoflink);
1680 }
1681 $sql .= " ORDER BY t.lastname ASC";
1682
1683 dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1684 $resql = $this->db->query($sql);
1685 if ($resql) {
1686 $num = $this->db->num_rows($resql);
1687 $i = 0;
1688 while ($i < $num) {
1689 $obj = $this->db->fetch_object($resql);
1690
1691 if (!$list) {
1692 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1693 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1694 $tab[$i] = array(
1695 'parentId' => $this->id,
1696 'source' => $obj->source,
1697 'socid' => $obj->socid,
1698 'id' => $obj->id,
1699 'nom' => $obj->lastname, // For backward compatibility
1700 'civility' => $obj->civility,
1701 'lastname' => $obj->lastname,
1702 'firstname' => $obj->firstname,
1703 'email' => $obj->email,
1704 'address' => $obj->address,
1705 'zip' => $obj->zip,
1706 'town' => $obj->town,
1707 'country_id' => $obj->country_id,
1708 'country' => $obj->country,
1709 'login' => (empty($obj->login) ? '' : $obj->login),
1710 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1711 'gender' => (empty($obj->gender) ? '' : $obj->gender),
1712 'statuscontact' => $obj->statuscontact,
1713 'rowid' => $obj->rowid,
1714 'code' => $obj->code,
1715 'libelle' => $libelle_type,
1716 'status' => (int) $obj->statuslink,
1717 'fk_c_type_contact' => $obj->fk_c_type_contact
1718 );
1719 } else {
1720 $tab[$i] = $obj->id;
1721 }
1722
1723 $i++;
1724 }
1725
1726 return $tab;
1727 } else {
1728 $this->error = $this->db->lasterror();
1729 dol_print_error($this->db);
1730 return -1;
1731 }
1732 }
1733
1734
1741 public function swapContactStatus($rowid)
1742 {
1743 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1744 $sql .= " tc.code, tc.libelle as type_label";
1745 $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1746 $sql .= " WHERE ec.rowid =".((int) $rowid);
1747 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1748 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1749
1750 dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1751 $resql = $this->db->query($sql);
1752 if ($resql) {
1753 $obj = $this->db->fetch_object($resql);
1754 $newstatut = ($obj->statut == 4) ? 5 : 4;
1755 $result = $this->update_contact($rowid, $newstatut);
1756 $this->db->free($resql);
1757 return $result;
1758 } else {
1759 $this->error = $this->db->error();
1760 dol_print_error($this->db);
1761 return -1;
1762 }
1763 }
1764
1765 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1776 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1777 {
1778 // phpcs:enable
1779 global $langs;
1780
1781 $sanitized_order = $order; // @phan-suppress-current-line SqlInjection
1782
1783 if (empty($sanitized_order)) {
1784 $sanitized_order = 'position';
1785 }
1786 if ($sanitized_order == 'position') {
1787 $sanitized_order .= ',code';
1788 }
1789
1790 $tab = array();
1791
1792 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1793 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1794 $sql .= " WHERE tc.element = '".$this->db->escape($this->element)."'";
1795 if ($activeonly == 1) {
1796 $sql .= " AND tc.active = 1"; // only the active types
1797 }
1798 if (!empty($source) && $source != 'all') {
1799 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1800 }
1801 if (!empty($code)) {
1802 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1803 }
1804 $sql .= $this->db->order($sanitized_order, 'ASC');
1805
1806 //print "sql=".$sql;
1807 $resql = $this->db->query($sql);
1808 if (!$resql) {
1809 $this->error = $this->db->lasterror();
1810 //dol_print_error($this->db);
1811 return null;
1812 }
1813
1814 $num = $this->db->num_rows($resql);
1815 $i = 0;
1816 while ($i < $num) {
1817 $obj = $this->db->fetch_object($resql);
1818
1819 $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1820 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1821 if (empty($option)) {
1822 $tab[$obj->rowid] = $libelle_type;
1823 } elseif ($option == 1) {
1824 $tab[$obj->code] = $libelle_type;
1825 } else {
1826 $tab[$obj->rowid] = array('id' => $obj->rowid, 'code' => $obj->code, 'label' => $libelle_type);
1827 }
1828 $i++;
1829 }
1830
1831 return $tab;
1832 }
1833
1845 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1846 {
1847 global $langs;
1848
1849 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1850
1851 $tab = array();
1852
1853 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1854 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1855
1856 $sqlWhere = array();
1857 if (!empty($element)) {
1858 $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1859 }
1860 if (!empty($excludeelement)) {
1861 $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1862 }
1863
1864 if ($activeonly == 1) {
1865 $sqlWhere[] = " tc.active=1"; // only the active types
1866 }
1867
1868 if (!empty($source) && $source != 'all') {
1869 $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1870 }
1871
1872 if (!empty($code)) {
1873 $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1874 }
1875
1876 if (count($sqlWhere) > 0) {
1877 $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1878 }
1879
1880 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1881
1882 dol_syslog(__METHOD__, LOG_DEBUG);
1883 $resql = $this->db->query($sql);
1884 if ($resql) {
1885 $num = $this->db->num_rows($resql);
1886 if ($num > 0) {
1887 $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1888
1889 while ($obj = $this->db->fetch_object($resql)) {
1890 $modulename = $obj->module ?? $obj->element;
1891 if (strpos($obj->element, 'project') !== false) {
1892 $modulename = 'projet';
1893 } elseif ($obj->element == 'contrat') {
1894 $element = 'contract';
1895 } elseif ($obj->element == 'action') {
1896 $modulename = 'agenda';
1897 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1898 $modulename = 'fournisseur';
1899 }
1900 if (isModEnabled($modulename)) {
1901 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1902 $tmpelement = $obj->element;
1903 $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1904 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1905 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1906 }
1907 }
1908 }
1909 return $tab;
1910 } else {
1911 $this->error = $this->db->lasterror();
1912 return null;
1913 }
1914 }
1915
1927 public function getIdContact($source, $code, $status = 0)
1928 {
1929 $result = array();
1930 $i = 0;
1931 // Particular case for shipping
1932 if (!getDolGlobalInt('SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element == 'shipping' && $this->origin_id != 0) {
1933 $id = $this->origin_id;
1934 $element = 'commande';
1935 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1936 $id = $this->origin_id;
1937 $element = 'order_supplier';
1938 } else {
1939 $id = $this->id;
1940 $element = $this->element;
1941 }
1942
1943 $sql = "SELECT ec.fk_socpeople";
1944 $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1945 if ($source == 'internal') {
1946 $sql .= " ".$this->db->prefix()."user as c,";
1947 }
1948 if ($source == 'external') {
1949 $sql .= " ".$this->db->prefix()."socpeople as c,";
1950 }
1951 $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1952 $sql .= " WHERE ec.element_id = ".((int) $id);
1953 $sql .= " AND ec.fk_socpeople = c.rowid";
1954 if ($source == 'internal') {
1955 $sql .= " AND c.entity IN (".getEntity('user').")";
1956 }
1957 if ($source == 'external') {
1958 $sql .= " AND c.entity IN (".getEntity('societe').")";
1959 }
1960 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1961 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1962 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1963 if ($code) {
1964 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1965 }
1966 $sql .= " AND tc.active = 1";
1967 if ($status) {
1968 $sql .= " AND ec.statut = ".((int) $status);
1969 }
1970
1971 dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1972 $resql = $this->db->query($sql);
1973 if ($resql) {
1974 while ($obj = $this->db->fetch_object($resql)) {
1975 $result[$i] = $obj->fk_socpeople;
1976 $i++;
1977 }
1978 } else {
1979 $this->error = $this->db->error();
1980 return null;
1981 }
1982
1983 return $result;
1984 }
1985
1986 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1993 public function fetch_contact($contactid = null)
1994 {
1995 // phpcs:enable
1996 if (empty($contactid)) {
1997 $contactid = $this->contact_id;
1998 }
1999
2000 if (empty($contactid)) {
2001 return 0;
2002 }
2003
2004 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2005 $contact = new Contact($this->db);
2006 $result = $contact->fetch($contactid);
2007 $this->contact = $contact;
2008 return $result;
2009 }
2010
2011 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2019 public function fetch_thirdparty($force_thirdparty_id = 0)
2020 {
2021 // phpcs:enable
2022 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2023 return 0;
2024 }
2025
2026 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
2027
2028 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2029 if ($force_thirdparty_id) {
2030 $idtofetch = $force_thirdparty_id;
2031 }
2032
2033 if ($idtofetch) {
2034 $thirdparty = new Societe($this->db);
2035 $result = $thirdparty->fetch($idtofetch);
2036 if ($result < 0) {
2037 $this->errors = array_merge($this->errors, $thirdparty->errors);
2038 }
2039 $this->thirdparty = $thirdparty;
2040
2041 // Use first price level if level not defined for third party
2042 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->thirdparty->price_level)) {
2043 $this->thirdparty->price_level = 1;
2044 }
2045
2046 return $result;
2047 } else {
2048 return -1;
2049 }
2050 }
2051
2052
2060 public function fetchOneLike($ref)
2061 {
2062 if (!$this->table_ref_field) {
2063 return 0;
2064 }
2065
2066 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2067 $sql .= " WHERE ".$this->db->sanitize($this->table_ref_field)." LIKE '".$this->db->escape($ref)."'"; // no escapeforlike here
2068 $sql .= " LIMIT 1";
2069
2070 $query = $this->db->query($sql);
2071
2072 if (!$this->db->num_rows($query)) {
2073 return 0;
2074 }
2075
2076 $result = $this->db->fetch_object($query);
2077
2078 if (method_exists($this, 'fetch')) {
2079 return $this->fetch($result->rowid);
2080 } else {
2081 $this->error = 'Fetch method not implemented on '.get_class($this);
2082 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2083 array_push($this->errors, $this->error);
2084 return -1;
2085 }
2086 }
2087
2088 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2097 public function fetch_barcode()
2098 {
2099 // phpcs:enable
2100 return $this->fetchBarCode();
2101 }
2102
2110 public function fetchBarCode()
2111 {
2112 dol_syslog(get_class($this).'::fetchBarCode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
2113
2114 $idtype = $this->barcode_type;
2115 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
2116 if ($this->element == 'product' && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) {
2117 $idtype = getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE');
2118 } elseif ($this->element == 'societe') {
2119 $idtype = getDolGlobalString('GENBARCODE_BARCODETYPE_THIRDPARTY');
2120 } else {
2121 dol_syslog('Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2122 }
2123 }
2124
2125 if ($idtype > 0) {
2126 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
2127 $sql = "SELECT rowid, code, libelle as label, coder";
2128 $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
2129 $sql .= " WHERE rowid = ".((int) $idtype);
2130
2131 $resql = $this->db->query($sql);
2132 if ($resql) {
2133 $obj = $this->db->fetch_object($resql);
2134
2135 $this->barcode_type = $obj->rowid;
2136 $this->barcode_type_code = $obj->code;
2137 $this->barcode_type_label = $obj->label;
2138 $this->barcode_type_coder = $obj->coder;
2139 return 1;
2140 } else {
2141 dol_print_error($this->db);
2142 return -1;
2143 }
2144 }
2145 }
2146 return 0;
2147 }
2148
2154 public function fetchProject()
2155 {
2156 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
2157
2158 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2159 $this->fk_project = $this->fk_projet; // For backward compatibility
2160 }
2161 if (empty($this->fk_project)) {
2162 return 0;
2163 }
2164
2165 $project = new Project($this->db);
2166 $result = $project->fetch($this->fk_project);
2167
2168 $this->project = $project;
2169
2170 return $result;
2171 }
2172
2173 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2181 public function fetch_project()
2182 {
2183 // phpcs:enable
2184 return $this->fetchProject();
2185 }
2186
2187 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2195 public function fetch_projet()
2196 {
2197 // phpcs:enable
2198 return $this->fetchProject();
2199 }
2200
2201 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2207 public function fetch_product()
2208 {
2209 // phpcs:enable
2210 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2211
2212 // @phan-suppress-next-line PhanUndeclaredProperty
2213 if (empty($this->fk_product)) {
2214 return 0;
2215 }
2216
2217 $product = new Product($this->db);
2218 // @phan-suppress-next-line PhanUndeclaredProperty
2219 $result = $product->fetch($this->fk_product);
2220
2221 $this->product = $product;
2222 return $result;
2223 }
2224
2225 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2232 public function fetch_user($userid)
2233 {
2234 // phpcs:enable
2235 $user = new User($this->db);
2236 $result = $user->fetch($userid);
2237 $this->user = $user;
2238 return $result;
2239 }
2240
2241 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2248 public function fetch_origin()
2249 {
2250 // phpcs:enable
2251 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2252
2253 // Manage classes with non standard name
2254 if ($tmpclassname == 'shipping') {
2255 $tmpclassname = 'Expedition';
2256 }
2257 if ($tmpclassname == 'delivery') {
2258 $tmpclassname = 'Livraison';
2259 }
2260 if ($tmpclassname == 'order_supplier' || $tmpclassname == 'supplier_order') {
2261 $tmpclassname = 'CommandeFournisseur';
2262 }
2263
2264 $classname = ucfirst($tmpclassname);
2265
2266 $this->origin_object = new $classname($this->db);
2267 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
2268 $this->origin_object->fetch($this->origin_id);
2269 }
2270
2280 public function fetchObjectFrom($table, $field, $key, $element = null)
2281 {
2282 global $conf;
2283
2284 $result = false;
2285
2286 $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
2287 $sql .= " WHERE ".$this->db->sanitize($field)." = '".$this->db->escape($key)."'";
2288 if (!empty($element)) {
2289 $sql .= " AND entity IN (".getEntity($element).")";
2290 } else {
2291 $sql .= " AND entity = ".((int) $conf->entity);
2292 }
2293
2294 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
2295 $resql = $this->db->query($sql);
2296 if ($resql) {
2297 $obj = $this->db->fetch_object($resql);
2298 // Test for avoid error -1
2299 if ($obj) {
2300 if (method_exists($this, 'fetch')) {
2301 $result = $this->fetch($obj->rowid);
2302 } else {
2303 $this->error = 'fetch() method not implemented on '.get_class($this);
2304 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2305 array_push($this->errors, $this->error);
2306 $result = -1;
2307 }
2308 }
2309 }
2310
2311 return $result;
2312 }
2313
2322 public function getValueFrom($table, $id, $field)
2323 {
2324 $result = false;
2325 if (!empty($id) && !empty($field) && !empty($table)) {
2326 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2327 dol_syslog(get_class($this).'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2328 return -1;
2329 }
2330 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2331 dol_syslog(get_class($this).'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2332 return -1;
2333 }
2334
2335 $sql = "SELECT ".$this->db->sanitize($field)." FROM ".$this->db->prefix().$this->db->sanitize($table);
2336 $sql .= " WHERE rowid = ".((int) $id);
2337
2338 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2339 $resql = $this->db->query($sql);
2340 if ($resql) {
2341 $row = $this->db->fetch_row($resql);
2342 $result = $row[0];
2343 }
2344 }
2345 return $result;
2346 }
2347
2364 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2365 {
2366 global $user;
2367
2368 if (empty($table)) {
2369 $table = $this->table_element;
2370 }
2371 if (empty($id)) {
2372 $id = $this->id;
2373 }
2374 if (empty($format)) {
2375 $format = 'text';
2376 }
2377 if (empty($id_field)) {
2378 $id_field = 'rowid';
2379 }
2380
2381 $propfield = $field;
2382
2383 // Special case
2384 if ($table == 'product') {
2385 if ($field == 'note_private') {
2386 $field = 'note';
2387 $propfield = 'note_private';
2388 } elseif ($field == 'status') {
2389 $field = 'tosell';
2390 $propfield = 'status';
2391 } elseif ($field == 'status_buy') {
2392 $field = 'tobuy';
2393 $propfield = 'status_buy';
2394 } elseif ($field == 'status_batch') {
2395 $field = 'tobatch';
2396 $propfield = 'status_batch';
2397 }
2398 }
2399
2400 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2401 $fk_user_field = 'fk_user_mod';
2402 }
2403 if (in_array($table, array('prelevement_bons'))) { // TODO Add a field fk_user_modif into llx_prelevement_bons
2404 $fk_user_field = '';
2405 }
2406
2407 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2408 dol_syslog(get_class($this).'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2409 return -1;
2410 }
2411 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2412 dol_syslog(get_class($this).'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2413 return -1;
2414 }
2415
2416 $oldvalue = null;
2417 if ($trigkey) {
2418 $sql = "SELECT " . $this->db->sanitize($field);
2419 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2420 $sql .= " WHERE " . $this->db->sanitize($id_field) . " = " . ((int) $id);
2421
2422 $resql = $this->db->query($sql);
2423 if ($resql) {
2424 if ($obj = $this->db->fetch_object($resql)) {
2425 if ($format == 'date') {
2426 $oldvalue = $this->db->jdate($obj->$field);
2427 } else {
2428 $oldvalue = $obj->$field;
2429 }
2430 }
2431 } else {
2432 $this->error = $this->db->lasterror();
2433 return -1;
2434 }
2435 }
2436
2437 $error = 0;
2438
2439 dol_syslog(__METHOD__, LOG_DEBUG);
2440
2441 $this->db->begin();
2442
2443 $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2444
2445 if ($format == 'text') {
2446 $sql .= $this->db->sanitize($field)." = '".$this->db->escape($value)."'";
2447 } elseif ($format == 'int') {
2448 $sql .= $this->db->sanitize($field)." = ".((int) $value);
2449 } elseif ($format == 'date') {
2450 $sql .= $this->db->sanitize($field)." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2451 } elseif ($format == 'dategmt') {
2452 $sql .= $this->db->sanitize($field)." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
2453 }
2454
2455 if ($fk_user_field) {
2456 if (!empty($fuser) && is_object($fuser)) {
2457 $sql .= ", ".$this->db->sanitize($fk_user_field)." = ".((int) $fuser->id);
2458 } elseif (empty($fuser) || $fuser != 'none') {
2459 $sql .= ", ".$this->db->sanitize($fk_user_field)." = ".((int) $user->id);
2460 }
2461 }
2462
2463 $sql .= " WHERE ".$this->db->sanitize($id_field)." = ".((int) $id);
2464
2465 $resql = $this->db->query($sql);
2466 if ($resql) {
2467 if ($trigkey) {
2468 // call trigger with updated object values
2469 if (method_exists($this, 'fetch')) {
2470 $result = $this->fetch($id);
2471 } else {
2472 $result = $this->fetchCommon($id);
2473 }
2474
2475 $this->oldcopy = clone $this;
2476 if (property_exists($this->oldcopy, $field)) {
2477 $this->oldcopy->$field = $oldvalue;
2478 }
2479 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2480 $this->oldcopy->$propfield = $oldvalue;
2481 }
2482
2483 if (empty($this->context['actionmsgmore'])) {
2484 $this->context['actionmsgmore'] = 'Trigger called by setValueFrom';
2485 }
2486
2487 if ($result >= 0) {
2488 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2489 }
2490 if ($result < 0) {
2491 $error++;
2492 }
2493 } else {
2494 if (property_exists($this, $field)) {
2495 $this->$field = $value;
2496 }
2497 if ($propfield != $field && property_exists($this, $propfield)) {
2498 $this->$propfield = $value;
2499 }
2500 }
2501
2502 if (!$error) {
2503 $this->db->commit();
2504 return 1;
2505 } else {
2506 if (property_exists($this, $field)) {
2507 $this->$field = $oldvalue;
2508 }
2509 if ($propfield != $field && property_exists($this, $propfield)) {
2510 $this->$propfield = $oldvalue;
2511 }
2512 $this->db->rollback();
2513 return -2;
2514 }
2515 } else {
2516 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2517 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2518 } else {
2519 $this->error = $this->db->lasterror();
2520 }
2521 $this->db->rollback();
2522 return -1;
2523 }
2524 }
2525
2526 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2537 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2538 {
2539 // phpcs:enable
2540 global $conf, $user;
2541
2542 if (!$this->table_element) {
2543 dol_print_error(null, get_class($this)."::load_previous_next_ref was called on object with property table_element not defined");
2544 return -1;
2545 }
2546 if ($fieldid == 'none') {
2547 return 1;
2548 }
2549
2550 // For backward compatibility
2551 if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2552 $fieldid = 'titre';
2553 }
2554
2555 // Security on socid
2556 $socid = 0;
2557 if ($user->socid > 0) {
2558 $socid = $user->socid;
2559 }
2560
2561 // this->ismultientitymanaged contains
2562 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2563 $aliastablesociete = 's';
2564 if ($this->element == 'societe') {
2565 $aliastablesociete = 'te'; // te as table_element
2566 }
2567 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2568 $sql = "SELECT MAX(te.".$this->db->sanitize($fieldid).")";
2569 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2570 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2571 $tmparray = explode('@', $this->ismultientitymanaged);
2572 $sql .= ", ".$this->db->prefix().$this->db->sanitize($tmparray[1])." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2573 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2574 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2575 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2576 $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
2577 }
2578 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2579 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2580 }
2581 if ($fieldid == 'rowid') {
2582 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." < ".((int) $this->id);
2583 } elseif ($fieldid == 'label') {
2584 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." < '".$this->db->escape((string) $this->label)."'";
2585 } else { // Should be 'ref' or any other string field
2586 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." < '".$this->db->escape((string) $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2587 }
2588 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2589 $sql .= " AND sc.fk_user = ".((int) $user->id);
2590 }
2591 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2592 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2593 }
2594
2595 $filtermax = $filter;
2596
2597 // Manage filter
2598 $errormessage = '';
2599 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermax, $errormessage);
2600 if ($errormessage) {
2601 if (!preg_match('/^\s*AND/i', $filtermax)) {
2602 $sql .= " AND ";
2603 }
2604 $sql .= $filtermax; // @phan-suppress-current-line SqlInjection
2605 } else {
2606 $sql .= $tmpsql;
2607 }
2608
2609 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2610 $tmparray = explode('@', $this->ismultientitymanaged);
2611 $sql .= " AND te.".$this->db->sanitize($tmparray[0])." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2612 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2613 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2614 }
2615 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2616 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2617 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2618 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2619 } else {
2620 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2621 }
2622 } else {
2623 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2624 }
2625 }
2626 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2627 $tmparray = explode('@', $this->ismultientitymanaged);
2628 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2629 }
2630 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2631 $sql .= ' AND te.fk_soc = '.((int) $socid);
2632 }
2633 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2634 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2635 }
2636 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2637 $sql .= ' AND te.rowid = '.((int) $socid);
2638 }
2639 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2640
2641 $result = $this->db->query($sql);
2642 if (!$result) {
2643 $this->error = $this->db->lasterror();
2644 return -1;
2645 }
2646 $row = $this->db->fetch_row($result);
2647 $this->ref_previous = $row[0];
2648
2649 $sql = "SELECT MIN(te.".$this->db->sanitize($fieldid).")";
2650 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2651 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2652 $tmparray = explode('@', $this->ismultientitymanaged);
2653 $sql .= ", ".$this->db->prefix().$this->db->sanitize($tmparray[1])." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2654 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2655 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2656 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2657 $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
2658 }
2659 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2660 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2661 }
2662 if ($fieldid == 'rowid') {
2663 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." > ".((int) $this->id);
2664 } elseif ($fieldid == 'label') {
2665 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." > '".$this->db->escape((string) $this->label)."'";
2666 } else { // Should be 'ref' or any other string field
2667 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." > '".$this->db->escape((string) $this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2668 }
2669 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2670 $sql .= " AND (sc.fk_user = ".((int) $user->id);
2671 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
2672 $userschilds = $user->getAllChildIds();
2673 $sql .= " OR sc.fk_user IN (".$this->db->sanitize(implode(',', $userschilds)).")";
2674 }
2675 $sql .= ')';
2676 }
2677 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2678 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2679 }
2680
2681 $filtermin = $filter;
2682
2683 // Manage filter
2684 $errormessage = '';
2685 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermin, $errormessage);
2686 if ($errormessage) {
2687 if (!preg_match('/^\s*AND/i', $filtermin)) {
2688 $sql .= " AND ";
2689 }
2690 $sql .= $filtermin; // @phan-suppress-current-line SqlInjection
2691
2692 $filtermin = '';
2693 } else {
2694 $sql .= $tmpsql;
2695 }
2696
2697 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2698 $tmparray = explode('@', $this->ismultientitymanaged);
2699 $sql .= " AND te.".$this->db->sanitize($tmparray[0])." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2700 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2701 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2702 }
2703 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2704 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2705 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2706 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2707 } else {
2708 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2709 }
2710 } else {
2711 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2712 }
2713 }
2714 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2715 $tmparray = explode('@', $this->ismultientitymanaged);
2716 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2717 }
2718 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2719 $sql .= ' AND te.fk_soc = '.((int) $socid);
2720 }
2721 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2722 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2723 }
2724 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2725 $sql .= ' AND te.rowid = '.((int) $socid);
2726 }
2727 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2728 // 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
2729
2730 $result = $this->db->query($sql);
2731 if (!$result) {
2732 $this->error = $this->db->lasterror();
2733 return -2;
2734 }
2735 $row = $this->db->fetch_row($result);
2736 $this->ref_next = $row[0];
2737
2738 return 1;
2739 }
2740
2741
2749 public function getListContactId($source = 'external')
2750 {
2751 $contactAlreadySelected = array();
2752 $tab = $this->liste_contact(-1, $source);
2753 $num = count($tab);
2754 $i = 0;
2755 while ($i < $num) {
2756 if ($source == 'thirdparty') {
2757 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2758 } else {
2759 $contactAlreadySelected[$i] = $tab[$i]['id'];
2760 }
2761 $i++;
2762 }
2763 return $contactAlreadySelected;
2764 }
2765
2766
2774 public function setProject($projectid, $notrigger = 0)
2775 {
2776 global $user;
2777 $error = 0;
2778
2779 if (!$this->table_element) {
2780 dol_syslog(get_class($this)."::setProject was called on object with property table_element not defined", LOG_ERR);
2781 return -1;
2782 }
2783
2784 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2785 if ($this->table_element == 'actioncomm') { // Special case for actioncomm
2786 if ($projectid) {
2787 $sql .= " SET fk_project = ".((int) $projectid);
2788 } else {
2789 $sql .= " SET fk_project = NULL";
2790 }
2791 $sql .= ' WHERE id = '.((int) $this->id);
2792 // @phan-suppress-next-line PhanTypeMismatchProperty
2793 } elseif (!empty($this->fields['fk_project'])) { // Common case
2794 if ($projectid) {
2795 $sql .= " SET fk_project = ".((int) $projectid);
2796 } else {
2797 $sql .= " SET fk_project = NULL";
2798 }
2799 $sql .= ' WHERE rowid = '.((int) $this->id);
2800 } else { // Special case for old architecture objects
2801 if ($projectid) {
2802 $sql .= ' SET fk_projet = '.((int) $projectid);
2803 } else {
2804 $sql .= ' SET fk_projet = NULL';
2805 }
2806 $sql .= " WHERE rowid = ".((int) $this->id);
2807 }
2808
2809 $this->db->begin();
2810
2811 dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2812 if ($this->db->query($sql)) {
2813 $this->fk_project = ((int) $projectid);
2814 } else {
2815 dol_print_error($this->db);
2816 $error++;
2817 }
2818
2819 // Triggers
2820 if (!$error && !$notrigger) {
2821 // Call triggers
2822 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2823 if ($result < 0) {
2824 $error++;
2825 } //Do also here what you must do to rollback action if trigger fail
2826 // End call triggers
2827 }
2828
2829 // Commit or rollback
2830 if ($error) {
2831 $this->db->rollback();
2832 return -1;
2833 } else {
2834 $this->db->commit();
2835 return 1;
2836 }
2837 }
2838
2845 public function setPaymentMethods($id)
2846 {
2847 global $user;
2848
2849 $error = 0;
2850 $notrigger = 0;
2851
2852 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2853
2854 if ($this->status >= 0 || $this->element == 'societe') {
2855 $this->oldcopy = dol_clone($this, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
2856
2857 // TODO uniformize field name
2858 $fieldname = 'fk_mode_reglement';
2859 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
2860 if ($this->element == 'societe') {
2861 $fieldname = 'mode_reglement';
2862 $triggerName = 'COMPANY';
2863 }
2864 if (get_class($this) == 'Facture') {
2865 $triggerName = 'BILL';
2866 }
2867 if (get_class($this) == 'Fournisseur') {
2868 $fieldname = 'mode_reglement_supplier';
2869 $triggerName = 'BILL_SUPPLIER';
2870 }
2871 if (get_class($this) == 'Tva') {
2872 $fieldname = 'fk_typepayment';
2873 $triggerName = 'VAT';
2874 }
2875 if (get_class($this) == 'Salary') {
2876 $fieldname = 'fk_typepayment';
2877 }
2878
2879 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2880 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2881 $sql .= ' WHERE rowid = '.((int) $this->id);
2882
2883 if ($this->db->query($sql)) {
2884 $this->mode_reglement_id = $id;
2885 // for supplier
2886 if (get_class($this) == 'Fournisseur') {
2887 $this->mode_reglement_supplier_id = $id;
2888 }
2889
2890 // Triggers
2891 if (!$error && !$notrigger) {
2892 // Call triggers
2893 $result = $this->call_trigger($triggerName.'_MODIFY', $user);
2894 if ($result < 0) {
2895 $error++;
2896 }
2897 // End call triggers
2898 }
2899 return 1;
2900 } else {
2901 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2902 $this->error = $this->db->error();
2903 return -1;
2904 }
2905 } else {
2906 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2907 $this->error = 'Status of the object is incompatible '.$this->status;
2908 return -2;
2909 }
2910 }
2911
2918 public function setMulticurrencyCode($code)
2919 {
2920 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2921 if ($this->status >= 0 || $this->element == 'societe') {
2922 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2923 $sql .= " SET multicurrency_code = '".$this->db->escape($code)."'";
2924 $sql .= ' WHERE rowid='.((int) $this->id);
2925
2926 if ($this->db->query($sql)) {
2927 $this->multicurrency_code = $code;
2928
2929 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2930 if ($rate) {
2931 $this->setMulticurrencyRate($rate, 2);
2932 }
2933
2934 return 1;
2935 } else {
2936 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2937 $this->error = $this->db->error();
2938 return -1;
2939 }
2940 } else {
2941 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2942 $this->error = 'Status of the object is incompatible '.$this->status;
2943 return -2;
2944 }
2945 }
2946
2954 public function setMulticurrencyRate($rate, $mode = 1)
2955 {
2956 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.', '.$mode.')');
2957 if ($this->status >= 0 || $this->element == 'societe') {
2958 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2959 $sql .= " SET multicurrency_tx = ".((float) $rate);
2960 $sql .= ' WHERE rowid='.((int) $this->id);
2961
2962 if ($this->db->query($sql)) {
2963 $this->multicurrency_tx = $rate;
2964
2965 // Update line price
2966 if (!empty($this->lines)) {
2967 foreach ($this->lines as &$line) {
2968 // A credit line (deposit, credit note, discount applied to the invoice) is not priced at the invoice rate:
2969 // both its amounts are the historical ones of the credit, so a rate change must leave it untouched.
2970 if (!empty($line->fk_remise_except)) {
2971 continue;
2972 }
2973
2974 // Amounts in company currency will be recalculated
2975 if ($mode == 1) {
2976 $line->subprice = 0;
2977 }
2978
2979 // Amounts in foreign currency will be recalculated
2980 if ($mode == 2) {
2981 $line->multicurrency_subprice = 0;
2982 }
2983
2984 switch ($this->element) {
2985 case 'propal':
2988 '@phan-var-force Propal $this';
2989 '@phan-var-force PropaleLigne $line';
2990 $this->updateline(
2991 $line->id,
2992 $line->subprice,
2993 $line->qty,
2994 $line->remise_percent,
2995 $line->tva_tx,
2996 $line->localtax1_tx,
2997 $line->localtax2_tx,
2998 ($line->description ? $line->description : $line->desc),
2999 'HT',
3000 $line->info_bits,
3001 $line->special_code,
3002 $line->fk_parent_line,
3003 $line->skip_update_total,
3004 $line->fk_fournprice,
3005 $line->pa_ht,
3006 $line->label,
3007 $line->product_type,
3008 $line->date_start,
3009 $line->date_end,
3010 $line->array_options,
3011 $line->fk_unit,
3012 $line->multicurrency_subprice
3013 );
3014 break;
3015 case 'commande':
3018 '@phan-var-force Commande $this';
3019 '@phan-var-force OrderLine $line';
3020 $this->updateline(
3021 $line->id,
3022 ($line->description ? $line->description : $line->desc),
3023 $line->subprice,
3024 $line->qty,
3025 $line->remise_percent,
3026 $line->tva_tx,
3027 $line->localtax1_tx,
3028 $line->localtax2_tx,
3029 'HT',
3030 $line->info_bits,
3031 $line->date_start,
3032 $line->date_end,
3033 $line->product_type,
3034 $line->fk_parent_line,
3035 $line->skip_update_total,
3036 $line->fk_fournprice,
3037 $line->pa_ht,
3038 $line->label,
3039 $line->special_code,
3040 $line->array_options,
3041 $line->fk_unit,
3042 $line->multicurrency_subprice
3043 );
3044 break;
3045 case 'facture':
3048 '@phan-var-force Facture $this';
3049 '@phan-var-force FactureLigne $line';
3050 $this->updateline(
3051 $line->id,
3052 ($line->description ? $line->description : $line->desc),
3053 $line->subprice,
3054 $line->qty,
3055 $line->remise_percent,
3056 $line->date_start,
3057 $line->date_end,
3058 $line->tva_tx,
3059 $line->localtax1_tx,
3060 $line->localtax2_tx,
3061 'HT',
3062 $line->info_bits,
3063 $line->product_type,
3064 $line->fk_parent_line,
3065 $line->skip_update_total,
3066 $line->fk_fournprice,
3067 $line->pa_ht,
3068 $line->label,
3069 $line->special_code,
3070 $line->array_options,
3071 $line->situation_percent,
3072 $line->fk_unit,
3073 $line->multicurrency_subprice
3074 );
3075 break;
3076 case 'facturerec':
3079 '@phan-var-force FactureRec $this';
3080 '@phan-var-force FactureLigneRec $line';
3081 $this->updateline(
3082 $line->id,
3083 ($line->description ? $line->description : $line->desc),
3084 $line->subprice,
3085 $line->qty,
3086 $line->tva_tx,
3087 $line->localtax1_tx,
3088 $line->localtax2_tx,
3089 $line->fk_product,
3090 $line->remise_percent,
3091 'HT',
3092 $line->info_bits,
3093 0,
3094 0,
3095 $line->product_type,
3096 $line->rang,
3097 $line->special_code,
3098 $line->label,
3099 $line->fk_unit,
3100 $line->multicurrency_subprice,
3101 0,
3102 $line->date_start,
3103 $line->date_end,
3104 $line->fk_fournprice,
3105 $line->pa_ht,
3106 $line->fk_parent_line
3107 );
3108 break;
3109 case 'supplier_proposal':
3112 '@phan-var-force SupplierProposal $this';
3113 '@phan-var-force SupplierProposalLine $line';
3114 $this->updateline(
3115 $line->id,
3116 $line->subprice,
3117 $line->qty,
3118 $line->remise_percent,
3119 $line->tva_tx,
3120 $line->localtax1_tx,
3121 $line->localtax2_tx,
3122 ($line->description ? $line->description : $line->desc),
3123 'HT',
3124 $line->info_bits,
3125 $line->special_code,
3126 $line->fk_parent_line,
3127 $line->skip_update_total,
3128 $line->fk_fournprice,
3129 $line->pa_ht,
3130 $line->label,
3131 $line->product_type,
3132 $line->array_options,
3133 $line->ref_fourn,
3134 (int) $line->fk_unit,
3135 $line->multicurrency_subprice
3136 );
3137 break;
3138 case 'order_supplier':
3141 '@phan-var-force CommandeFournisseur $this';
3142 '@phan-var-force CommandeFournisseurLigne $line';
3143 $this->updateline(
3144 $line->id,
3145 ($line->description ? $line->description : $line->desc),
3146 $line->subprice,
3147 $line->qty,
3148 $line->remise_percent,
3149 $line->tva_tx,
3150 $line->localtax1_tx,
3151 $line->localtax2_tx,
3152 'HT',
3153 $line->info_bits,
3154 $line->product_type,
3155 0,
3156 $line->date_start,
3157 $line->date_end,
3158 $line->array_options,
3159 $line->fk_unit,
3160 $line->multicurrency_subprice,
3161 $line->ref_supplier
3162 );
3163 break;
3164 case 'invoice_supplier':
3167 '@phan-var-force FactureFournisseur $this';
3168 '@phan-var-force SupplierInvoiceLIne $line';
3169 $this->updateline(
3170 $line->id,
3171 ($line->description ? $line->description : $line->desc),
3172 $line->subprice,
3173 $line->tva_tx,
3174 $line->localtax1_tx,
3175 $line->localtax2_tx,
3176 $line->qty,
3177 0,
3178 'HT',
3179 $line->info_bits,
3180 $line->product_type,
3181 $line->remise_percent,
3182 0,
3183 $line->date_start,
3184 $line->date_end,
3185 $line->array_options,
3186 $line->fk_unit,
3187 $line->multicurrency_subprice,
3188 $line->ref_supplier
3189 );
3190 break;
3191 default:
3192 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3193 break;
3194 }
3195 }
3196 }
3197
3198 return 1;
3199 } else {
3200 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
3201 $this->error = $this->db->error();
3202 return -1;
3203 }
3204 } else {
3205 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
3206 $this->error = 'Status of the object is incompatible '.$this->status;
3207 return -2;
3208 }
3209 }
3210
3218 public function setPaymentTerms($id, $deposit_percent = null)
3219 {
3220 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.formatLogObject($deposit_percent).')');
3221 if ($this->status >= 0 || $this->element == 'societe') {
3222 // TODO uniformize field name
3223 $fieldname = 'fk_cond_reglement';
3224 if ($this->element == 'societe') {
3225 $fieldname = 'cond_reglement';
3226 }
3227 if (get_class($this) == 'Fournisseur') {
3228 $fieldname = 'cond_reglement_supplier';
3229 }
3230
3231 if (empty($deposit_percent) || $deposit_percent < 0) {
3232 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
3233 }
3234
3235 if ($deposit_percent > 100) {
3236 $deposit_percent = 100;
3237 }
3238
3239 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3240 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3241 if (in_array($this->table_element, array('propal', 'commande', 'supplier_proposal', 'commande_fournisseur', 'societe'))) {
3242 $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape((string) $deposit_percent)."'");
3243 }
3244 $sql .= ' WHERE rowid = '.((int) $this->id);
3245
3246 if ($this->db->query($sql)) {
3247 $this->cond_reglement_id = $id;
3248 // for supplier
3249 if (get_class($this) == 'Fournisseur') {
3250 $this->cond_reglement_supplier_id = $id;
3251 }
3252 $this->deposit_percent = $deposit_percent;
3253 return 1;
3254 } else {
3255 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
3256 $this->error = $this->db->error();
3257 return -1;
3258 }
3259 } else {
3260 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
3261 $this->error = 'Status of the object is incompatible '.$this->status;
3262 return -2;
3263 }
3264 }
3265
3272 public function setTransportMode($id)
3273 {
3274 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
3275 if ($this->status >= 0 || $this->element == 'societe') {
3276 $fieldname = 'fk_transport_mode';
3277 if ($this->element == 'societe') {
3278 $fieldname = 'transport_mode';
3279 }
3280 if (get_class($this) == 'Fournisseur') {
3281 $fieldname = 'transport_mode_supplier';
3282 }
3283
3284 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3285 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3286 $sql .= ' WHERE rowid='.((int) $this->id);
3287
3288 if ($this->db->query($sql)) {
3289 $this->transport_mode_id = $id;
3290 // for supplier
3291 if (get_class($this) == 'Fournisseur') {
3292 $this->transport_mode_supplier_id = $id;
3293 }
3294 return 1;
3295 } else {
3296 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
3297 $this->error = $this->db->error();
3298 return -1;
3299 }
3300 } else {
3301 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
3302 $this->error = 'Status of the object is incompatible '.$this->status;
3303 return -2;
3304 }
3305 }
3306
3314 public function setDeliveryAddress($id)
3315 {
3316 $fieldname = 'fk_delivery_address';
3317 if ($this->element == 'delivery' || $this->element == 'shipping') {
3318 $fieldname = 'fk_address';
3319 }
3320
3321 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$this->db->sanitize($fieldname)." = ".((int) $id);
3322 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
3323
3324 if ($this->db->query($sql)) {
3325 $this->fk_delivery_address = $id;
3326 return 1;
3327 } else {
3328 $this->error = $this->db->error();
3329 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
3330 return -1;
3331 }
3332 }
3333
3334
3343 public function setShippingMethod($shipping_method_id, $notrigger = 0, $userused = null)
3344 {
3345 global $user;
3346
3347 if (empty($userused)) {
3348 $userused = $user;
3349 }
3350
3351 $error = 0;
3352
3353 if (!$this->table_element) {
3354 dol_syslog(get_class($this)."::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3355 return -1;
3356 }
3357
3358 $this->db->begin();
3359
3360 if ($shipping_method_id < 0) {
3361 $shipping_method_id = 'NULL';
3362 }
3363 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
3364
3365 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3366 $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
3367 $sql .= " WHERE rowid=".((int) $this->id);
3368 $resql = $this->db->query($sql);
3369 if (!$resql) {
3370 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
3371 $this->error = $this->db->lasterror();
3372 $error++;
3373 } else {
3374 if (!$notrigger) {
3375 // Call trigger
3376 $this->context = array('shippingmethodupdate' => 1);
3377 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3378 $result = $this->call_trigger($triggerPrefix.'_MODIFY', $userused);
3379 if ($result < 0) {
3380 $error++;
3381 }
3382 // End call trigger
3383 }
3384 }
3385 if ($error) {
3386 $this->db->rollback();
3387 return -1;
3388 } else {
3389 $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id;
3390 $this->db->commit();
3391 return 1;
3392 }
3393 }
3394
3395
3402 public function setWarehouse($warehouse_id)
3403 {
3404 if (!$this->table_element) {
3405 dol_syslog(get_class($this)."::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3406 return -1;
3407 }
3408 if ($warehouse_id < 0) {
3409 $warehouse_id = 'NULL';
3410 }
3411 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
3412
3413 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3414 $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
3415 $sql .= " WHERE rowid=".((int) $this->id);
3416
3417 if ($this->db->query($sql)) {
3418 $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id;
3419 return 1;
3420 } else {
3421 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
3422 $this->error = $this->db->error();
3423 return 0;
3424 }
3425 }
3426
3427
3435 public function setDocModel($user, $modelpdf)
3436 {
3437 if (!$this->table_element) {
3438 dol_syslog(get_class($this)."::setDocModel was called on object with property table_element not defined", LOG_ERR);
3439 return -1;
3440 }
3441
3442 $newmodelpdf = dol_trunc($modelpdf, 255);
3443
3444 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3445 $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
3446 $sql .= " WHERE rowid = ".((int) $this->id);
3447
3448 dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
3449 $resql = $this->db->query($sql);
3450 if ($resql) {
3451 $this->model_pdf = $modelpdf;
3452 return 1;
3453 } else {
3454 dol_print_error($this->db);
3455 return 0;
3456 }
3457 }
3458
3459
3468 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
3469 {
3470 global $user;
3471
3472 if (empty($userused)) {
3473 $userused = $user;
3474 }
3475
3476 $error = 0;
3477
3478 if (!$this->table_element) {
3479 dol_syslog(get_class($this)."::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3480 return -1;
3481 }
3482 $this->db->begin();
3483
3484 if ($fk_account < 0) {
3485 $fk_account = 'NULL';
3486 }
3487 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3488
3489 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3490 $sql .= " SET fk_account = ".((int) $fk_account);
3491 $sql .= " WHERE rowid=".((int) $this->id);
3492
3493 $resql = $this->db->query($sql);
3494 if (!$resql) {
3495 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3496 $this->error = $this->db->lasterror();
3497 $error++;
3498 } else {
3499 if (!$notrigger) {
3500 // Call trigger
3501 $this->context['bankaccountupdate'] = 1;
3502
3503 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3504 $result = $this->call_trigger($triggerName . '_MODIFY', $userused);
3505 if ($result < 0) {
3506 $error++;
3507 }
3508 // End call trigger
3509 }
3510 }
3511 if ($error) {
3512 $this->db->rollback();
3513 return -1;
3514 } else {
3515 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
3516 $this->db->commit();
3517 return 1;
3518 }
3519 }
3520
3521
3522 // TODO: Move line related operations to CommonObjectLine?
3523
3524 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3534 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3535 {
3536 // phpcs:enable
3537 if (!$this->table_element_line) {
3538 dol_syslog(get_class($this)."::line_order was called on object with property table_element_line not defined", LOG_ERR);
3539 return -1;
3540 }
3541 if (!$this->fk_element) {
3542 dol_syslog(get_class($this)."::line_order was called on object with property fk_element not defined", LOG_ERR);
3543 return -1;
3544 }
3545
3546 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3547 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3548 $fieldposition = 'position';
3549 }
3550
3551 // Count number of lines to reorder (according to choice $renum)
3552 $nl = 0;
3553 $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3554 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3555 if (!$renum) {
3556 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = 0";
3557 }
3558 if ($renum) {
3559 $sql .= " AND " . $this->db->sanitize($fieldposition) . " <> 0";
3560 }
3561
3562 dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3563 $resql = $this->db->query($sql);
3564 if ($resql) {
3565 $row = $this->db->fetch_row($resql);
3566 $nl = $row[0];
3567 } else {
3568 dol_print_error($this->db);
3569 }
3570 if ($nl > 0) {
3571 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3572 $rows = array();
3573
3574 // We first search all lines that are parent lines (for multilevel details lines)
3575 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3576 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3577 if ($fk_parent_line) {
3578 $sql .= ' AND fk_parent_line IS NULL';
3579 }
3580 $sql .= " ORDER BY " . $this->db->sanitize($fieldposition) . " ASC, rowid " . $this->db->sanitize($rowidorder);
3581
3582 dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3583 $resql = $this->db->query($sql);
3584 if ($resql) {
3585 $i = 0;
3586 $num = $this->db->num_rows($resql);
3587 $grandchild = getDolGlobalInt('MAIN_CARE_GRANDCHILD');
3588 while ($i < $num) {
3589 $row = $this->db->fetch_row($resql);
3590 $rows[] = $row[0]; // Add parent line into array rows
3591 if ($fk_parent_line) {
3592 $children = $this->getChildrenOfLine($row[0], $grandchild);
3593 }
3594 if (!empty($children)) {
3595 foreach ($children as $child) {
3596 array_push($rows, $child);
3597 }
3598 }
3599 $i++;
3600 }
3601
3602 // Now we set a new number for each lines (parent and children with children included into parent tree)
3603 if (!empty($rows)) {
3604 foreach ($rows as $key => $row) {
3605 $this->updateRangOfLine($row, ($key + 1));
3606 }
3607 }
3608 } else {
3609 dol_print_error($this->db);
3610 }
3611 }
3612 return 1;
3613 }
3614
3622 public function getChildrenOfLine($id, $includealltree = 0)
3623 {
3624 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3625 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3626 $fieldposition = 'position';
3627 }
3628
3629 $rows = array();
3630
3631 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3632 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3633 $sql .= ' AND fk_parent_line = '.((int) $id);
3634 $sql .= " ORDER BY " . $this->db->sanitize($fieldposition) . " ASC";
3635
3636 dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3637
3638 $resql = $this->db->query($sql);
3639 if (!$resql || $this->db->num_rows($resql) <= 0) {
3640 return array();
3641 }
3642
3643 while ($row = $this->db->fetch_row($resql)) {
3644 $rows[] = $row[0];
3645 if (!empty($includealltree) && $includealltree <= 1000) { // Test <= 1000 is a protection in depth of recursive call to avoid infinite loop
3646 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree + 1));
3647 }
3648 }
3649 return $rows;
3650 }
3651
3652 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3660 public function line_up($rowid, $fk_parent_line = true)
3661 {
3662 // phpcs:enable
3663 $this->line_order(false, 'ASC', $fk_parent_line);
3664
3665 // Get rang of line
3666 $rang = $this->getRangOfLine($rowid);
3667
3668 // Update position of line
3669 $this->updateLineUp($rowid, $rang);
3670 }
3671
3672 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3680 public function line_down($rowid, $fk_parent_line = true)
3681 {
3682 // phpcs:enable
3683 $this->line_order(false, 'ASC', $fk_parent_line);
3684
3685 // Get rang of line
3686 $rang = $this->getRangOfLine($rowid);
3687
3688 // Get max value for rang
3689 $max = $this->line_max();
3690
3691 // Update position of line
3692 $this->updateLineDown($rowid, $rang, $max);
3693 }
3694
3702 public function updateRangOfLine($rowid, $rang)
3703 {
3704 global $hookmanager;
3705 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3706 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3707 $fieldposition = 'position';
3708 }
3709
3710 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldposition)." = ".((int) $rang);
3711 $sql .= ' WHERE rowid = '.((int) $rowid);
3712 if ($this->id > 0 && !empty($this->fk_element)) {
3713 // The line must belong to the object we reorder lines of
3714 $sql .= " AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3715 }
3716
3717 dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3718 if (!$this->db->query($sql)) {
3719 dol_print_error($this->db);
3720 return -1;
3721 }
3722
3723 $parameters = array('rowid' => $rowid, 'rang' => $rang, 'fieldposition' => $fieldposition);
3724 $action = '';
3725 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3726 return 1;
3727 }
3728
3729 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3736 public function line_ajaxorder($rows)
3737 {
3738 // phpcs:enable
3739 $num = count($rows);
3740 for ($i = 0; $i < $num; $i++) {
3741 $this->updateRangOfLine($rows[$i], ($i + 1));
3742 }
3743 }
3744
3752 public function updateLineUp($rowid, $rang)
3753 {
3754 if ($rang <= 1) {
3755 return -1;
3756 }
3757
3758 $fieldposition = 'rang';
3759 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3760 $fieldposition = 'position';
3761 }
3762
3763 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line)." SET ".$this->db->sanitize($fieldposition)." = ".((int) $rang);
3764 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3765 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = " . ((int) ($rang - 1));
3766 if (!$this->db->query($sql)) {
3767 $this->error = $this->db->lasterror();
3768 return -1;
3769 }
3770
3771 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldposition)." = ".((int) ($rang - 1));
3772 $sql .= ' WHERE rowid = '.((int) $rowid);
3773 if (!$this->db->query($sql)) {
3774 $this->error = $this->db->lasterror();
3775 return -1;
3776 }
3777
3778 return 1;
3779 }
3780
3789 public function updateLineDown($rowid, $rang, $max)
3790 {
3791 if ($rang >= $max) {
3792 return -1;
3793 }
3794
3795 $fieldposition = 'rang';
3796 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3797 $fieldposition = 'position';
3798 }
3799
3800 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line)." SET ".$this->db->sanitize($fieldposition)." = ".((int) $rang);
3801 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3802 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = " . ((int) ($rang + 1));
3803 if (!$this->db->query($sql)) {
3804 $this->error = $this->db->lasterror();
3805 return -1;
3806 }
3807
3808 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldposition)." = ".((int) ($rang + 1));
3809 $sql .= ' WHERE rowid = '.((int) $rowid);
3810 if (!$this->db->query($sql)) {
3811 $this->error = $this->db->lasterror();
3812 return -1;
3813 }
3814
3815 return 1;
3816 }
3817
3824 public function getRangOfLine($rowid)
3825 {
3826 $fieldposition = 'rang';
3827 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3828 $fieldposition = 'position';
3829 }
3830
3831 $sql = "SELECT " . $this->db->sanitize($fieldposition) . " FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3832 $sql .= " WHERE rowid = ".((int) $rowid);
3833
3834 dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3835 $resql = $this->db->query($sql);
3836 if (!$resql) {
3837 return 0;
3838 }
3839
3840 $row = $this->db->fetch_row($resql);
3841 return $row[0];
3842 }
3843
3850 public function getIdOfLine($rang)
3851 {
3852 $fieldposition = 'rang';
3853 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3854 $fieldposition = 'position';
3855 }
3856
3857 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3858 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3859 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = ".((int) $rang);
3860 $resql = $this->db->query($sql);
3861 if (!$resql) {
3862 return 0;
3863 }
3864
3865 $row = $this->db->fetch_row($resql);
3866 return $row[0];
3867 }
3868
3878 public function roundQtyToPackaging($qty, $packaging)
3879 {
3880 if (empty($packaging) || !is_numeric($packaging) || (float) $packaging <= 0) {
3881 return $qty;
3882 }
3883 $sign = ((float) $qty < 0 ? -1 : 1);
3884 $absqty = abs((float) $qty);
3885 if ($absqty < (float) $packaging) {
3886 return $sign * (float) $packaging;
3887 }
3888 if ((float) price2num($absqty - round($absqty / (float) $packaging) * (float) $packaging, 'MS') != 0) { // Not a multiple of the packaging (do not use fmod, it fails with decimal packaging)
3889 $coeff = intval($absqty / (float) $packaging) + 1;
3890 return $sign * (float) price2num((float) $packaging * $coeff, 'MS');
3891 }
3892 return $qty;
3893 }
3894
3895 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3902 public function line_max($fk_parent_line = 0)
3903 {
3904 // phpcs:enable
3905 $positionfield = 'rang';
3906 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3907 $positionfield = 'position';
3908 }
3909
3910 $sql = "SELECT max(".$this->db->sanitize($positionfield).") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3911 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3912
3913 // Search the last rang with fk_parent_line
3914 if ($fk_parent_line) {
3915 $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3916 }
3917
3918 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3919 $resql = $this->db->query($sql);
3920 if ($resql) {
3921 $row = $this->db->fetch_row($resql);
3922
3923 if ($fk_parent_line) {
3924 if (!empty($row[0])) {
3925 return $row[0];
3926 } else {
3927 return $this->getRangOfLine($fk_parent_line);
3928 }
3929 } else {
3930 return $row[0];
3931 }
3932 }
3933
3934 return 0;
3935 }
3936
3937 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3944 public function update_ref_ext($ref_ext)
3945 {
3946 // phpcs:enable
3947 if (!$this->table_element) {
3948 dol_syslog(get_class($this)."::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3949 return -1;
3950 }
3951
3952 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3953 $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3954 // @phan-suppress-next-line PhanUndeclaredProperty
3955 $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3956
3957 dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3958 if ($this->db->query($sql)) {
3959 $this->ref_ext = $ref_ext;
3960 return 1;
3961 } else {
3962 $this->error = $this->db->error();
3963 return -1;
3964 }
3965 }
3966
3967 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3976 public function update_note($note, $suffix = '', $notrigger = 0)
3977 {
3978 // phpcs:enable
3979 global $user;
3980
3981 if (!$this->table_element) {
3982 $this->error = 'update_note was called on object with property table_element not defined';
3983 dol_syslog(get_class($this)."::update_note was called on object with property table_element not defined", LOG_ERR);
3984 return -1;
3985 }
3986 if (!in_array($suffix, array('', '_public', '_private'))) {
3987 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3988 dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3989 return -2;
3990 }
3991
3992 $newsuffix = $suffix;
3993
3994 // Special case
3995 if ($this->table_element == 'product' && $newsuffix == '_private') {
3996 $newsuffix = '';
3997 }
3998 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3999 $fieldusermod = "fk_user_mod";
4000 } elseif ($this->table_element == 'ecm_files') {
4001 $fieldusermod = "fk_user_m";
4002 } else {
4003 $fieldusermod = "fk_user_modif";
4004 }
4005 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4006 $sql .= " SET note".$this->db->sanitize($newsuffix)." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
4007 $sql .= ", ".$this->db->sanitize($fieldusermod)." = ".((int) $user->id);
4008 $sql .= " WHERE rowid = ".((int) $this->id);
4009
4010 dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
4011 if ($this->db->query($sql)) {
4012 if ($suffix == '_public') {
4013 $this->note_public = $note;
4014 } elseif ($suffix == '_private') {
4015 $this->note_private = $note;
4016 } else {
4017 $this->note = $note; // deprecated
4018 $this->note_private = $note;
4019 }
4020 if (empty($notrigger)) {
4021 // TODO Use the $this->TRIGGER_PREFIX when implemented
4022 switch ($this->element) {
4023 case 'societe':
4024 $triggerName = 'COMPANY_MODIFY';
4025 break;
4026 case 'facture':
4027 $triggerName = 'BILL_MODIFY';
4028 break;
4029 case 'invoice_supplier':
4030 $triggerName = 'BILL_SUPPLIER_MODIFY';
4031 break;
4032 case 'facturerec':
4033 $triggerName = 'BILLREC_MODIFIY';
4034 break;
4035 case 'expensereport':
4036 $triggerName = 'EXPENSE_REPORT_MODIFY';
4037 break;
4038 default:
4039 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) . '_MODIFY';
4040 }
4041 $ret = $this->call_trigger($triggerName, $user);
4042 if ($ret < 0) {
4043 return -1;
4044 }
4045 }
4046 return 1;
4047 } else {
4048 $this->error = $this->db->lasterror();
4049 return -1;
4050 }
4051 }
4052
4053 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4062 public function update_note_public($note)
4063 {
4064 // phpcs:enable
4065 return $this->update_note($note, '_public');
4066 }
4067
4068 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4079 public function update_price($exclspec = 0, $roundingadjust = 'auto', $nodatabaseupdate = 0, $seller = null)
4080 {
4081 // phpcs:enable
4082 global $conf, $hookmanager, $action;
4083
4084 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
4085 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4086 if ($reshook > 0) {
4087 return 1; // replacement code
4088 } elseif ($reshook < 0) {
4089 return -1; // failure
4090 } // reshook = 0 => execute normal code
4091
4092 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
4093 $isElementForSupplier = false;
4094 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND'; // const for customer by default
4095 $MODULE = "";
4096 if ($this->element == 'propal') {
4097 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4098 } elseif ($this->element == 'commande' || $this->element == 'order') {
4099 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4100 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
4101 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4102 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
4103 $isElementForSupplier = true;
4104 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4105 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
4106 $isElementForSupplier = true;
4107 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4108 } elseif ($this->element == 'supplier_proposal') {
4109 $isElementForSupplier = true;
4110 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4111 }
4112 if ($isElementForSupplier) {
4113 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER'; // const for supplier
4114 }
4115
4116 if (!empty($MODULE)) {
4117 if (getDolGlobalString($MODULE)) {
4118 $modsactivated = explode(',', getDolGlobalString($MODULE));
4119 foreach ($modsactivated as $mod) {
4120 if (isModEnabled($mod)) {
4121 return 1; // update was disabled by specific setup
4122 }
4123 }
4124 }
4125 }
4126
4127 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4128
4129 $forcedroundingmode = $roundingadjust;
4130 if ($forcedroundingmode == 'auto' && isset($conf->global->{$roundTotalConstName})) {
4131 $forcedroundingmode = getDolGlobalString($roundTotalConstName);
4132 } elseif ($forcedroundingmode == 'auto') {
4133 $forcedroundingmode = '0';
4134 }
4135
4136 $error = 0;
4137
4138 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4139
4140 // Define constants to find lines to sum (field name into the table_element_line not into table_element)
4141 $fieldtva = 'total_tva';
4142 $fieldlocaltax1 = 'total_localtax1';
4143 $fieldlocaltax2 = 'total_localtax2';
4144 $fieldup = 'subprice';
4145 $base_price_type = 'HT';
4146 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
4147 $fieldtva = 'tva';
4148 $fieldup = 'pu_ht';
4149 }
4150 if ($this->element == 'invoice_supplier_rec') {
4151 $fieldup = 'pu_ht';
4152 }
4153 if ($this->element == 'expensereport') {
4154 // Force rounding mode to '0', otherwise when you set MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND to 1, you may have lines with different totals.
4155 // For example, if you have 2 lines with same TTC amounts (6,2 Unit price TTC and VAT rate 20%), on the first line you got 5,17 on HT total
4156 // and 5,16 on HT total and 1,04 on VAT total to get 6,20 on TTT total on second line (see #30051).
4157 $forcedroundingmode = '0';
4158 $fieldup = 'value_unit';
4159 $base_price_type = 'TTC';
4160 }
4161
4162 $sql = "SELECT rowid, qty, ".$this->db->sanitize($fieldup)." as up, remise_percent,";
4163 $sql .= " total_ht, ".$this->db->sanitize($fieldtva)." as total_tva, total_ttc, ".$this->db->sanitize($fieldlocaltax1)." as total_localtax1, ".$this->db->sanitize($fieldlocaltax2)." as total_localtax2,";
4164 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4165 $sql .= ' info_bits, product_type,';
4166 if ($this->element == 'expensereport') {
4167 $sql .= ' comments as description';
4168 } else {
4169 $sql .= ' description';
4170 }
4171 if ($this->table_element_line == 'facturedet') {
4172 $sql .= ', situation_percent';
4173 }
4174 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4175 $sql .= " FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4176 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4177 if ($exclspec) {
4178 $product_field = 'product_type';
4179 if ($this->table_element_line == 'contratdet') {
4180 $product_field = ''; // contratdet table has no product_type field
4181 }
4182 if ($product_field) {
4183 $sql .= " AND ".$this->db->sanitize($product_field)." <> 9";
4184 }
4185 }
4186 $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
4187
4188 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4189
4190 $resql = $this->db->query($sql);
4191 if ($resql) {
4192 $this->total_ht = 0;
4193 $this->total_tva = 0;
4194 $this->total_localtax1 = 0;
4195 $this->total_localtax2 = 0;
4196 $this->total_ttc = 0;
4197 $total_ht_by_vats = array();
4198 $total_tva_by_vats = array();
4199 $total_ttc_by_vats = array();
4200 $this->multicurrency_total_ht = 0;
4201 $this->multicurrency_total_tva = 0;
4202 $this->multicurrency_total_ttc = 0;
4203
4204 $this->db->begin();
4205
4206 $num = $this->db->num_rows($resql);
4207 $i = 0;
4208 while ($i < $num) {
4209 $obj = $this->db->fetch_object($resql);
4210
4211 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = '0'
4212 $parameters = array('fk_element' => $obj->rowid);
4213 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4214
4215 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'
4216 // This part of code is to fix data. We should not call it too often.
4217 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4218 $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);
4219
4220 $diff_when_using_price_ht = price2num((float) $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.
4221 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
4222 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
4223 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
4224
4225 if ($diff_on_current_total) {
4226 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
4227 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line;
4228 $sqlfix .= " SET ".$this->db->sanitize($fieldtva)." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2]);
4229 $sqlfix .= ", multicurrency_total_tva = ".price2num((float) $tmpcal[17]).", multicurrency_total_ttc = ".price2num((float) $tmpcal[18]);
4230 $sqlfix .= " WHERE rowid = ".((int) $obj->rowid);
4231 dol_syslog('Warn1: 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);
4232 $resqlfix = $this->db->query($sqlfix);
4233 if (!$resqlfix) {
4234 dol_print_error($this->db, 'Failed to update line');
4235 }
4236 $obj->total_tva = $tmpcal[1];
4237 $obj->total_ttc = $tmpcal[2];
4238 $obj->multicurrency_total_tva = $tmpcal[17];
4239 $obj->multicurrency_total_ttc = $tmpcal[18];
4240 } elseif ($diff_when_using_price_ht) {
4241 // If total_ht calculated from unit price is different than the one in database, we do nothing, this may be a regular case to have also a different VAT, that can be explained
4242 // because price was entered included tax and we round the unit price without tax to store it in database (so recalculation will give different results),
4243 // so we continue only if price HT are same.
4244 if ((float) $tmpcal[0] == (float) $obj->total_ht) {
4245 // In rare cases, we can have the unit price that was not saved as original (like when adding a line from a discount of down payment). In this case, recalculation from unit price
4246 // will give different results than the one stored in database (the good one are the one in database and we must not fix anything).
4247 if ($obj->description != '(DEPOSIT)' && !getDolGlobalInt('MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4248 // After calculation from HT, totals sum of all part is consistent ($diff_on_current_total) + total_ht is same + we are not on a line with a bad unit amount + we have found a difference between VAT part calculated from unit price and the VAT part into database,
4249 // and we ask to force the use of rounding on line (like what we did on initial calculation) so this should not happen, so we force the update of line to fix this.
4250 // This part of code must be called only to fix corrupted data due to the use of the old feature to round total instead of rounding lines.
4251 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line;
4252 $sqlfix .= " SET ".$this->db->sanitize($fieldtva)." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2]);
4253 $sqlfix .= ", multicurrency_total_tva = ".price2num((float) $tmpcal[17]).", multicurrency_total_ttc = ".price2num((float) $tmpcal[18]);
4254 $sqlfix .= " WHERE rowid = ".((int) $obj->rowid);
4255
4256 dol_syslog('Warn2: 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);
4257
4258 $resqlfix = $this->db->query($sqlfix);
4259 if (!$resqlfix) {
4260 dol_print_error($this->db, 'Failed to update line');
4261 }
4262 $obj->total_tva = $tmpcal[1];
4263 $obj->total_ttc = $tmpcal[2];
4264 $obj->multicurrency_total_tva = $tmpcal[17];
4265 $obj->multicurrency_total_ttc = $tmpcal[18];
4266 }
4267 }
4268 }
4269 }
4270
4271 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
4272 $this->total_tva += $obj->total_tva;
4273 $this->total_localtax1 += $obj->total_localtax1;
4274 $this->total_localtax2 += $obj->total_localtax2;
4275 $this->total_ttc += $obj->total_ttc;
4276 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
4277 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4278 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4279
4280 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4281 $total_ht_by_vats[$obj->vatrate] = 0;
4282 }
4283 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4284 $total_tva_by_vats[$obj->vatrate] = 0;
4285 }
4286 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4287 $total_ttc_by_vats[$obj->vatrate] = 0;
4288 }
4289 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4290 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4291 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4292
4293 if ($forcedroundingmode == '1') { // Check if we need adjustment onto line for vat. TODO This works on the company currency but not on foreign currency
4294 if ($base_price_type == 'TTC') {
4295 $tmpvat = price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate), 'MT', 1);
4296 } else {
4297 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
4298 }
4299 $diff = price2num($total_tva_by_vats[$obj->vatrate] - (float) $tmpvat, 'MT', 1);
4300 //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";
4301 if ($diff) {
4302 $maxdiff = (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)));
4303 if (abs((float) $diff) > $maxdiff) {
4304 // If error is more than 10 times the accuracy of rounding. This should not happen.
4305 $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.';
4306 dol_syslog($errmsg, LOG_WARNING);
4307 $this->error = $errmsg;
4308 $error++;
4309 break;
4310 }
4311
4312 if ($base_price_type == 'TTC') {
4313 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldtva)." = ".price2num($obj->total_tva - (float) $diff).", total_ht = ".price2num($obj->total_ht + (float) $diff)." WHERE rowid = ".((int) $obj->rowid);
4314 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_ht of line by running sqlfix = ".$sqlfix);
4315 } else {
4316 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldtva)." = ".price2num($obj->total_tva - (float) $diff).", total_ttc = ".price2num($obj->total_ttc - (float) $diff)." WHERE rowid = ".((int) $obj->rowid);
4317 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);
4318 }
4319
4320 $resqlfix = $this->db->query($sqlfix);
4321
4322 if (!$resqlfix) {
4323 dol_print_error($this->db, 'Failed to update line');
4324 }
4325
4326 $this->total_tva = (float) price2num($this->total_tva - (float) $diff, '', 1);
4327 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4328 if ($base_price_type == 'TTC') {
4329 $this->total_ht = (float) price2num($this->total_ht + (float) $diff, '', 1);
4330 $total_ht_by_vats[$obj->vatrate] = (float) price2num($total_ht_by_vats[$obj->vatrate] + (float) $diff, '', 1);
4331 } else {
4332 $this->total_ttc = (float) price2num($this->total_ttc - (float) $diff, '', 1);
4333 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4334 }
4335 }
4336 }
4337
4338 $i++;
4339 }
4340
4341 // Add revenue stamp to total
4342 // @phan-suppress-next-line PhanUndeclaredProperty
4343 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4344 // @phan-suppress-next-line PhanUndeclaredProperty
4345 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4346
4347 // Situations totals
4348 if (!empty($this->situation_cycle_ref) && !empty($this->situation_counter) && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) { // @phan-suppress-current-line PhanUndeclaredProperty
4349 '@phan-var-force Facture $this';
4350 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; // Note: possibly useless as $this is normally already Facture, so the class file should be loaded
4351 if ($this->type != Facture::TYPE_CREDIT_NOTE) { // @phpstan-ignore-line
4352 if (getDolGlobalInt('INVOICE_USE_SITUATION') != 2) {
4353 $prev_sits = $this->get_prev_sits();
4354
4355 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
4356 $this->total_ht -= $sit->total_ht;
4357 $this->total_tva -= $sit->total_tva;
4358 $this->total_localtax1 -= $sit->total_localtax1;
4359 $this->total_localtax2 -= $sit->total_localtax2;
4360 $this->total_ttc -= $sit->total_ttc;
4361 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4362 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4363 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4364 }
4365 }
4366 }
4367 }
4368
4369 // Clean total
4370 $this->total_ht = (float) price2num($this->total_ht);
4371 $this->total_tva = (float) price2num($this->total_tva);
4372 $this->total_localtax1 = (float) price2num($this->total_localtax1);
4373 $this->total_localtax2 = (float) price2num($this->total_localtax2);
4374 $this->total_ttc = (float) price2num($this->total_ttc);
4375
4376 $this->db->free($resql);
4377
4378 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
4379 $fieldht = 'total_ht';
4380 $fieldtva = 'tva';
4381 $fieldlocaltax1 = 'localtax1';
4382 $fieldlocaltax2 = 'localtax2';
4383 $fieldttc = 'total_ttc';
4384 // Specific code for backward compatibility with old field names
4385 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
4386 $fieldtva = 'total_tva';
4387 }
4388
4389 if (!$error && empty($nodatabaseupdate)) {
4390 $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
4391 $sql .= " ".$this->db->sanitize($fieldht)." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
4392 $sql .= " ".$this->db->sanitize($fieldtva)." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
4393 $sql .= " ".$this->db->sanitize($fieldlocaltax1)." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
4394 $sql .= " ".$this->db->sanitize($fieldlocaltax2)." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
4395 $sql .= " ".$this->db->sanitize($fieldttc)." = ".((float) price2num($this->total_ttc, 'MT', 1));
4396 $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
4397 $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
4398 $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
4399 $sql .= " WHERE rowid = ".((int) $this->id);
4400
4401 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4402 $resql = $this->db->query($sql);
4403
4404 if (!$resql) {
4405 $error++;
4406 $this->error = $this->db->lasterror();
4407 $this->errors[] = $this->db->lasterror();
4408 }
4409 }
4410
4411 if (!$error) {
4412 $this->db->commit();
4413 return 1;
4414 } else {
4415 $this->db->rollback();
4416 return -1;
4417 }
4418 } else {
4419 dol_print_error($this->db, 'Bad request in update_price');
4420 return -1;
4421 }
4422 }
4423
4424 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4435 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
4436 {
4437 // phpcs:enable
4438 global $user, $hookmanager, $action;
4439 dol_syslog(__METHOD__, LOG_DEBUG);
4440
4441 if (empty($this->origin_type) && !empty($this->origin)) {
4442 $this->origin_type = $this->origin;
4443 }
4444 $origin = (!empty($origin) ? $origin : $this->origin_type);
4445 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4446 $f_user = isset($f_user) ? $f_user : $user;
4447
4448 // Special case
4449 if ($origin == 'order') {
4450 $origin = 'commande';
4451 }
4452 if ($origin == 'invoice') {
4453 $origin = 'facture';
4454 }
4455 if ($origin == 'invoice_template') {
4456 $origin = 'facturerec';
4457 }
4458 if ($origin == 'supplierorder') {
4459 $origin = 'order_supplier';
4460 }
4461
4462 // Add module part to target type
4463 $targettype = $this->getElementType();
4464
4465 $parameters = array('targettype' => $targettype);
4466 // Hook for explicitly set the targettype if it must be different than $this->element
4467 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4468 if ($reshook > 0) {
4469 if (!empty($hookmanager->resArray['targettype'])) {
4470 $targettype = $hookmanager->resArray['targettype'];
4471 }
4472 }
4473
4474 $this->db->begin();
4475 $error = 0;
4476
4477 $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
4478 $sql .= "fk_source";
4479 $sql .= ", sourcetype";
4480 $sql .= ", fk_target";
4481 $sql .= ", targettype";
4482 $sql .= ") VALUES (";
4483 $sql .= ((int) $origin_id);
4484 $sql .= ", '" . $this->db->escape($origin) . "'";
4485 $sql .= ", " . ((int) $this->id);
4486 $sql .= ", '" . $this->db->escape($targettype) . "'";
4487 $sql .= ")";
4488
4489 dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
4490 if ($this->db->query($sql)) {
4491 // If we link a supplier order to a supplier invoice that already uses discounts coming from other supplier invoices
4492 // (deposit invoice / credit note used as payment), also link those source invoices to the same supplier order.
4493 // This helps keep "linked elements" consistent when totals are impacted by such discounts.
4494 if ($origin === 'order_supplier' && $targettype === 'invoice_supplier' && $this->element === 'invoice_supplier' && (int) $origin_id > 0 && (int) $this->id > 0) {
4495 $sourceinvoices = array();
4496
4497 $sqlsources = "SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4498 $sqlsources .= " FROM ".$this->db->prefix()."societe_remise_except as rc";
4499 $sqlsources .= " WHERE rc.fk_invoice_supplier = ".((int) $this->id);
4500 $sqlsources .= " AND rc.fk_invoice_supplier_source IS NOT NULL";
4501
4502 $resqlsources = $this->db->query($sqlsources);
4503 if ($resqlsources) {
4504 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4505 $srcid = (int) $objsrc->rowid;
4506 if ($srcid > 0 && $srcid !== (int) $this->id) {
4507 $sourceinvoices[$srcid] = $srcid;
4508 }
4509 }
4510 } else {
4511 dol_syslog(get_class($this)."::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4512 }
4513
4514 if (!empty($sourceinvoices)) {
4515 $existing = array();
4516 $sourcelist = implode(',', $sourceinvoices);
4517
4518 $sqlexists = "SELECT fk_target";
4519 $sqlexists .= " FROM ".$this->db->prefix()."element_element";
4520 $sqlexists .= " WHERE fk_source = ".((int) $origin_id);
4521 $sqlexists .= " AND sourcetype = '".$this->db->escape($origin)."'";
4522 $sqlexists .= " AND targettype = '".$this->db->escape($targettype)."'";
4523 $sqlexists .= " AND fk_target IN (".$this->db->sanitize($sourcelist).")";
4524
4525 $resqlexists = $this->db->query($sqlexists);
4526 if ($resqlexists) {
4527 while ($objexist = $this->db->fetch_object($resqlexists)) {
4528 $existing[(int) $objexist->fk_target] = 1;
4529 }
4530 } else {
4531 dol_syslog(get_class($this)."::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4532 }
4533
4534 foreach ($sourceinvoices as $srcid) {
4535 if (!empty($existing[(int) $srcid])) {
4536 continue;
4537 }
4538
4539 $sqladd = "INSERT INTO " . $this->db->prefix() . "element_element (fk_source, sourcetype, fk_target, targettype)";
4540 $sqladd .= " VALUES (".((int) $origin_id).", '".$this->db->escape($origin)."', ".((int) $srcid).", '".$this->db->escape($targettype)."')";
4541 $this->db->query($sqladd); // Best-effort: do not fail original link action
4542 }
4543 }
4544 }
4545
4546 if (!$notrigger) {
4547 // Call trigger
4548 $this->context['link_origin'] = $origin;
4549 $this->context['link_origin_id'] = $origin_id;
4550
4551 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user); // Note: We should have used here a hook. Not a business event
4552 if ($result < 0) {
4553 $error++;
4554 }
4555 // End call triggers
4556 }
4557 } else {
4558 $this->error = $this->db->lasterror();
4559 $error++;
4560 }
4561
4562 if (!$error) {
4563 $this->db->commit();
4564 return 1;
4565 } else {
4566 $this->db->rollback();
4567 return 0;
4568 }
4569 }
4570
4576 public function getElementType()
4577 {
4578 // 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.
4579 // 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).
4580 $coreModule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
4581 // Add module part to target type if object has $module property and isn't in core modules.
4582 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.'_' : '').$this->element;
4583 }
4584
4585
4608 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
4609 {
4610 global $hookmanager, $action;
4611
4612 // Important for pdf generation time reduction
4613 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
4614 // If you need to force the reload, you can call clearObjectLinkedCache() before calling fetchObjectLinked()
4615 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4616 return 1;
4617 }
4618
4619 $this->linkedObjectsIds = array();
4620 $this->linkedObjects = array();
4621
4622 // Hook for allowing modules to completely alter the behavior of the method
4623 $parameters = array(
4624 'sourceid' => $sourceid,
4625 'sourcetype' => $sourcetype,
4626 'targetid' => $targetid,
4627 'targettype' => $targettype,
4628 'clause' => $clause,
4629 'alsosametype' => $alsosametype,
4630 'orderby' => $orderby,
4631 'loadalsoobjects' => $loadalsoobjects
4632 );
4633 $reshook = $hookmanager->executeHooks('fetchObjectLinked', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4634 if ($reshook > 0) {
4635 return $reshook;
4636 }
4637
4638 $justsource = false;
4639 $justtarget = false;
4640 $withtargettype = false;
4641 $withsourcetype = false;
4642
4643 // Hook for explicitly set the targettype if it must be differtent than $this->element
4644 if (is_object($hookmanager)) {
4645 $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
4646 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4647 if ($reshook > 0) {
4648 if (!empty($hookmanager->resArray['sourcetype'])) {
4649 $sourcetype = $hookmanager->resArray['sourcetype'];
4650 }
4651 if (!empty($hookmanager->resArray['sourceid'])) {
4652 $sourceid = $hookmanager->resArray['sourceid'];
4653 }
4654 if (!empty($hookmanager->resArray['targettype'])) {
4655 $targettype = $hookmanager->resArray['targettype'];
4656 }
4657 if (!empty($hookmanager->resArray['targetid'])) {
4658 $targetid = $hookmanager->resArray['targetid'];
4659 }
4660 }
4661 }
4662
4663 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4664 $justsource = true; // the source (id and type) is a search criteria
4665 if (!empty($targettype)) {
4666 $withtargettype = true;
4667 }
4668 }
4669 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4670 $justtarget = true; // the target (id and type) is a search criteria
4671 if (!empty($sourcetype)) {
4672 $withsourcetype = true;
4673 }
4674 }
4675
4676 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4677 $targetid = (!empty($targetid) ? $targetid : $this->id);
4678 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
4679 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
4680
4681 /*if (empty($sourceid) && empty($targetid))
4682 {
4683 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
4684 return -1;
4685 }*/
4686
4687 // Links between objects are stored in table element_element
4688 $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4689 $sql .= " FROM ".$this->db->prefix()."element_element";
4690 $sql .= " WHERE ";
4691 if ($justsource || $justtarget) {
4692 if ($justsource) {
4693 $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
4694 if ($withtargettype) {
4695 $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
4696 }
4697 } elseif ($justtarget) {
4698 $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
4699 if ($withsourcetype) {
4700 $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
4701 }
4702 }
4703 } else {
4704 $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
4705 $sql .= " ".$this->db->sanitize($clause)." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
4706 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
4707 $this->linkedObjectsFullLoaded[$this->id] = true;
4708 }
4709 }
4710 $sql .= $this->db->order($orderby);
4711
4712 dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
4713
4714 $resql = $this->db->query($sql);
4715 if ($resql) {
4716 $num = $this->db->num_rows($resql);
4717 $i = 0;
4718 while ($i < $num) {
4719 $obj = $this->db->fetch_object($resql);
4720 if ($justsource || $justtarget) {
4721 if ($justsource) {
4722 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4723 } elseif ($justtarget) {
4724 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4725 }
4726 } else {
4727 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4728 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4729 }
4730 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4731 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4732 }
4733 }
4734 $i++;
4735 }
4736
4737 if (!empty($this->linkedObjectsIds)) {
4738 $tmparray = $this->linkedObjectsIds;
4739 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4740 $element_properties = getElementProperties($objecttype);
4741 $element = $element_properties['element'];
4742 $classPath = $element_properties['classpath'];
4743 $classFile = $element_properties['classfile'];
4744 $className = $element_properties['classname'];
4745 $module = $element_properties['module'];
4746
4747 // Here $module, $classFile and $className are set, we can use them.
4748 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4749 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4750 dol_include_once('/'.$classPath.'/'.$classFile.'.class.php');
4751 if (class_exists($className)) {
4752 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4753 $object = new $className($this->db);
4754 '@phan-var-force CommonObject $object';
4755 $ret = $object->fetch($objectid);
4756 if ($ret > 0) {
4757 $this->linkedObjects[$objecttype][$i] = $object;
4758 }
4759 }
4760 }
4761 }
4762 } else {
4763 unset($this->linkedObjectsIds[$objecttype]);
4764 }
4765 }
4766 }
4767 return 1;
4768 } else {
4769 dol_print_error($this->db);
4770 return -1;
4771 }
4772 }
4773
4780 public function clearObjectLinkedCache()
4781 {
4782 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4783 unset($this->linkedObjectsFullLoaded[$this->id]);
4784 }
4785
4786 return 1;
4787 }
4788
4801 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4802 {
4803 global $user;
4804 $updatesource = false;
4805 $updatetarget = false;
4806 $f_user = isset($f_user) ? $f_user : $user;
4807 dol_syslog(__METHOD__, LOG_DEBUG);
4808
4809 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4810 $updatesource = true;
4811 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4812 $updatetarget = true;
4813 }
4814
4815 $this->db->begin();
4816 $error = 0;
4817
4818 $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4819 if ($updatesource) {
4820 $sql .= "fk_source = " . ((int) $sourceid);
4821 $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4822 $sql .= " WHERE fk_target = " . ((int) $this->id);
4823 $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4824 } elseif ($updatetarget) {
4825 $sql .= "fk_target = " . ((int) $targetid);
4826 $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4827 $sql .= " WHERE fk_source = " . ((int) $this->id);
4828 $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4829 }
4830
4831 dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4832 if ($this->db->query($sql)) {
4833 if (!$notrigger) {
4834 // Call trigger
4835 $this->context['link_source_id'] = $sourceid;
4836 $this->context['link_source_type'] = $sourcetype;
4837 $this->context['link_target_id'] = $targetid;
4838 $this->context['link_target_type'] = $targettype;
4839
4840 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user); // Note: We should have used here a hook. Not a business event
4841 if ($result < 0) {
4842 $error++;
4843 }
4844 // End call triggers
4845 }
4846 } else {
4847 $this->error = $this->db->lasterror();
4848 $error++;
4849 }
4850
4851 if (!$error) {
4852 $this->db->commit();
4853 return 1;
4854 } else {
4855 $this->db->rollback();
4856 return -1;
4857 }
4858 }
4859
4873 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0)
4874 {
4875 global $user;
4876 $deletesource = false;
4877 $deletetarget = false;
4878 $f_user = isset($f_user) ? $f_user : $user;
4879
4880 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4881 $deletesource = true;
4882 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4883 $deletetarget = true;
4884 }
4885
4886 $element = $this->getElementType();
4887 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4888 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
4889 $targetid = (!empty($targetid) ? $targetid : $this->id);
4890 $targettype = (!empty($targettype) ? $targettype : $element);
4891 $this->db->begin();
4892 $error = 0;
4893
4894 if (!$notrigger) {
4895 // Call trigger
4896 $this->context['link_id'] = $rowid;
4897 $this->context['link_source_id'] = $sourceid;
4898 $this->context['link_source_type'] = $sourcetype;
4899 $this->context['link_target_id'] = $targetid;
4900 $this->context['link_target_type'] = $targettype;
4901
4902 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user); // Note: We should have used here a hook. Not a business event
4903 if ($result < 0) {
4904 $error++;
4905 }
4906 // End call triggers
4907 }
4908
4909 if (!$error) {
4910 $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4911 $sql .= " WHERE";
4912 if ($rowid > 0) {
4913 $sql .= " rowid = " . ((int) $rowid);
4914 } else {
4915 if ($deletesource) {
4916 $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4917 $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($element) . "'";
4918 } elseif ($deletetarget) {
4919 $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4920 $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($element) . "'";
4921 } else {
4922 $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($element) . "')";
4923 $sql .= " OR";
4924 $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($element) . "')";
4925 }
4926 }
4927
4928 dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4929 if (!$this->db->query($sql)) {
4930 $this->error = $this->db->lasterror();
4931 $this->errors[] = $this->error;
4932 $error++;
4933 }
4934 }
4935
4936 if (!$error) {
4937 $this->db->commit();
4938 return 1;
4939 } else {
4940 $this->db->rollback();
4941 return 0;
4942 }
4943 }
4944
4954 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4955 {
4956 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4957 return -1;
4958 }
4959 if (!preg_match('/^[_a-zA-Z0-9]+$/', $field_select)) {
4960 dol_syslog('Invalid value $field_select for parameter '.$field_select.' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4961 }
4962
4963 global $db;
4964
4965 $sql = "SELECT ".$db->sanitize($field_select)." FROM ".$db->prefix().$db->sanitize($table_element)." WHERE ".$db->sanitize($field_where)." = ".((int) $fk_object_where);
4966 $resql = $db->query($sql);
4967
4968 $TRes = array();
4969 if (!empty($resql)) {
4970 while ($res = $db->fetch_object($resql)) {
4971 $TRes[] = $res->{$field_select};
4972 }
4973 }
4974
4975 return $TRes;
4976 }
4977
4986 public static function getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4987 {
4988 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4989 return -1;
4990 }
4991
4992 global $db;
4993
4994 $sql = "SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element)." WHERE ".$db->sanitize($field_where)." = ".((int) $fk_object_where);
4995 $resql = $db->query($sql);
4996 $n = 0;
4997 if ($resql) {
4998 $res = $db->fetch_object($resql);
4999 if ($res) {
5000 $n = $res->nb;
5001 }
5002 }
5003
5004 return $n;
5005 }
5006
5015 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
5016 {
5017 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5018 return -1;
5019 }
5020
5021 global $db;
5022
5023 $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$db->sanitize($field_where)." = ".((int) $fk_object_where);
5024 $resql = $db->query($sql);
5025
5026 if (empty($resql)) {
5027 return 0;
5028 }
5029
5030 return 1;
5031 }
5032
5044 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = '')
5045 {
5046 global $user;
5047
5048 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
5049
5050 $elementId = (!empty($elementId) ? $elementId : $this->id);
5051 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5052
5053 $this->db->begin();
5054
5055 if (empty($fieldstatus)) {
5056 if ($elementTable == 'facture_rec') {
5057 $fieldstatus = "suspended";
5058 }
5059 if ($elementTable == 'mailing') {
5060 $fieldstatus = "statut";
5061 }
5062 if ($elementTable == 'cronjob') {
5063 $fieldstatus = "status";
5064 }
5065 if ($elementTable == 'user') {
5066 $fieldstatus = "statut";
5067 }
5068 if ($elementTable == 'expensereport') {
5069 $fieldstatus = "fk_statut";
5070 }
5071 if ($elementTable == 'receptiondet_batch') {
5072 $fieldstatus = "status";
5073 }
5074 if ($elementTable == 'prelevement_bons') {
5075 $fieldstatus = "statut";
5076 }
5077 if ($elementTable == 'bank_account') {
5078 $fieldstatus = "clos";
5079 }
5080 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
5081 $fieldstatus = 'status';
5082 }
5083 // If still empty
5084 if (empty($fieldstatus)) {
5085 $fieldstatus = 'fk_statut';
5086 }
5087 }
5088
5089 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5090 $sql .= " SET ".$this->db->sanitize($fieldstatus)." = ".((int) $status);
5091 // If status = 1 = validated and we update the main status field, we can update also fk_user_valid
5092 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields and on $fieldstatus
5093 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
5094 $sql .= ", fk_user_valid = ".((int) $user->id);
5095 }
5096 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
5097 $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
5098 }
5099 if ($status == 1 && in_array($elementTable, array('inventory'))) {
5100 $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
5101 }
5102 $sql .= " WHERE rowid = ".((int) $elementId);
5103 $sql .= " AND ".$this->db->sanitize($fieldstatus)." <> ".((int) $status); // We avoid update if status already correct
5104
5105 dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
5106 $resql = $this->db->query($sql);
5107 if ($resql) {
5108 $error = 0;
5109
5110 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
5111
5112 if ($nb_rows_affected > 0) {
5113 if (empty($trigkey)) {
5114 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
5115 if ($this->element == 'supplier_proposal' && $status == 2) {
5116 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
5117 }
5118 if ($this->element == 'supplier_proposal' && $status == 3) {
5119 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
5120 }
5121 if ($this->element == 'supplier_proposal' && $status == 4) {
5122 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
5123 }
5124 if ($this->element == 'fichinter' && $status == 3) {
5125 $trigkey = 'FICHINTER_CLASSIFY_DONE';
5126 }
5127 if ($this->element == 'fichinter' && $status == 2) {
5128 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
5129 }
5130 if ($this->element == 'fichinter' && $status == 1) {
5131 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
5132 }
5133 }
5134
5135 $this->context = array_merge($this->context, array('newstatus' => $status));
5136
5137 if ($trigkey && $trigkey != 'none') {
5138 $this->oldcopy = dol_clone($this);
5139
5140 // Call trigger
5141 $result = $this->call_trigger($trigkey, $user);
5142 if ($result < 0) {
5143 $error++;
5144 }
5145 // End call triggers
5146 }
5147 } else {
5148 // The status was probably already good. We do nothing more, no triggers.
5149 }
5150
5151 if (!$error) {
5152 $this->db->commit();
5153
5154 if (empty($savElementId)) {
5155 // If the element we update is $this (so $elementId was provided as null)
5156 if ($fieldstatus == 'dispute_status') {
5157 $this->dispute_status = $status;
5158 } elseif ($fieldstatus == 'tosell') {
5159 $this->status = $status;
5160 } elseif ($fieldstatus == 'tobuy') {
5161 $this->status_buy = $status; // @phpstan-ignore-line
5162 } elseif ($fieldstatus == 'tobatch') {
5163 $this->status_batch = $status; // @phpstan-ignore-line
5164 } else {
5165 $this->status = $status;
5166 }
5167 }
5168
5169 return 1;
5170 } else {
5171 $this->db->rollback();
5172 dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
5173 return -1;
5174 }
5175 } else {
5176 $this->error = $this->db->lasterror();
5177 $this->db->rollback();
5178 return -1;
5179 }
5180 }
5181
5182
5190 public function getCanvas($id = 0, $ref = '')
5191 {
5192 if (empty($id) && empty($ref)) {
5193 return 0;
5194 }
5195 if (getDolGlobalString('MAIN_DISABLE_CANVAS')) {
5196 return 0; // To increase speed. Not enabled by default.
5197 }
5198
5199 // Clean parameters
5200 $ref = trim($ref);
5201
5202 $sql = "SELECT rowid, canvas";
5203 $sql .= " FROM ".$this->db->prefix().$this->table_element;
5204 $sql .= " WHERE entity IN (".getEntity($this->element).")";
5205 if (!empty($id)) {
5206 $sql .= " AND rowid = ".((int) $id);
5207 }
5208 if (!empty($ref)) {
5209 $sql .= " AND ref = '".$this->db->escape($ref)."'";
5210 }
5211
5212 $resql = $this->db->query($sql);
5213 if ($resql) {
5214 $obj = $this->db->fetch_object($resql);
5215 if ($obj) {
5216 $this->canvas = $obj->canvas;
5217 return 1;
5218 } else {
5219 return 0;
5220 }
5221 } else {
5222 dol_print_error($this->db);
5223 return -1;
5224 }
5225 }
5226
5227
5234 public function getSpecialCode($lineid)
5235 {
5236 $sql = "SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5237 $sql .= " WHERE rowid = ".((int) $lineid);
5238 $resql = $this->db->query($sql);
5239 if ($resql) {
5240 $row = $this->db->fetch_row($resql);
5241 return (!empty($row[0]) ? $row[0] : 0);
5242 }
5243
5244 return 0;
5245 }
5246
5255 public function isObjectUsed($id = 0, $entity = 0)
5256 {
5257 global $langs;
5258
5259 if (empty($id)) {
5260 $id = $this->id;
5261 }
5262
5263 // Check parameters
5264 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5265 dol_print_error(null, 'Called isObjectUsed on a class with property this->childtables not defined');
5266 return -1;
5267 }
5268
5269 $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
5270 // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
5271 $tmparray = array_keys($this->childtables);
5272 if (is_numeric($tmparray[0])) {
5273 $arraytoscan = array_flip($this->childtables);
5274 }
5275
5276 // Test on all child tables to scan if child exists
5277 $haschild = 0;
5278 foreach ($arraytoscan as $table => $element) {
5279 //print $id.'-'.$table.'-'.$elementname.'<br>';
5280
5281 // Check if module is enabled (to avoid error if tables of module not created)
5282 if (isset($element['enabled']) && !empty($element['enabled'])) {
5283 $enabled = (int) dol_eval((string) $element['enabled'], 1);
5284 if (empty($enabled)) {
5285 continue;
5286 }
5287 }
5288
5289 // Check if element can be deleted
5290 $sql = "SELECT COUNT(*) as nb";
5291 $sql .= " FROM ".$this->db->prefix().$this->db->sanitize($table)." as c";
5292 if (!empty($element['parent']) && !empty($element['parentkey'])) {
5293 $sql .= ", ".$this->db->prefix().$this->db->sanitize($element['parent'])." as p";
5294 }
5295 if (!empty($element['fk_element'])) {
5296 $sql .= " WHERE c.".$this->db->sanitize($element['fk_element'])." = ".((int) $id);
5297 } else {
5298 $sql .= " WHERE c.".$this->db->sanitize($this->fk_element)." = ".((int) $id);
5299 }
5300 if (!empty($element['parent']) && !empty($element['parentkey'])) {
5301 $sql .= " AND c.".$this->db->sanitize($element['parentkey'])." = p.rowid";
5302 }
5303 if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
5304 $sql .= " AND c.".$this->db->sanitize($element['parenttypefield'])." = '".$this->db->escape($element['parenttypevalue'])."'";
5305 }
5306 if (!empty($entity)) {
5307 if (!empty($element['parent']) && !empty($element['parentkey'])) {
5308 $sql .= " AND p.entity = ".((int) $entity);
5309 } else {
5310 $sql .= " AND c.entity = ".((int) $entity);
5311 }
5312 }
5313 //var_dump($table, $element, $sql);
5314
5315 $resql = $this->db->query($sql);
5316 if ($resql) {
5317 $obj = $this->db->fetch_object($resql);
5318 if ($obj->nb > 0) {
5319 $langs->load("errors");
5320 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
5321 $haschild += (int) $obj->nb;
5322 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
5323 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5324 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
5325 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5326 } else { // new usage: $element['name']=Translation key
5327 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
5328 }
5329 break; // We found at least one, we stop here
5330 }
5331 } else {
5332 $this->errors[] = $this->db->lasterror();
5333 return -1;
5334 }
5335 }
5336
5337 if ($haschild > 0) {
5338 $this->errors[] = "ErrorRecordHasChildren";
5339 return $haschild;
5340 } else {
5341 return 0;
5342 }
5343 }
5344
5351 public function hasProductsOrServices($predefined = -1)
5352 {
5353 $nb = 0;
5354
5355 foreach ($this->lines as $key => $val) {
5356 $qualified = 0;
5357 if ($predefined == -1) {
5358 $qualified = 1;
5359 }
5360 if ($predefined == 1 && $val->fk_product > 0) {
5361 $qualified = 1;
5362 }
5363 if ($predefined == 0 && $val->fk_product <= 0) {
5364 $qualified = 1;
5365 }
5366 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5367 $qualified = 1;
5368 }
5369 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5370 $qualified = 1;
5371 }
5372 if ($qualified) {
5373 $nb++;
5374 }
5375 }
5376 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
5377 return $nb;
5378 }
5379
5385 public function getTotalDiscount()
5386 {
5387 if (!empty($this->table_element_line) && ($this->table_element_line != 'expeditiondet')) {
5388 $total_discount = 0.00;
5389
5390 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5391 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
5392 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
5393
5394 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
5395 $resql = $this->db->query($sql);
5396 if ($resql) {
5397 $num = $this->db->num_rows($resql);
5398 $i = 0;
5399 while ($i < $num) {
5400 $obj = $this->db->fetch_object($resql);
5401
5402 $pu_ht = $obj->pu_ht;
5403 $qty = $obj->qty;
5404 $total_ht = $obj->total_ht;
5405
5406 $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT');
5407 $total_discount += $total_discount_line;
5408
5409 $i++;
5410 }
5411 }
5412
5413 //print $total_discount; exit;
5414 return (float) price2num($total_discount);
5415 }
5416
5417 return null;
5418 }
5419
5420
5427 public function getTotalWeightVolume()
5428 {
5429 $totalWeight = 0;
5430 $totalVolume = 0;
5431 // defined for shipment only
5432 $totalOrdered = 0;
5433 // defined for shipment only
5434 $totalToShip = 0;
5435
5436 if (empty($this->lines)) {
5437 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5438 }
5439
5440 foreach ($this->lines as $line) {
5441 if (isset($line->qty_asked)) {
5442 $totalOrdered += $line->qty_asked; // defined for shipment only
5443 }
5444 if (isset($line->qty_shipped)) {
5445 $totalToShip += $line->qty_shipped; // defined for shipment only
5446 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
5447 if (empty($totalToShip)) {
5448 $totalToShip = 0;
5449 }
5450 $totalToShip += $line->qty; // defined for reception only
5451 }
5452
5453 // Define qty, weight, volume, weight_units, volume_units
5454 if ($this->element == 'shipping') {
5455 // for shipments
5456 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5457 } else {
5458 $qty = $line->qty ? $line->qty : 0;
5459 }
5460
5461 $weight = !empty($line->weight) ? $line->weight : 0;
5462 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5463 $volume = !empty($line->volume) ? $line->volume : 0;
5464 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5465
5466 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5467 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5468 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5469 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5470
5471 $weightUnit = 0;
5472 $volumeUnit = 0;
5473 if (!empty($weight_units)) {
5474 $weightUnit = $weight_units;
5475 }
5476 if (!empty($volume_units)) {
5477 $volumeUnit = $volume_units;
5478 }
5479
5480 if (empty($totalWeight)) {
5481 $totalWeight = 0; // Avoid warning because $totalWeight is ''
5482 }
5483 if (empty($totalVolume)) {
5484 $totalVolume = 0; // Avoid warning because $totalVolume is ''
5485 }
5486
5487 //var_dump($line->volume_units);
5488 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5489 $trueWeightUnit = pow(10, $weightUnit);
5490 $totalWeight += $weight * $qty * $trueWeightUnit;
5491 } else {
5492 if ($weight_units == 99) {
5493 // conversion 1 Pound = 0.45359237 KG
5494 $trueWeightUnit = 0.45359237;
5495 $totalWeight += $weight * $qty * $trueWeightUnit;
5496 } elseif ($weight_units == 98) {
5497 // conversion 1 Ounce = 0.0283495 KG
5498 $trueWeightUnit = 0.0283495;
5499 $totalWeight += $weight * $qty * $trueWeightUnit;
5500 } else {
5501 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
5502 }
5503 }
5504 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5505 //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
5506 $trueVolumeUnit = pow(10, $volumeUnit);
5507 //print $line->volume;
5508 $totalVolume += $volume * $qty * $trueVolumeUnit;
5509 } else {
5510 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
5511 }
5512 }
5513
5514 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5515 }
5516
5517
5523 public function setExtraParameters()
5524 {
5525 $this->db->begin();
5526
5527 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
5528 $extraparams = dol_trunc($extraparams, 250);
5529
5530 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
5531 $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
5532 $sql .= " WHERE rowid = ".((int) $this->id);
5533
5534 dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
5535 $resql = $this->db->query($sql);
5536 if (!$resql) {
5537 $this->error = $this->db->lasterror();
5538 $this->db->rollback();
5539 return -1;
5540 } else {
5541 $this->db->commit();
5542 return 1;
5543 }
5544 }
5545
5546
5547 // --------------------
5548 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
5549 // --------------------
5550
5551 /* This is to show add lines */
5552
5562 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
5563 {
5564 global $conf, $user, $langs, $object, $hookmanager, $extrafields, $form;
5565
5566 // Line extrafield
5567 if (!is_object($extrafields)) {
5568 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5569 $extrafields = new ExtraFields($this->db);
5570 }
5571 $extrafields->fetch_name_optionals_label($this->table_element_line);
5572
5573 // Output template part (modules that overwrite templates must declare this into descriptor)
5574 // Use global variables + $dateSelector + $seller and $buyer
5575 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
5576 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5577 foreach ($dirtpls as $module => $reldir) {
5578 if (!empty($module)) {
5579 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
5580 } else {
5581 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
5582 }
5583
5584 if (empty($conf->file->strict_mode)) {
5585 $res = @include $tpl;
5586 } else {
5587 $res = include $tpl; // for debug
5588 }
5589 if ($res) {
5590 break;
5591 }
5592 }
5593 }
5594
5595
5596
5597 /* This is to show array of line of details */
5598
5599
5614 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
5615 {
5616 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
5617 // TODO We should not use global var for this
5618 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5619
5620 // Define $usemargins (used by objectline_xxx.tpl.php files)
5621 $usemargins = 0;
5622 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
5623 $usemargins = 1;
5624 }
5625
5626 $num = count($this->lines);
5627
5628 // Line extrafield
5629 if (!is_object($extrafields)) {
5630 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5631 $extrafields = new ExtraFields($this->db);
5632 }
5633 $extrafields->fetch_name_optionals_label($this->table_element_line);
5634
5635 if (method_exists($this, 'loadExpeditions')) {
5636 // TODO No reason to have this here. This fill an array ->expeditions not used here. This can be called before going here of by the code that need it.
5637 $this->loadExpeditions();
5638 }
5639
5640 $parameters = array();
5641 $reshook = $hookmanager->executeHooks('printObjectLinesBlock', $parameters, $this, $action);
5642 if (empty($reshook)) {
5643 $parameters = array('num' => $num, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
5644 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5645 if (empty($reshook)) {
5646 // Output template part (modules that overwrite templates must declare this into descriptor)
5647 // Use global variables + $dateSelector + $seller and $buyer
5648 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
5649 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5650 foreach ($dirtpls as $module => $reldir) {
5651 $res = 0;
5652 if (!empty($module)) {
5653 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
5654 } else {
5655 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
5656 }
5657 if (file_exists($tpl)) {
5658 if (empty($conf->file->strict_mode)) {
5659 $res = @include $tpl;
5660 } else {
5661 $res = include $tpl; // for debug
5662 }
5663 }
5664 if ($res) {
5665 break;
5666 }
5667 }
5668 }
5669
5670 $i = 0;
5671
5672 print "<!-- begin printObjectLines() -->\n";
5673 foreach ($this->lines as $line) {
5674 // Line extrafield. TODO Remove this. extrafields should be already loaded.
5675 //$line->fetch_optionals();
5676
5677 if (is_object($hookmanager)) {
5678 if (empty($line->fk_parent_line)) {
5679 $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element, 'defaulttpldir' => $defaulttpldir);
5680 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5681 } else {
5682 $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);
5683 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5684 }
5685 }
5686 if (empty($reshook)) {
5687 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5688 }
5689
5690 $i++;
5691 }
5692 print "<!-- end printObjectLines() -->\n";
5693 }
5694 }
5695
5713 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
5714 {
5715 global $conf, $langs, $user, $object, $hookmanager; // used into tpl
5716 global $form;
5717 global $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
5718
5719 // var used into tpl
5720 $text = '';
5721 $description = '';
5722
5723 // Line in view mode
5724 if ($action != 'editline' || $selected != $line->id) {
5725 // Product
5726 if (!empty($line->fk_product) && $line->fk_product > 0) {
5727 $product_static = new Product($this->db);
5728 $product_static->fetch($line->fk_product);
5729
5730 $product_static->ref = (string) $line->ref; //can change ref in hook
5731 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5732
5733 $text = $product_static->getNomUrl(1);
5734
5735 // Define output language and label
5736 if (getDolGlobalInt('MAIN_MULTILANGS')) {
5737 // @phan-suppress-next-line PhanUndeclaredProperty
5738 if (property_exists($this, 'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
5739 dol_print_error(null, 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5740 return;
5741 }
5742
5743 $prod = new Product($this->db);
5744 $prod->fetch($line->fk_product);
5745
5746 $outputlangs = $langs;
5747 $newlang = '';
5748 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5749 $newlang = GETPOST('lang_id', 'aZ09');
5750 }
5751 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5752 $newlang = $this->thirdparty->default_lang; // To use language of customer
5753 }
5754 if (!empty($newlang)) {
5755 $outputlangs = new Translate("", $conf);
5756 $outputlangs->setDefaultLang($newlang);
5757 }
5758
5759 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5760 } else {
5761 $label = $line->product_label;
5762 }
5763
5764 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5765 $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.
5766 }
5767
5768 // Recalculate unit price with tax if not defined
5769 if (empty((float) $line->subprice_ttc) && $line->qty) { // subprice_ttc may be not stored on old version or not defined for lines with no unit price (like a discount)
5770 // So we calculate an estimated value just to show something on screen.
5771 // Not: the unit price is always for 100% of line, it is not a prorata of situation invoice (when total is)
5772 if ($line->remise_percent != 100) {
5773 $line->subprice_ttc = (float) price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100), 'MU');
5774 } else {
5775 // Other method is less accurate
5776 $line->subprice_ttc = (float) price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5777 }
5778 }
5779 $line->pu_ttc = $line->subprice_ttc; // deprecated
5780
5781 // Output template part (modules that overwrite templates must declare this into descriptor)
5782 // Use global variables + $dateSelector + $seller and $buyer
5783 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5784
5785 $qty_shipped = 0;
5786 if (isset($this->expeditions[$line->id])) {
5787 $qty_shipped = $this->expeditions[$line->id];
5788 }
5789 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
5790
5791 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5792 foreach ($dirtpls as $module => $reldir) {
5793 $res = 0;
5794 if (!empty($module)) {
5795 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5796 } else {
5797 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5798 }
5799 //var_dump($tpl);
5800 if (file_exists($tpl)) {
5801 if (empty($conf->file->strict_mode)) {
5802 $res = @include $tpl;
5803 } else {
5804 $res = include $tpl; // for debug
5805 }
5806 }
5807 if ($res) {
5808 break;
5809 }
5810 }
5811 }
5812
5813 // Line in update mode
5814 if ($this->status == 0 && $action == 'editline' && $selected == $line->id) {
5815 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5816
5817 $line->subprice_ttc = (float) price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5818 $line->pu_ttc = $line->subprice_ttc; // deprecated
5819
5820 // Output template part (modules that overwrite templates must declare this into descriptor)
5821 // Use global variables + $dateSelector + $seller and $buyer
5822 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5823 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5824 foreach ($dirtpls as $module => $reldir) {
5825 if (!empty($module)) {
5826 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5827 } else {
5828 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5829 }
5830
5831 if (empty($conf->file->strict_mode)) {
5832 $res = @include $tpl;
5833 } else {
5834 $res = include $tpl; // for debug
5835 }
5836 if ($res) {
5837 break;
5838 }
5839 }
5840 }
5841 }
5842
5843
5844 /* This is to show array of line of details of source object */
5845
5846
5857 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5858 {
5859 global $langs, $hookmanager, $form, $action;
5860
5861 print '<!-- printOriginLinesList '.get_class($this).' -->'."\n";
5862 print '<tr class="liste_titre">';
5863 print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5864 print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5865 print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5866 print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5867 if (isModEnabled("multicurrency")) {
5868 print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5869 }
5870 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5871 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5872 print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5873 }
5874 print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5875 print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5876 print '<td class="center">';
5877 print $form->showCheckAddButtons('checkforselect', 1);
5878 print '</td>';
5879 print '</tr>';
5880 $i = 0;
5881
5882 if (!empty($this->lines)) {
5883 foreach ($this->lines as $line) {
5884 $reshook = 0;
5885 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5886 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5887 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
5888 if (!empty($line->fk_parent_line)) {
5889 $parameters['fk_parent_line'] = $line->fk_parent_line;
5890 }
5891 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5892 }
5893 if (empty($reshook)) {
5894 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5895 }
5896
5897 $i++;
5898 }
5899 }
5900 }
5901
5915 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5916 {
5917 global $langs, $conf;
5918
5919 //var_dump($line);
5920 if (!empty($line->date_start)) {
5921 // @phan-suppress-next-line PhanUndeclaredProperty
5922 $date_start = $line->date_start;
5923 } else {
5924 $date_start = $line->date_debut_prevue;
5925 if ($line->date_debut_reel) {
5926 $date_start = $line->date_debut_reel;
5927 }
5928 }
5929 if (!empty($line->date_end)) {
5930 // @phan-suppress-next-line PhanUndeclaredProperty
5931 $date_end = $line->date_end;
5932 } else {
5933 $date_end = $line->date_fin_prevue;
5934 if ($line->date_fin_reel) {
5935 $date_end = $line->date_fin_reel;
5936 }
5937 }
5938
5939 // Set thevalue into ->tpl[] array.
5940 $this->tpl['id'] = $line->id;
5941
5942 $this->tpl['label'] = '';
5943 if (!empty($line->fk_parent_line)) {
5944 $this->tpl['label'] .= img_picto('', 'rightarrow.png');
5945 }
5946
5947 if (((int) $line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5948 $discount = new DiscountAbsolute($this->db);
5949 if (property_exists($this, 'socid')) {
5950 $discount->fk_soc = $this->socid;
5951 $discount->socid = $this->socid;
5952 }
5953 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5954 } elseif (!empty($line->fk_product)) {
5955 $productstatic = new Product($this->db);
5956 $productstatic->id = $line->fk_product;
5957 $productstatic->ref = (string) $line->ref;
5958 $productstatic->type = $line->fk_product_type;
5959 if (empty($productstatic->ref)) {
5960 $line->fetch_product();
5961 $productstatic = $line->product;
5962 }
5963
5964 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5965 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5966 // Dates
5967 if ($line->product_type == 1 && ($date_start || $date_end)) {
5968 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5969 }
5970 } else {
5971 $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans('Service'), 'service', 'class="pictofixedwidth"') : img_object($langs->trans('Product'), 'product', 'class="pictofixedwidth"')));
5972 if (!empty($line->desc)) {
5973 $this->tpl['label'] .= $line->desc;
5974 } else {
5975 $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5976 }
5977
5978 // Dates
5979 if ($line->product_type == 1 && ($date_start || $date_end)) {
5980 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5981 }
5982 }
5983
5984 if (!empty($line->desc)) {
5985 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5986 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5987 $discount = new DiscountAbsolute($this->db);
5988 $discount->fetch($line->fk_remise_except);
5989 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5990 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5991 $discount = new DiscountAbsolute($this->db);
5992 $discount->fetch($line->fk_remise_except);
5993 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5994 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5995 $discount = new DiscountAbsolute($this->db);
5996 $discount->fetch($line->fk_remise_except);
5997 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5998 } elseif ($line->desc == '(EXCESS PAID)') {
5999 $discount = new DiscountAbsolute($this->db);
6000 $discount->fetch($line->fk_remise_except);
6001 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
6002 } else {
6003 $this->tpl['description'] = dol_trunc($line->desc, 60);
6004 }
6005 } else {
6006 $this->tpl['description'] = '&nbsp;';
6007 }
6008
6009 // VAT Rate
6010 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
6011 $this->tpl['vat_rate'] .= (((int) $line->info_bits & 1) == 1) ? '*' : '';
6012 if (!empty($line->vat_src_code) && !preg_match('/\‍(/', $this->tpl['vat_rate'])) {
6013 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
6014 }
6015
6016 $this->tpl['price'] = price($line->subprice);
6017 $this->tpl['total_ht'] = price($line->total_ht);
6018 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
6019 $this->tpl['qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
6020 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
6021 $this->tpl['unit'] = $line->getLabelOfUnit('long', $langs);
6022 $this->tpl['unit_short'] = $line->getLabelOfUnit('short', $langs);
6023 //$this->tpl['unit_code'] = $line->getLabelOfUnit('code');
6024 }
6025 $this->tpl['remise_percent'] = (((int) $line->info_bits & 2) != 2) ? vatrate((string) $line->remise_percent, true) : '&nbsp;';
6026
6027 // Is the line strike or not
6028 $this->tpl['strike'] = 0;
6029 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
6030 $this->tpl['strike'] = 1;
6031 } elseif (defined('SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6032 // SUBTOTALS_SPECIAL_CODE is only defined when the subtotals module
6033 // is loaded (htdocs/subtotals/class/commonsubtotal.class.php:24).
6034 // Without the guard, printing origin lines from a PO into a vendor
6035 // invoice fatals (#37663). Other tpl files already follow this pattern.
6036 $this->tpl['strike'] = 1;
6037 }
6038
6039 // Output template part (modules that overwrite templates must declare this into descriptor)
6040 // Use global variables + $dateSelector + $seller and $buyer
6041 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
6042 foreach ($dirtpls as $module => $reldir) {
6043 if (!empty($module)) {
6044 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
6045 } else {
6046 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
6047 }
6048
6049 if (empty($conf->file->strict_mode)) {
6050 $res = @include $tpl;
6051 } else {
6052 $res = include $tpl; // for debug
6053 }
6054 if ($res) {
6055 break;
6056 }
6057 }
6058 }
6059
6060
6061 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6073 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0, $notrigger = 0)
6074 {
6075 // phpcs:enable
6076 global $user;
6077 $this->db->begin();
6078
6079 $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
6080 $sql .= "resource_id";
6081 $sql .= ", resource_type";
6082 $sql .= ", element_id";
6083 $sql .= ", element_type";
6084 $sql .= ", busy";
6085 $sql .= ", mandatory";
6086 $sql .= ") VALUES (";
6087 $sql .= ((int) $resource_id);
6088 $sql .= ", '".$this->db->escape($resource_type)."'";
6089 $sql .= ", '".$this->db->escape((string) $this->id)."'";
6090 $sql .= ", '".$this->db->escape($this->element)."'";
6091 $sql .= ", '".$this->db->escape((string) $busy)."'";
6092 $sql .= ", '".$this->db->escape((string) $mandatory)."'";
6093 $sql .= ")";
6094
6095 dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
6096 if ($this->db->query($sql)) {
6097 if (!$notrigger) {
6098 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).'_ADD_RESOURCE', $user);
6099 if ($result < 0) {
6100 $this->db->rollback();
6101 return -1;
6102 }
6103 }
6104 $this->db->commit();
6105 return 1;
6106 } else {
6107 $this->error = $this->db->lasterror();
6108 $this->db->rollback();
6109 return 0;
6110 }
6111 }
6112
6113 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6122 public function delete_resource($rowid, $element = '', $notrigger = 0)
6123 {
6124 // phpcs:enable
6125 global $user;
6126
6127 $this->db->begin();
6128
6129 $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
6130 $sql .= " WHERE rowid = ".((int) $rowid);
6131
6132 dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
6133
6134 $resql = $this->db->query($sql);
6135 if (!$resql) {
6136 $this->error = $this->db->lasterror();
6137 $this->db->rollback();
6138 return -1;
6139 } else {
6140 if (!$notrigger) {
6141 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).'_DELETE_RESOURCE', $user);
6142 if ($result < 0) {
6143 $this->db->rollback();
6144 return -1;
6145 }
6146 }
6147 $this->db->commit();
6148 return 1;
6149 }
6150 }
6151
6152
6158 public function __clone()
6159 {
6160 // Force a copy of this->lines, otherwise it will point to same object.
6161 if (isset($this->lines) && is_array($this->lines)) {
6162 $nboflines = count($this->lines);
6163 for ($i = 0; $i < $nboflines; $i++) {
6164 if (is_object($this->lines[$i])) {
6165 $this->lines[$i] = clone $this->lines[$i];
6166 }
6167 }
6168 }
6169 }
6170
6184 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
6185 {
6186 global $conf, $langs, $hookmanager, $action;
6187
6188 $srctemplatepath = '';
6189
6190 $parameters = array('modelspath' => $modelspath, 'modele' => $modele, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'hidedesc' => $hidedesc, 'hideref' => $hideref, 'moreparams' => $moreparams);
6191 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6192
6193 if (!empty($reshook)) {
6194 return $reshook;
6195 }
6196
6197 dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
6198
6199 if (empty($modele)) {
6200 $this->error = 'BadValueForParameterModele';
6201 return -1;
6202 }
6203
6204 // Increase limit for PDF build
6205 $err = error_reporting();
6206 error_reporting(0);
6207 @set_time_limit(120);
6208 error_reporting($err);
6209
6210 // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
6211 $tmp = explode(':', $modele, 2);
6212 $saved_model = $modele;
6213 if (!empty($tmp[1])) {
6214 $modele = $tmp[0];
6215 $srctemplatepath = $tmp[1];
6216
6217 if (!preg_match('/^'.preg_quote(DOL_DATA_ROOT, '/').'\/(ecm|doctemplates)/', $srctemplatepath)) {
6218 $this->error = 'BadDirForTemplateFile';
6219 return -1;
6220 }
6221 }
6222
6223 // Search template files
6224 $file = '';
6225 $classname = '';
6226 $filefound = '';
6227 $dirmodels = array('/');
6228 if (is_array($conf->modules_parts['models'])) {
6229 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
6230 }
6231 foreach ($dirmodels as $reldir) {
6232 foreach (array('doc', 'pdf') as $prefix) {
6233 if (in_array(get_class($this), array('Adherent'))) {
6234 // Member module use prefix_modele.class.php
6235 $file = $prefix."_".$modele.".class.php";
6236 } else {
6237 // Other module use prefix_modele.modules.php
6238 $file = $prefix."_".$modele.".modules.php";
6239 }
6240
6241 $file = dol_sanitizeFileName($file);
6242
6243 // We check if the file exists
6244 $file = dol_buildpath($reldir.$modelspath.$file, 0);
6245 if (file_exists($file)) {
6246 $filefound = $file;
6247 $classname = $prefix.'_'.$modele;
6248 break;
6249 }
6250 }
6251 if ($filefound) {
6252 break;
6253 }
6254 }
6255
6256 if ($filefound === '' || $classname === '') {
6257 $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
6258 $this->errors[] = $this->error;
6259 dol_syslog($this->error, LOG_ERR);
6260 return -1;
6261 }
6262
6263 // Sanitize $filefound
6264 $filefound = dol_sanitizePathName($filefound);
6265
6266 // If generator was found
6267 global $db; // Required to solve a conception error making an include of some code that uses $db instead of $this->db just after.
6268
6269 require_once $filefound;
6270
6271 $obj = new $classname($this->db);
6272
6273 // TODO: Check the following classes that seem possible for $obj, but removed for compatibility:
6274 // ModeleBankAccountDoc|ModeleExpenseReport|ModelePDFBom|ModelePDFCommandes|ModelePDFContract|
6275 // ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|
6276 // ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|
6277 // ModelePDFRecruitmentJobPosition|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|
6278 // ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePdfExpedition|ModelePdfReception|
6279 // ModelePDFStock|ModelePDFStockTransfer|
6280 // ModeleDon|ModelePDFTask|
6281 // ModelePDFAsset|ModelePDFTicket|ModelePDFUserGroup|ModeleThirdPartyDoc|ModelePDFUser
6282 // Has no write_file: ModeleBarCode|ModeleImports|ModeleExports|
6283 '@phan-var-force ModelePDFMember $obj';
6284 // '@phan-var-force ModelePDFMember|ModeleBarCode|ModeleDon|ModeleExports|ModeleImports|ModelePDFAsset|ModelePDFContract|ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|ModelePDFRecruitmentJobPosition|ModelePDFStock|ModelePDFStockTransfer|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePDFTask|ModelePDFTicket|ModelePDFUser|ModelePDFUserGroup|ModelePdfExpedition|ModelePdfReception|ModeleThirdPartyDoc $obj';
6285
6286 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
6287 if ($obj->type == 'odt' && empty($srctemplatepath)) {
6288 $varfortemplatedir = $obj->scandir;
6289 if ($varfortemplatedir && getDolGlobalString($varfortemplatedir)) {
6290 $dirtoscan = getDolGlobalString($varfortemplatedir);
6291
6292 $listoffiles = array();
6293
6294 // Now we add first model found in directories scanned
6295 $listofdir = explode(',', $dirtoscan);
6296 foreach ($listofdir as $key => $tmpdir) {
6297 $tmpdir = trim($tmpdir);
6298 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6299 if (!$tmpdir) {
6300 unset($listofdir[$key]);
6301 continue;
6302 }
6303 if (is_dir($tmpdir)) {
6304 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
6305 if (count($tmpfiles)) {
6306 $listoffiles = array_merge($listoffiles, $tmpfiles);
6307 }
6308 }
6309 }
6310
6311 if (count($listoffiles)) {
6312 foreach ($listoffiles as $record) {
6313 $srctemplatepath = $record['fullname'];
6314 break;
6315 }
6316 }
6317 }
6318
6319 if (empty($srctemplatepath)) {
6320 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6321 return -1;
6322 }
6323 }
6324
6325 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
6326 if (!dol_is_file($srctemplatepath)) {
6327 dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6328 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6329 return -1;
6330 }
6331 }
6332
6333 // We save charset_output to restore it because write_file can change it if needed for
6334 // output format that does not support UTF8.
6335 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
6336
6337 // update model_pdf in object
6338 $this->model_pdf = $saved_model;
6339
6340 try {
6341 if ($obj instanceof ModelePDFMember) {
6342 if ($this instanceof Adherent) {
6343 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards');
6344 } else {
6345 $resultwritefile = -1;
6346 dol_syslog("Error generating document - Provided ".get_class($this)." to ".get_class($obj)."::write_file()", LOG_ERR);
6347 }
6348 } elseif ($obj instanceof ModeleDon) {
6349 // Only 3 arguments
6350 if ($this instanceof Don) {
6351 $resultwritefile = $obj->write_file($this, $outputlangs /*, $currency */);
6352 } else {
6353 $resultwritefile = -1;
6354 dol_syslog("Error generating document - Provided ".get_class($this)." to Don::write_file()", LOG_ERR);
6355 }
6356 } else {
6357 // TODO: Try to set type above again
6358 '@phan-var-force ModeleBarCode|ModeleExports|ModeleImports|ModelePDFAsset|ModelePDFContract|ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|ModelePDFRecruitmentJobPosition|ModelePDFStock|ModelePDFStockTransfer|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePDFTask|ModelePDFTicket|ModelePDFUser|ModelePDFUserGroup|ModelePdfExpedition|ModelePdfReception|ModeleThirdPartyDoc $obj';
6359 $this->context['moreparams'] = $moreparams;
6360 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref); // @phan-suppress-current-line PhanTypeMismatchArgument
6361 }
6362 } catch (\Throwable $e) {
6363 $resultwritefile = -1;
6364 $this->error = $e->getMessage();
6365 dol_syslog("Exception in write_file() for ".get_class($this).": ".$e->getMessage(), LOG_ERR);
6366 }
6367 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
6368
6369
6370 if ($resultwritefile > 0) {
6371 $outputlangs->charset_output = $sav_charset_output;
6372
6373 // We delete old preview
6374 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6375 dol_delete_preview($this);
6376
6377 // Index file in database
6378 if (!empty($obj->result['fullpath'])) {
6379 $destfull = $obj->result['fullpath'];
6380
6381 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
6382 $update_main_doc_field = 0;
6383 if (!empty($obj->update_main_doc_field)) {
6384 $update_main_doc_field = 1;
6385 }
6386
6387 // Check that the file exists, before indexing it.
6388 // Hint: It does not exist, if we create a PDF and auto delete the ODT File
6389 if (dol_is_file($destfull)) {
6390 $this->indexFile($destfull, $update_main_doc_field);
6391 }
6392 } else {
6393 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);
6394 }
6395
6396 // Success in building document. We build meta file.
6397 dol_meta_create($this);
6398
6399 $this->warnings = $obj->warnings;
6400
6401 return 1;
6402 } else {
6403 $outputlangs->charset_output = $sav_charset_output;
6404 if (empty($this->error)) {
6405 $this->error = $obj->error;
6406 }
6407 if (empty($this->errors)) {
6408 $this->errors = $obj->errors;
6409 }
6410 $this->warnings = $obj->warnings;
6411 dol_syslog("Error generating document for ".__CLASS__.". Error: ".$this->error, LOG_ERR);
6412 return -1;
6413 }
6414 }
6415
6425 public function indexFile($destfull, $update_main_doc_field)
6426 {
6427 global $conf, $user;
6428
6429 $upload_dir = dirname($destfull);
6430 $destfile = basename($destfull);
6431 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
6432
6433 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
6434 $filename = basename($destfile);
6435 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
6436 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
6437
6438 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
6439 $ecmfile = new EcmFiles($this->db);
6440 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
6441
6442 // Set the public "share" key
6443 $setsharekey = false;
6444 if (
6445 !empty($this->TRIGGER_PREFIX)
6446 && (getDolGlobalInt($this->TRIGGER_PREFIX . "_ALLOW_EXTERNAL_DOWNLOAD") || getDolGlobalInt($this->TRIGGER_PREFIX . "_ALLOW_ONLINESIGN"))
6447 ) {
6448 $setsharekey = true;
6449 }
6450 // TODO Remove case covered by trigger prefix
6451 if ($this->element == 'propal' || $this->element == 'proposal') {
6452 if (getDolGlobalInt("PROPOSAL_ALLOW_ONLINESIGN")) {
6453 $setsharekey = true; // feature to make online signature is not set or set to on (default)
6454 }
6455 if (getDolGlobalInt("PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6456 $setsharekey = true;
6457 }
6458 }
6459 if ($this->element == 'facture' && getDolGlobalInt("INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6460 $setsharekey = true;
6461 }
6462 if ($this->element == 'bank_account' && getDolGlobalInt("BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6463 $setsharekey = true;
6464 }
6465 if ($this->element == 'contrat' && getDolGlobalInt("CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6466 $setsharekey = true;
6467 }
6468 if ($this->element == 'supplier_proposal' && getDolGlobalInt("SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6469 $setsharekey = true;
6470 }
6471 if ($this->element == 'order_supplier' && getDolGlobalInt("SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6472 $setsharekey = true;
6473 }
6474 if ($this->element == 'invoice_supplier' && getDolGlobalInt("SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6475 $setsharekey = true;
6476 }
6477 if ($this->element == 'societe_rib' && getDolGlobalInt("SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6478 $setsharekey = true;
6479 }
6480
6481 if ($setsharekey) {
6482 if (empty($ecmfile->share)) { // Because object not found or share not set yet
6483 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
6484 $ecmfile->share = getRandomPassword(true);
6485 }
6486 }
6487
6488 if ($result > 0) {
6489 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
6490 $ecmfile->fullpath_orig = '';
6491 $ecmfile->gen_or_uploaded = 'generated';
6492 $ecmfile->description = ''; // indexed content
6493 $ecmfile->keywords = ''; // keyword content
6494 $ecmfile->src_object_type = $this->table_element;
6495 $ecmfile->src_object_id = $this->id;
6496 $result = $ecmfile->update($user);
6497 if ($result < 0) {
6498 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
6499 return -1;
6500 }
6501 } else {
6502 $ecmfile->entity = $conf->entity;
6503 $ecmfile->filepath = $rel_dir;
6504 $ecmfile->filename = $filename;
6505 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
6506 $ecmfile->fullpath_orig = '';
6507 $ecmfile->gen_or_uploaded = 'generated';
6508 $ecmfile->description = ''; // indexed content
6509 $ecmfile->keywords = ''; // keyword content
6510 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
6511 $ecmfile->src_object_id = $this->id;
6512
6513 $result = $ecmfile->create($user);
6514 if ($result < 0) {
6515 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
6516 return -1;
6517 }
6518 }
6519
6520 /*$this->result['fullname']=$destfull;
6521 $this->result['filepath']=$ecmfile->filepath;
6522 $this->result['filename']=$ecmfile->filename;*/
6523 //var_dump($obj->update_main_doc_field);exit;
6524
6525 if ($update_main_doc_field && !empty($this->table_element)) {
6526 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
6527 $sql .= " WHERE rowid = ".((int) $this->id);
6528
6529 $resql = $this->db->query($sql);
6530 if (!$resql) {
6531 dol_print_error($this->db);
6532 return -1;
6533 } else {
6534 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
6535 }
6536 }
6537 }
6538
6539 return 1;
6540 }
6541
6550 public function addThumbs($file, $quality = 50)
6551 {
6552 $file_osencoded = dol_osencode($file);
6553
6554 if (file_exists($file_osencoded)) {
6555 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6556
6557 $tmparraysize = getDefaultImageSizes();
6558 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
6559 $maxheightsmall = $tmparraysize['maxheightsmall'];
6560 $maxwidthmini = $tmparraysize['maxwidthmini'];
6561 $maxheightmini = $tmparraysize['maxheightmini'];
6562 //$quality = $tmparraysize['quality'];
6563
6564 // Create small thumbs for company (Ratio is near 16/9)
6565 // Used on logon for example
6566 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
6567
6568 // Create mini thumbs for company (Ratio is near 16/9)
6569 // Used on menu or for setup page for example
6570 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
6571 }
6572 }
6573
6581 public function delThumbs($file)
6582 {
6583 $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
6584 dol_delete_file($imgThumbName);
6585 $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
6586 dol_delete_file($imgThumbName);
6587 }
6588
6589
6590 /* Functions common to commonobject and commonobjectline */
6591
6592 /* For default values */
6593
6607 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
6608 {
6609 /* TODO Remove this. Must use now something like:
6610 $note_private = GETPOST('note_private', 'restricthtml');
6611 if (!GETPOSTISSET('note_private') && empty($note_private) && !empty($objectsrc) [&& othercondtion]) {
6612 $note_private = $objectsrc->note_private;
6613 }
6614 */
6615
6616 // If param here has been posted, we use this value first.
6617 if (GETPOSTISSET($fieldname)) {
6618 return GETPOST($fieldname, $type, 3);
6619 }
6620
6621 if (isset($alternatevalue)) {
6622 return $alternatevalue;
6623 }
6624
6625 $newelement = $this->element;
6626 if ($newelement == 'facture') {
6627 $newelement = 'invoice';
6628 }
6629 if ($newelement == 'commande') {
6630 $newelement = 'order';
6631 }
6632 if (empty($newelement)) {
6633 dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6634 return '';
6635 }
6636
6637 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
6638 //var_dump($keyforfieldname);
6639 if (getDolGlobalString($keyforfieldname)) {
6640 return getDolGlobalString($keyforfieldname);
6641 }
6642
6643 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
6644 // store content into $conf->cache['overwrite_default']
6645
6646 return '';
6647 }
6648
6649
6650 /* Functions for data in other language */
6651
6652
6662 {
6663 // To avoid SQL errors. Probably not the better solution though
6664 if (!$this->element) {
6665 return 0;
6666 }
6667 if (!($this->id > 0)) {
6668 return 0;
6669 }
6670 if (is_array($this->array_languages)) {
6671 return 1;
6672 }
6673
6674 $this->array_languages = array();
6675
6676 $element = $this->element;
6677 if ($element == 'categorie') {
6678 $element = 'categories'; // For compatibility
6679 }
6680
6681 // Request to get translation values for object
6682 $sql = "SELECT rowid, property, lang , value";
6683 $sql .= " FROM ".$this->db->prefix()."object_lang";
6684 $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
6685 $sql .= " AND fk_object = ".((int) $this->id);
6686
6687 $resql = $this->db->query($sql);
6688 if ($resql) {
6689 $numrows = $this->db->num_rows($resql);
6690 if ($numrows) {
6691 $i = 0;
6692 while ($i < $numrows) {
6693 $obj = $this->db->fetch_object($resql);
6694 $key = $obj->property;
6695 $value = $obj->value;
6696 $codelang = $obj->lang;
6697 $type = $this->fields[$key]['type'];
6698
6699 // we can add this attribute to object
6700 if (preg_match('/date/', $type)) {
6701 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6702 } else {
6703 $this->array_languages[$key][$codelang] = $value;
6704 }
6705
6706 $i++;
6707 }
6708 }
6709
6710 $this->db->free($resql);
6711
6712 if ($numrows) {
6713 return $numrows;
6714 } else {
6715 return 0;
6716 }
6717 } else {
6718 dol_print_error($this->db);
6719 return -1;
6720 }
6721 }
6722
6730 public function setValuesForExtraLanguages($onlykey = '')
6731 {
6732 // Get extra fields
6733 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6734 $tmparray = explode('-', $postfieldkey);
6735 if ($tmparray[0] != 'field') {
6736 continue;
6737 }
6738
6739 $element = $tmparray[1];
6740 $key = $tmparray[2];
6741 $codelang = $tmparray[3];
6742 //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
6743
6744 if (!empty($onlykey) && $key != $onlykey) {
6745 continue;
6746 }
6747 if ($element != $this->element) {
6748 continue;
6749 }
6750
6751 $key_type = $this->fields[$key]['type'];
6752
6753 $enabled = 1;
6754 if (isset($this->fields[$key]['enabled'])) {
6755 $enabled = (int) dol_eval((string) $this->fields[$key]['enabled'], 1, 1, '1');
6756 }
6757 /*$perms = 1;
6758 if (isset($this->fields[$key]['perms']))
6759 {
6760 $perms = (int) dol_eval((string) $this->fields[$key]['perms'], 1, 1, '1');
6761 }*/
6762 if (empty($enabled)) {
6763 continue;
6764 }
6765 //if (empty($perms)) continue;
6766
6767 if (in_array($key_type, array('date'))) {
6768 // Clean parameters
6769 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6770 $value_key = dol_mktime(0, 0, 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6771 } elseif (in_array($key_type, array('datetime'))) {
6772 // Clean parameters
6773 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6774 $value_key = dol_mktime(GETPOSTINT($postfieldkey."hour"), GETPOSTINT($postfieldkey."min"), 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6775 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
6776 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
6777 if (!empty($value_arr)) {
6778 $value_key = implode(',', $value_arr);
6779 } else {
6780 $value_key = '';
6781 }
6782 } elseif (in_array($key_type, array('price', 'double'))) {
6783 $value_arr = GETPOST($postfieldkey, 'alpha');
6784 $value_key = price2num($value_arr);
6785 } else {
6786 $value_key = GETPOST($postfieldkey);
6787 if (in_array($key_type, array('link')) && $value_key == '-1') {
6788 $value_key = '';
6789 }
6790 }
6791
6792 $this->array_languages[$key][$codelang] = $value_key;
6793
6794 /*if ($nofillrequired) {
6795 $langs->load('errors');
6796 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
6797 return -1;
6798 }*/
6799 }
6800
6801 return 1;
6802 }
6803
6804
6805 /* Functions for extrafields */
6806
6813 public function fetchNoCompute($id)
6814 {
6815 global $conf;
6816
6817 $savDisableCompute = $conf->disable_compute;
6818 $conf->disable_compute = 1;
6819
6820 $ret = $this->fetch($id); /* @phpstan-ignore-line */
6821
6822 $conf->disable_compute = $savDisableCompute;
6823
6824 return $ret;
6825 }
6826
6827 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6837 public function fetch_optionals($rowid = null, $optionsArray = null)
6838 {
6839 // phpcs:enable
6840 global $conf, $extrafields;
6841
6842 if (empty($rowid)) {
6843 $rowid = $this->id;
6844 }
6845 if (empty($rowid) && isset($this->rowid)) { // @phan-suppress-current-line PhanUndeclaredProperty
6846 $rowid = $this->rowid; // deprecated @phan-suppress-current-line PhanUndeclaredProperty
6847 }
6848
6849 // To avoid SQL errors. Probably not the better solution though
6850 if (!$this->table_element) {
6851 return 0;
6852 }
6853 $this->array_options = array();
6854
6855 if (!is_array($optionsArray)) {
6856 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6857 if (!isset($extrafields) || !is_object($extrafields)) {
6858 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6859 $extrafields = new ExtraFields($this->db);
6860 }
6861
6862 // Load array of extrafields for elementype = $this->table_element
6863 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6864 $extrafields->fetch_name_optionals_label($this->table_element);
6865 }
6866 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6867 } else {
6868 global $extrafields;
6869 dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6870 }
6871
6872 $table_element = $this->table_element;
6873 if ($table_element == 'categorie') {
6874 $table_element = 'categories'; // For compatibility
6875 }
6876
6877 // Request to get complementary values
6878 if (is_array($optionsArray) && count($optionsArray) > 0) {
6879 $sql = "SELECT rowid";
6880 foreach ($optionsArray as $name => $label) {
6881 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || (!in_array($extrafields->attributes[$this->table_element]['type'][$name], ['separate', 'point', 'multipts', 'linestrg','polygon']))) {
6882 $sql .= ", ".$this->db->sanitize($name);
6883 }
6884 // use geo sql function to read as text
6885 if (!empty($extrafields->attributes[$this->table_element]['type'][$name]) && in_array($extrafields->attributes[$this->table_element]['type'][$name], array('point', 'multipts', 'linestrg', 'polygon'))) {
6886 // TODO Add an abstraction method in the database driver
6887 $sql .= ", ST_AsWKT(".$this->db->sanitize($name).") as ".$this->db->sanitize($name);
6888 }
6889 }
6890 $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6891 $sql .= " WHERE fk_object = ".((int) $rowid);
6892
6893 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6894 $resql = $this->db->query($sql);
6895 if ($resql) {
6896 $numrows = $this->db->num_rows($resql);
6897 if ($numrows) {
6898 $tab = $this->db->fetch_array($resql);
6899 foreach ($tab as $key => $value) {
6900 // 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)
6901 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6902 // we can add this attribute to object
6903 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6904 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6905 $this->array_options["options_".$key] = $this->db->jdate($value);
6906 } else {
6907 $this->array_options["options_".$key] = $value;
6908 }
6909
6910 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6911 }
6912 if (!empty($extrafields->attributes[$this->table_element]['type'][$key]) && $extrafields->attributes[$this->table_element]['type'][$key] == 'password') {
6913 if (!empty($value) && preg_match('/^dolcrypt:/', $value)) {
6914 $this->array_options["options_".$key] = dolDecrypt($value);
6915 }
6916 }
6917 }
6918 } else {
6923 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6924 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6925 $this->array_options['options_' . $key] = null;
6926 }
6927 }
6928 }
6929
6930 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6931 // in the element's extrafields table)
6932 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6933 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6934 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6935 //var_dump($conf->disable_compute);
6936 if (empty($conf->disable_compute)) {
6937 // We set a global variable to $objectoffield so we can use it inside computed formula (must be before the assignment)
6938 global $objectoffield;
6939 $objectoffield = dol_clone($this, 2);
6940 $this->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
6941 }
6942 }
6943 }
6944 }
6945
6946 $this->db->free($resql);
6947
6948 if ($numrows) {
6949 return $numrows;
6950 } else {
6951 return 0;
6952 }
6953 } else {
6954 $this->errors[] = $this->db->lasterror();
6955 return -1;
6956 }
6957 }
6958 return 0;
6959 }
6960
6967 public function deleteExtraFields()
6968 {
6969 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6970 return 0;
6971 }
6972
6973 $this->db->begin();
6974
6975 $table_element = $this->table_element;
6976 if ($table_element == 'categorie') {
6977 $table_element = 'categories'; // For compatibility
6978 }
6979
6980 dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6981
6982 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6983
6984 $resql = $this->db->query($sql_del);
6985 if (!$resql) {
6986 $this->error = $this->db->lasterror();
6987 $this->db->rollback();
6988 return -1;
6989 } else {
6990 $this->db->commit();
6991 return 1;
6992 }
6993 }
6994
7005 public function insertExtraFields($trigger = '', $userused = null)
7006 {
7007 global $langs, $extrafields, $user;
7008
7009 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7010 return 0;
7011 }
7012
7013 if (empty($userused)) {
7014 $userused = $user;
7015 }
7016
7017 $error = 0;
7018
7019 // Check parameters
7020 $langs->load('admin');
7021 if (!isset($extrafields) || !is_object($extrafields)) {
7022 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
7023 $extrafields = new ExtraFields($this->db);
7024 }
7025 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7026
7027 // Eliminate copied source object extra fields that do not exist in target object
7028 $new_array_options = array();
7029 foreach ($this->array_options as $key => $value) {
7030 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
7031 $new_array_options[$key] = $value;
7032 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
7033 $new_array_options['options_'.$key] = $value;
7034 }
7035 }
7036
7037 foreach ($new_array_options as $key => $value) {
7038 $attributeKey = substr($key, 8); // Remove 'options_' prefix
7039 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
7040 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element]['label'][$attributeKey]);
7041 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
7042 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
7043 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
7044 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
7045 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element]['emptyonclone'][$attributeKey];
7046 /*
7047 $attributeEnabled = $extrafields->attributes[$this->table_element]['enabled'][$attributeKey];
7048 $enabled = 0;
7049 if (!empty($extrafields->attributes[$this->table_element]['enabled'][$key])) {
7050 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
7051 }
7052 */
7053
7054 // If we clone, we have to clean unique extrafields to prevent duplicates.
7055 // If we clone, we have to clean extrafields having "empty on clone" option on.
7056 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
7057 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7058 $new_array_options[$key] = null;
7059 continue;
7060 }
7061
7062 // If we create product combination, we have to clean unique extrafields to prevent duplicates.
7063 // This behaviour can be prevented by external code by changing $this->context['createproductcombination'] value in hook
7064 if (!empty($this->context['createproductcombination']) && $this->context['createproductcombination'] == 'createproductcombination' && !empty($attributeUnique)) {
7065 $new_array_options[$key] = null;
7066 continue;
7067 }
7068
7069 // Similar code than into insertExtraFields
7070 if ($attributeRequired) { // If attribute is "Mandatory", then it is also in database as "Not null", so we must check even if attribute is not 'enabled'.
7071 $v = $this->array_options[$key];
7072 if (ExtraFields::isEmptyValue($v, $attributeType)) {
7073 $langs->load("errors");
7074 dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
7075 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
7076 return -1;
7077 }
7078 }
7079
7080 if (!empty($attrfieldcomputed)) {
7081 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
7082 global $objectoffield; // We set a global variable to $objectoffield so
7083 $objectoffield = $this; // we can use it inside the computed formula
7084 $value = dol_eval((string) $attrfieldcomputed, 1, 0, '2');
7085 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
7086 $new_array_options[$key] = $value;
7087 } else {
7088 $new_array_options[$key] = null;
7089 }
7090 continue;
7091 }
7092
7093 switch ($attributeType) {
7094 case 'int':
7095 case 'duration':
7096 case 'stars':
7097 if (!is_numeric($value) && $value != '') {
7098 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7099 return -1;
7100 } elseif ($value === '') {
7101 $new_array_options[$key] = null;
7102 }
7103 break;
7104 case 'boolean':
7105 if ($value === '' || $value === false || $value === null) {
7106 $new_array_options[$key] = null;
7107 }
7108 break;
7109 case 'price':
7110 case 'double':
7111 $value = price2num($value);
7112 if (!is_numeric($value) && $value != '') {
7113 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7114 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7115 return -1;
7116 } elseif ($value == '') {
7117 $value = null;
7118 }
7119 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
7120 $new_array_options[$key] = $value;
7121 break;
7122 /*case 'select': // Not required, we chose value='0' for undefined values
7123 if ($value=='-1')
7124 {
7125 $this->array_options[$key] = null;
7126 }
7127 break;*/
7128 case 'password':
7129 $algo = '';
7130 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
7131 // If there is an encryption choice, we use it to encrypt data before insert
7132 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
7133 $algo = reset($tmparrays);
7134 if ($algo != '') {
7135 //global $action; // $action may be 'create', 'update', 'update_extras'...
7136 //var_dump($action);
7137 //var_dump($this->oldcopy);exit;
7138 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
7139 //var_dump('algo='.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
7140 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7141 // If old value encrypted in database is same than submitted new value, it means we don't change it, so we don't update.
7142 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7143 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
7144 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
7145 } else {
7146 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7147 }
7148 } else {
7149 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7150 }
7151 } else {
7152 // If value has changed
7153 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7154 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
7155 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
7156 } else {
7157 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7158 }
7159 } else {
7160 $new_array_options[$key] = dol_hash($this->array_options[$key], $algo);
7161 }
7162 }
7163 } else {
7164 //var_dump('jjj'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
7165 // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
7166 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options[$key])) { // dolibarr reversible encryption
7167 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
7168 } else {
7169 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7170 }
7171 }
7172 } else {
7173 // No encryption
7174 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7175 }
7176 } else { // Common usage
7177 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7178 }
7179 break;
7180 case 'date':
7181 case 'datetime':
7182 // If data is a string instead of a timestamp, we convert it
7183 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7184 $this->array_options[$key] = strtotime($this->array_options[$key]);
7185 }
7186 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7187 break;
7188 case 'datetimegmt':
7189 // If data is a string instead of a timestamp, we convert it
7190 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7191 $this->array_options[$key] = strtotime($this->array_options[$key]);
7192 }
7193 $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
7194 break;
7195 case 'link':
7196 $param_list = array_keys($attributeParam['options']);
7197 // 0 : ObjectName
7198 // 1 : classPath
7199 $InfoFieldList = explode(":", $param_list[0]);
7200 dol_include_once($InfoFieldList[1]);
7201 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7202 if ($value == '-1') { // -1 is key for no defined in combo list of objects
7203 $new_array_options[$key] = '';
7204 } elseif ($value) {
7205 $object = new $InfoFieldList[0]($this->db);
7206 '@phan-var-force CommonObject $object';
7207
7208 $objectId = 0;
7209
7210 $sqlFetchObject = "SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7211 if (is_numeric($value)) {
7212 $sqlFetchObject .= " WHERE rowid = " . (int) $value;
7213 } else {
7214 $sqlFetchObject .= " WHERE ref = '" . $this->db->escape($value) . "'";
7215 }
7216
7217 $obj = $this->db->getRow($sqlFetchObject);
7218
7219 // getRow() returns an object on success, int 0 when the query succeeded but
7220 // returned no row, and false on SQL failure. Testing "!== false" let the 0
7221 // through as a success: $obj->rowid on an int is null, $res was set to 1 and
7222 // null was stored in the column while a success was reported.
7223 if (is_object($obj)) {
7224 $objectId = $obj->rowid;
7225 $res = 1;
7226 } else {
7227 $res = -1;
7228 }
7229
7230 if ($res > 0) {
7231 $new_array_options[$key] = $objectId;
7232 } else {
7233 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
7234 return -1;
7235 }
7236 }
7237 } else {
7238 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7239 }
7240 break;
7241 case 'checkbox':
7242 case 'chkbxlst':
7243 if (is_array($this->array_options[$key])) {
7244 $new_array_options[$key] = implode(',', $this->array_options[$key]);
7245 } else {
7246 $new_array_options[$key] = $this->array_options[$key];
7247 }
7248 break;
7249 }
7250 }
7251
7252 // Set array $sqlColumnValues (SQL field name in extrafield table => value)
7253 $sqlColumnValues = ['fk_object' => (int) $this->id]; // key-value pairs for the SQL INSERT or UPDATE query
7254
7255 foreach ($new_array_options as $key => $newValue) {
7256 $attributeKey = substr($key, 8); // Remove 'options_' prefix
7257 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
7258 if ($attributeType === 'separate') {
7259 // separator extrafields don't have data per object so they don't have a comlumn in the database
7260 continue;
7261 }
7262 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ?? null;
7263 // Add field of attribute
7264 if (! $geoDataType) {
7265 // not a geodata type
7266 if ($newValue != '') {
7267 $sqlColumnValues[$attributeKey] = "'".$this->db->escape($newValue)."'";
7268 } else {
7269 $sqlColumnValues[$attributeKey] = 'null';
7270 }
7271 continue;
7272 }
7273 if (empty($newValue)) {
7274 $sqlColumnValues[$attributeKey] = 'null';
7275 continue;
7276 }
7277 if (preg_match('/error/i', $newValue)) {
7278 dol_syslog('Bad syntax string for '.$geoDataType['shortname'].' '.$newValue.' to generate SQL request', LOG_WARNING);
7279 $sqlColumnValues[$attributeKey] = 'null';
7280 continue;
7281 }
7282
7283 // Geodata type: Text must be a WKT string. Examples:
7284 // - point => "POINT(15 20)"
7285 // - multipts => "MULTIPOINT(0 0, 20 20, 60 60)"
7286 // - linestrg => "LINESTRING(0 0, 10 10, 20 25, 50 60)"
7287 // - polygon => "POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))"
7288 $sqlColumnValues[$attributeKey] = $geoDataType['ST_Function']."('".$this->db->escape($newValue)."')"; // @phan-suppress-current-line SqlInjection
7289 }
7290
7291 $this->db->begin();
7292
7293 $table_element = $this->table_element;
7294 if ($table_element == 'categorie') {
7295 $table_element = 'categories'; // For compatibility
7296 }
7297 $extrafieldsTable = $this->db->prefix() . $table_element . '_extrafields';
7298
7299 dol_syslog(get_class($this)."::insertExtraFields update or insert record line", LOG_DEBUG);
7300
7301 $linealreadyfound = 0;
7302 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7303 $resql = $this->db->query($sql);
7304 if ($resql) {
7305 $tmpobj = $this->db->fetch_object($resql);
7306 if ($tmpobj) {
7307 $linealreadyfound = $tmpobj->nb;
7308 }
7309 }
7310
7311 // if the extrafields row already exists for the object, we update it
7312 if ($linealreadyfound) {
7313 array_shift($sqlColumnValues); // drop the 'fk_object' column because its value won't change
7314 if (empty($sqlColumnValues)) {
7315 // No column of the target element to update. This happens when the object was created from
7316 // another element whose extrafields do not exist on this element (e.g. invoice created from a
7317 // shipment: the source line extrafields are copied into array_options but none match facturedet).
7318 // The existing row is already correct, so there is nothing to update: avoid an empty "SET" clause
7319 // that would produce an invalid SQL statement.
7320 $this->db->commit();
7321 return 1;
7322 }
7323 $sqlColumnValueString = implode(
7324 ',',
7329 array_map(function ($key) use ($sqlColumnValues) {
7330 return "{$key} = {$sqlColumnValues[$key]}";
7331 }, array_keys($sqlColumnValues))
7332 );
7333 $sql = "UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->id);
7334 } else {
7335 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
7336 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] ?? array();
7337 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7338 if (isset($sqlColumnValues[$key])) {
7339 // extrafield value already provided: no need to add it
7340 continue;
7341 }
7342 // default value: empty string, except for 'int', 'double' and 'price'
7343 $sqlColumnValues[$key] = "''";
7344 if (in_array($extrafieldType, array('int', 'double', 'price'))) {
7345 $sqlColumnValues[$key] = 0;
7346 }
7347 }
7348 $sqlColumns = implode(',', array_keys($sqlColumnValues));
7349 $sqlValues = implode(',', array_values($sqlColumnValues));
7350 $sql = "INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7351 }
7352
7353 $resql = $this->db->query($sql);
7354 if (!$resql) {
7355 $this->error = $this->db->lasterror();
7356 $error++;
7357 }
7358
7359 // Update also the user of last modification in parent table
7360 if (!$error && !empty($this->fields['fk_user_modif'])) { // @phan-suppress-current-line PhanTypeMismatchProperty
7361 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
7362 $sql .= " SET fk_user_modif = ".(int) $userused->id;
7363 $sql .= " WHERE ".(empty($this->table_rowid) ? 'rowid' : $this->db->sanitize($this->table_rowid))." = ".((int) $this->id);
7364 $this->db->query($sql);
7365 }
7366
7367 if (!$error && $trigger) {
7368 // Call trigger
7369 $this->context = array('extrafieldaddupdate' => 1);
7370 $result = $this->call_trigger($trigger, $userused);
7371 if ($result < 0) {
7372 $error++;
7373 }
7374 // End call trigger
7375 }
7376
7377 if ($error) {
7378 $this->db->rollback();
7379 return -1;
7380 } else {
7381 $this->db->commit();
7382 return 1;
7383 }
7384 }
7385
7397 public function insertExtraLanguages($trigger = '', $userused = null)
7398 {
7399 global $langs, $user;
7400
7401 if (empty($userused)) {
7402 $userused = $user;
7403 }
7404
7405 $error = 0;
7406
7407 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
7408 return 0; // For avoid conflicts if trigger used
7409 }
7410
7411 if (is_array($this->array_languages)) {
7412 $new_array_languages = $this->array_languages;
7413
7414 foreach ($new_array_languages as $key => $value) {
7415 $attributeKey = $key;
7416 $attributeType = $this->fields[$attributeKey]['type'];
7417 $attributeLabel = $this->fields[$attributeKey]['label'];
7418
7419 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
7420 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
7421
7422 switch ($attributeType) {
7423 case 'int':
7424 if (is_array($value) || (!is_numeric($value) && $value != '')) {
7425 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
7426 return -1;
7427 } elseif ($value == '') { // @phan-suppress-current-line PhanTypeComparisonFromArray
7428 $new_array_languages[$key] = null;
7429 }
7430 break;
7431 case 'double':
7432 $value = price2num((string) $value);
7433 if (!is_numeric($value) && $value != '') {
7434 dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7435 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
7436 return -1;
7437 } elseif ($value == '') {
7438 $new_array_languages[$key] = null;
7439 } else {
7440 $new_array_languages[$key] = $value;
7441 }
7442 break;
7443 /*case 'select': // Not required, we chose value='0' for undefined values
7444 if ($value=='-1')
7445 {
7446 $this->array_options[$key] = null;
7447 }
7448 break;*/
7449 }
7450 }
7451
7452 $this->db->begin();
7453
7454 $table_element = $this->table_element;
7455 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
7456 $table_element = 'categories'; // For compatibility
7457 }
7458
7459 dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
7460
7461 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
7462 foreach ($langcodearray as $langcode => $value) {
7463 $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
7464 $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
7465 $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
7466 $this->db->query($sql_del);
7467
7468 if ($value !== '') {
7469 $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
7470 $sql .= ") VALUES (".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
7471 $sql .= ")";
7472
7473 $resql = $this->db->query($sql);
7474 if (!$resql) {
7475 $this->error = $this->db->lasterror();
7476 $error++;
7477 break;
7478 }
7479 }
7480 }
7481 }
7482
7483 if (!$error && $trigger) {
7484 // Call trigger
7485 $this->context = array('extralanguagesaddupdate' => 1);
7486 $result = $this->call_trigger($trigger, $userused);
7487 if ($result < 0) {
7488 $error++;
7489 }
7490 // End call trigger
7491 }
7492
7493 if ($error) {
7494 $this->db->rollback();
7495 return -1;
7496 } else {
7497 $this->db->commit();
7498 return 1;
7499 }
7500 } else {
7501 return 0;
7502 }
7503 }
7504
7515 public function updateExtraField($key, $trigger = null, $userused = null)
7516 {
7517 global $langs, $user, $extrafields, $hookmanager;
7518
7519 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
7520 return 0;
7521 }
7522
7523 if (empty($userused)) {
7524 $userused = $user;
7525 }
7526
7527 $error = 0;
7528
7529 if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
7530 // Check parameters
7531 $langs->load('admin');
7532 if (!isset($extrafields) || !is_object($extrafields)) {
7533 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
7534 $extrafields = new ExtraFields($this->db);
7535 }
7536 $extrafields->fetch_name_optionals_label($this->table_element);
7537 if (!isset($extrafields->attributes[$this->table_element]['type'][$key])) {
7538 // Extrafield not defined for this object type: nothing to update
7539 return 0;
7540 }
7541 $value = $this->array_options["options_".$key];
7542
7543 $attributeKey = $key;
7544 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
7545 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
7546 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
7547 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
7548 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
7549 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
7550 //$attributeEnabled = $extrafields->attributes[$this->table_element]['enabled'][$attributeKey];
7551
7552 // Similar code than into insertExtraFields
7553 if ($attributeRequired) { // If attribute is "Mandatory", then it is also in database as "Not null", so we must check even if attribute is not 'enabled'.
7554 $mandatorypb = false;
7555 if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
7556 $mandatorypb = true;
7557 }
7558 if ($this->array_options["options_".$key] === '') {
7559 $mandatorypb = true;
7560 }
7561 if ($mandatorypb) {
7562 $langs->load("errors");
7563 dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
7564 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
7565 return -1;
7566 }
7567 }
7568
7569 // $new_array_options will be used for direct update, so must contains formatted data for the UPDATE.
7570 $new_array_options = $this->array_options;
7571
7572 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
7573 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
7574 if (!empty($attrfieldcomputed)) {
7575 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
7576 global $objectoffield; // We set a global variable to $objectoffield so
7577 $objectoffield = $this; // we can use it inside the computed formula
7578 $value = dol_eval((string) $attrfieldcomputed, 1, 0, '2');
7579 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
7580
7581 $new_array_options["options_".$key] = $value;
7582
7583 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7584 } else {
7585 $new_array_options["options_".$key] = null;
7586
7587 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7588 }
7589 }
7590
7591 switch ($attributeType) {
7592 case 'int':
7593 if (!is_numeric($value) && $value != '') {
7594 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7595 return -1;
7596 } elseif ($value === '') {
7597 $new_array_options["options_".$key] = null;
7598
7599 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7600 }
7601 break;
7602 case 'price':
7603 case 'double':
7604 $value = price2num($value);
7605 if (!is_numeric($value) && $value != '') {
7606 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7607 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7608 return -1;
7609 } elseif ($value === '') {
7610 $value = null;
7611 }
7612 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
7613 $new_array_options["options_".$key] = $value;
7614
7615 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7616 break;
7617 /*case 'select': // Not required, we chose value='0' for undefined values
7618 if ($value=='-1')
7619 {
7620 $new_array_options["options_".$key] = $value;
7621
7622 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7623 }
7624 break;*/
7625 case 'password':
7626 $algo = '';
7627 if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
7628 // If there is an encryption choice, we use it to encrypt data before insert
7629 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
7630 $algo = reset($tmparrays);
7631 if ($algo != '') {
7632 //global $action; // $action may be 'create', 'update', 'update_extras'...
7633 //var_dump($action);
7634 //var_dump($this->oldcopy);exit;
7635 //var_dump($key.' '.$this->array_options["options_".$key].' '.$algo);
7636 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
7637 //var_dump($this->oldcopy->array_options["options_".$key]); var_dump($this->array_options["options_".$key]);
7638 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.
7639 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7640 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7641 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7642 } else {
7643 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7644 }
7645 } else {
7646 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7647 }
7648 } else {
7649 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7650 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7651 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]);
7652 } else {
7653 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7654 }
7655 } else {
7656 $new_array_options["options_".$key] = dol_hash($this->array_options["options_".$key], $algo);
7657 }
7658 }
7659 } else {
7660 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { // dolibarr reversible encryption
7661 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7662 } else {
7663 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7664 }
7665 }
7666 } else {
7667 // No encryption
7668 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7669 }
7670 } else { // Common usage
7671 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7672 }
7673
7674 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7675 break;
7676 case 'date':
7677 case 'datetime':
7678 if (empty($this->array_options["options_".$key])) {
7679 $new_array_options["options_".$key] = null;
7680
7681 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7682 } else {
7683 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
7684 }
7685 break;
7686 case 'datetimegmt':
7687 if (empty($this->array_options["options_".$key])) {
7688 $new_array_options["options_".$key] = null;
7689
7690 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7691 } else {
7692 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
7693 }
7694 break;
7695 case 'boolean':
7696 if (empty($this->array_options["options_".$key])) {
7697 $new_array_options["options_".$key] = null;
7698
7699 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7700 }
7701 break;
7702 case 'link':
7703 if ($this->array_options["options_".$key] === '') {
7704 $new_array_options["options_".$key] = null;
7705
7706 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7707 }
7708 break;
7709 /*
7710 case 'link':
7711 $param_list = array_keys($attributeParam['options']);
7712 // 0 : ObjectName
7713 // 1 : classPath
7714 $InfoFieldList = explode(":", $param_list[0]);
7715 dol_include_once($InfoFieldList[1]);
7716 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
7717 {
7718 if ($value == '-1') // -1 is key for no defined in combo list of objects
7719 {
7720 $new_array_options[$key] = '';
7721 } elseif ($value) {
7722 $object = new $InfoFieldList[0]($this->db);
7723 if (is_numeric($value)) $res = $object->fetch($value); // Common case
7724 else $res = $object->fetch(0, $value); // For compatibility
7725
7726 if ($res > 0) $new_array_options[$key] = $object->id;
7727 else {
7728 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
7729 $this->db->rollback();
7730 return -1;
7731 }
7732 }
7733 } else {
7734 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7735 }
7736 break;
7737 */
7738 case 'checkbox':
7739 case 'chkbxlst':
7740 $new_array_options = array();
7741 if (is_array($this->array_options["options_".$key])) {
7742 $new_array_options["options_".$key] = implode(',', $this->array_options["options_".$key]);
7743 } else {
7744 $new_array_options["options_".$key] = $this->array_options["options_".$key];
7745 }
7746
7747 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7748 break;
7749 }
7750
7751 $this->db->begin();
7752
7753 $linealreadyfound = 0;
7754
7755 // 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)
7756 $table_element = $this->table_element;
7757 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
7758 $table_element = 'categories'; // For compatibility
7759 }
7760
7761 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7762 $resql = $this->db->query($sql);
7763 if ($resql) {
7764 $tmpobj = $this->db->fetch_object($resql);
7765 if ($tmpobj) {
7766 $linealreadyfound = $tmpobj->nb;
7767 }
7768 }
7769
7770 //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit;
7771 if ($linealreadyfound) {
7772 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ?? null; // @phan-suppress-current-line SqlInjection
7773 if ($this->array_options["options_".$key] === null) {
7774 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($table_element)."_extrafields";
7775 $sql .= " SET ".$this->db->sanitize($key)." = null";
7776 } elseif (!empty($sanitizedGeoDataType['ST_Function'])) {
7777 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($table_element)."_extrafields";
7778 $sql .= " SET ".$this->db->sanitize($key)." = ".$this->db->sanitize($sanitizedGeoDataType['ST_Function'])."('".$this->db->escape($this->array_options["options_".$key])."')";
7779 } else {
7780 // TODO What about if field is type int or float ($attributeType = price, int, ...) ?
7781 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($table_element)."_extrafields";
7782 $sql .= " SET ".$this->db->sanitize($key)." = '".$this->db->escape($new_array_options["options_".$key])."'";
7783 }
7784 $sql .= " WHERE fk_object = ".((int) $this->id);
7785
7786 $resql = $this->db->query($sql);
7787 if (!$resql) {
7788 $error++;
7789 $this->error = $this->db->lasterror();
7790 }
7791 } else {
7792 $result = $this->insertExtraFields('', $user);
7793 if ($result < 0) {
7794 $error++;
7795 }
7796 }
7797
7798 // Update also the user of last modification in parent table
7799 if (!$error && !empty($this->fields['fk_user_modif'])) {
7800 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
7801 $sql .= " SET fk_user_modif = ".(int) $userused->id;
7802 $sql .= " WHERE ".(empty($this->table_rowid) ? 'rowid' : $this->db->sanitize($this->table_rowid))." = ".((int) $this->id);
7803 $this->db->query($sql);
7804 }
7805
7806 if (!$error) {
7807 $parameters = array('key' => $key);
7808 global $action;
7809 $reshook = $hookmanager->executeHooks('updateExtraFieldBeforeCommit', $parameters, $this, $action);
7810 if ($reshook < 0) {
7811 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
7812 }
7813 }
7814
7815 if (!$error && $trigger) {
7816 // Call trigger
7817 $this->context = array('extrafieldupdate' => 1);
7818 $result = $this->call_trigger($trigger, $userused);
7819 if ($result < 0) {
7820 $error++;
7821 }
7822 // End call trigger
7823 }
7824
7825 if ($error) {
7826 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7827 $this->db->rollback();
7828 return -1;
7829 } else {
7830 $this->db->commit();
7831 return 1;
7832 }
7833 } else {
7834 return 0;
7835 }
7836 }
7837
7844 public function getExtraField($key)
7845 {
7846 return $this->array_options['options_'.$key] ?? null;
7847 }
7848
7856 public function setExtraField($key, $value)
7857 {
7858 $this->array_options['options_'.$key] = $value;
7859 }
7860
7871 public function updateExtraLanguages($key, $trigger = null, $userused = null)
7872 {
7873 global $user;
7874
7875 if (empty($userused)) {
7876 $userused = $user;
7877 }
7878
7879 //$error = 0;
7880
7881 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
7882 return 0; // For avoid conflicts if trigger used
7883 }
7884
7885 return 0;
7886 }
7887
7888
7903 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
7904 {
7905 global $conf, $langs, $form;
7906
7907
7908 // TODO pass the current object as a parameter to give more flexibility (like disable showing input for extra fields when canAlwaysBeEdited is false and $object->status is not draft...)
7909
7910 if (!is_object($form)) {
7911 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7912 $form = new Form($this->db);
7913 }
7914
7915 if (!empty($this->fields)) {
7916 $val = $this->fields[$key];
7917 }
7918
7919 // Validation tests and output
7920 $fieldValidationErrorMsg = '';
7921 $validationClass = '';
7922 $fieldValidationErrorMsg = $this->getFieldError($key);
7923 if (!empty($fieldValidationErrorMsg)) {
7924 $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
7925 } else {
7926 $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
7927 }
7928
7929 //$valuemultiselectinput = array();
7930 $out = '';
7931 $type = '';
7932 $isDependList = 0;
7933 $param = array();
7934 $param['options'] = array();
7935 $reg = array();
7936 // @phan-suppress-next-line PhanTypeMismatchProperty
7937 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
7938 // Because we work on extrafields
7939 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7940 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7941 $type = 'link';
7942 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7943 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7944 $type = 'link';
7945 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
7946 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7947 $type = 'link';
7948 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7949 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7950 $type = 'sellist';
7951 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7952 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7953 $type = 'sellist';
7954 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
7955 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7956 $type = 'sellist';
7957 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
7958 $param['options'] = array($reg[1] => 'N');
7959 $type = 'chkbxlst';
7960 } elseif (preg_match('/varchar\‍((\d+)\‍)/', $val['type'], $reg)) {
7961 $param['options'] = array();
7962 $type = 'varchar';
7963 $size = $reg[1];
7964 } elseif (preg_match('/varchar/', $val['type'])) {
7965 $param['options'] = array();
7966 $type = 'varchar';
7967 } elseif (preg_match('/stars\‍((\d+)\‍)/', $val['type'], $reg)) {
7968 $param['options'] = array();
7969 $type = 'stars';
7970 $size = $reg[1];
7971 } else {
7972 $param['options'] = array();
7973 $type = $this->fields[$key]['type'];
7974 }
7975 //var_dump($type); var_dump($param['options']);
7976
7977 // Special case that force options and type ($type can be integer, varchar, ...)
7978 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
7979 $param['options'] = $this->fields[$key]['arrayofkeyval'];
7980 // Special case that prevent to force $type to have multiple input @phan-suppress-next-line PhanTypeMismatchProperty
7981 if (empty($this->fields[$key]['multiinput'])) {
7982 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
7983 }
7984 }
7985
7986 $label = $this->fields[$key]['label'];
7987 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
7988 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7989 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
7990 // @phan-suppress-next-line PhanTypeMismatchProperty
7991 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
7992 // @phan-suppress-next-line PhanTypeMismatchProperty
7993 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
7994 // @phan-suppress-next-line PhanTypeMismatchProperty
7995 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
7996 // @phan-suppress-next-line PhanTypeMismatchProperty
7997 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
7998 // @phan-suppress-next-line PhanTypeMismatchProperty
7999 $placeholder = (!empty($this->fields[$key]['placeholder']) ? $this->fields[$key]['placeholder'] : 0);
8000
8001 // @phan-suppress-next-line PhanTypeMismatchProperty
8002 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
8003 // @phan-suppress-next-line PhanTypeMismatchProperty
8004 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
8005 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
8006
8007 $objectid = $this->id;
8008
8009 if ($computed) {
8010 if (!preg_match('/^search_/', $keyprefix)) {
8011 return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
8012 } else {
8013 return '';
8014 }
8015 }
8016
8017 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
8018 if (empty($morecss) && !empty($val['css'])) {
8019 $morecss = $val['css'];
8020 } elseif (empty($morecss)) {
8021 if ($type == 'date') {
8022 $morecss = 'minwidth100imp';
8023 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
8024 $morecss = 'minwidth200imp';
8025 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
8026 $morecss = 'maxwidth75';
8027 } elseif ($type == 'url') {
8028 $morecss = 'minwidth400';
8029 } elseif ($type == 'boolean') {
8030 $morecss = '';
8031 } else {
8032 if (is_numeric($size) && round((float) $size) < 12) {
8033 $morecss = 'minwidth100';
8034 } elseif (is_numeric($size) && round((float) $size) <= 48) {
8035 $morecss = 'minwidth200';
8036 } else {
8037 $morecss = 'minwidth400';
8038 }
8039 }
8040 }
8041
8042 // Add validation state class
8043 if (!empty($validationClass)) {
8044 $morecss .= $validationClass;
8045 }
8046
8047 if (in_array($type, array('date'))) {
8048 $tmp = explode(',', $size);
8049 $newsize = $tmp[0];
8050 $showtime = 0;
8051
8052 // Do not show current date when field not required (see selectDate() method)
8053 if (!$required && $value == '') {
8054 $value = '-1';
8055 }
8056
8057 // TODO Must also support $moreparam
8058 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
8059 } elseif (in_array($type, array('datetime'))) {
8060 $tmp = explode(',', $size);
8061 $newsize = $tmp[0];
8062 $showtime = 1;
8063
8064 // Do not show current date when field not required (see selectDate() method)
8065 if (!$required && $value == '') {
8066 $value = '-1';
8067 }
8068
8069 // TODO Must also support $moreparam
8070 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
8071 } elseif (in_array($type, array('duration'))) {
8072 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
8073 } elseif (in_array($type, array('int', 'integer'))) {
8074 $tmp = explode(',', $size);
8075 $newsize = $tmp[0];
8076 $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' : '').'>';
8077 } elseif (in_array($type, array('real'))) {
8078 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
8079 } elseif (preg_match('/varchar/', (string) $type)) {
8080 $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 : '').($placeholder ? ' placeholder="'.dolPrintHTMLForAttribute($placeholder).'"' : '').($autofocusoncreate ? ' autofocus' : '').'>';
8081 } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
8082 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
8083 } elseif (preg_match('/^text/', (string) $type)) {
8084 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
8085 if (!empty($param['options'])) {
8086 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
8087 //var_dump($param['options']);
8088 $out .= $form->selectarray($keyprefix.$key.$keysuffix."_multiinput", $param['options'], '', 1, 0, 0, "flat maxwidthonphone".$morecss);
8089 $out .= '<input id="'.$keyprefix.$key.$keysuffix.'_multiinputadd" type="button" class="button" value="'.$langs->trans("Add").'">';
8090 $out .= "<script>";
8091 $out .= '
8092 function handlemultiinputdisabling(htmlname){
8093 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8094 multiinput = $("#"+htmlname+"_multiinput");
8095 multiinput.find("option").each(function(){
8096 tmpval = $("#"+htmlname).val();
8097 tmpvalarray = tmpval.split("\n");
8098 valtotest = $(this).val();
8099 if(tmpvalarray.includes(valtotest)){
8100 $(this).prop("disabled",true);
8101 } else {
8102 if($(this).prop("disabled") == true){
8103 console.log(valtotest)
8104 $(this).prop("disabled", false);
8105 }
8106 }
8107 });
8108 }
8109
8110 $(document).ready(function () {
8111 $("#'.$keyprefix.$key.$keysuffix.'_multiinputadd").on("click",function() {
8112 tmpval = $("#'.$keyprefix.$key.$keysuffix.'").val();
8113 tmpvalarray = tmpval.split(",");
8114 valtotest = $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val();
8115 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8116 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.'");
8117 if(tmpval == ""){
8118 tmpval = valtotest;
8119 } else {
8120 tmpval = tmpval + "\n" + valtotest;
8121 }
8122 $("#'.$keyprefix.$key.$keysuffix.'").val(tmpval);
8123 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
8124 $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val(-1);
8125 } else {
8126 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.'");
8127 }
8128 });
8129 $("#'.$keyprefix.$key.$keysuffix.'").on("change",function(){
8130 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
8131 });
8132 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
8133 })';
8134 $out .= "</script>";
8135 $value = str_replace(',', "\n", $value);
8136 }
8137 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
8138 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
8139 $out .= (string) $doleditor->Create(1, '', true, '', '', '', $morecss);
8140 } else {
8141 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
8142 }
8143 } elseif (preg_match('/^html/', (string) $type)) {
8144 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
8145 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
8146 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
8147 $out = (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
8148 } else {
8149 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
8150 }
8151 } elseif ($type == 'boolean') {
8152 $checked = '';
8153 if (!empty($value)) {
8154 $checked = ' checked value="1" ';
8155 } else {
8156 $checked = ' value="1" ';
8157 }
8158 $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
8159 } elseif ($type == 'price') {
8160 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
8161 $value = price($value);
8162 }
8163 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> <span class="opacitymedium">'.$langs->getCurrencySymbol($conf->currency).'</span>';
8164 } elseif ($type == 'stars') {
8165 $out = '<input type="hidden" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
8166 $out .= '<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.'_selection">';
8167 $i = 1;
8168 while ($i <= $size) {
8169 $out .= '<span class="star" data-value="'.$i.'">'.img_picto('', 'fontawesome_star_fas').'</span>';
8170 $i++;
8171 }
8172 $out .= '</div>';
8173 $out .= '<script>
8174 jQuery(function($) { /* commonobject.class.php 1 */
8175 let container = $("#'.$keyprefix.$key.$keysuffix.'_selection");
8176 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.'").val()) || 0;
8177 container.find(".star").each(function() {
8178 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8179 });
8180 container.find(".star").on("mouseover", function() {
8181 let selectedStar = $(this).data("value");
8182 container.find(".star").each(function() {
8183 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8184 });
8185 });
8186 container.on("mouseout", function() {
8187 container.find(".star").each(function() {
8188 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8189 });
8190 });
8191 container.find(".star").off("click").on("click", function() {
8192 selectedStars = $(this).data("value");
8193 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.'").val() == 1) {
8194 selectedStars = 0;
8195 }
8196 $("#'.$keyprefix.$key.$keysuffix.'").val(selectedStars);
8197 container.find(".star").each(function() {
8198 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8199 });
8200 });
8201 });
8202 </script>';
8203 } elseif (preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
8204 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
8205 $value = price($value);
8206 }
8207 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
8208 } elseif ($type == 'select') { // combo list
8209 $out = '';
8210 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8211 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
8212 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8213 }
8214
8215 $tmpselect = '';
8216 $nbchoice = 0;
8217
8218 foreach ($param['options'] as $keyb => $valb) {
8219 if ((string) $keyb == '') {
8220 continue;
8221 }
8222 if (strpos($valb, "|") !== false) {
8223 list($valb, $parent) = explode('|', $valb);
8224 }
8225 $nbchoice++;
8226 $tmpselect .= '<option value="'.$keyb.'"';
8227 $tmpselect .= (((string) $value == (string) $keyb) ? ' selected' : '');
8228 if (!empty($parent)) {
8229 $isDependList = 1;
8230 }
8231 $tmpselect .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
8232 $tmpselect .= '>'.$langs->trans($valb).'</option>';
8233 }
8234
8235 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
8236 if ((!isset($this->fields[$key]['default'])) || empty($this->fields[$key]['notnull']) || ($this->fields[$key]['notnull'] != 1) || $nbchoice >= 2) {
8237 $out .= '<option value="0">&nbsp;</option>';
8238 }
8239 $out .= $tmpselect;
8240 $out .= '</select>';
8241 } elseif ($type == 'sellist') {
8242 $out = '';
8243 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8244 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
8245 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8246 }
8247
8248 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
8249 if (is_array($param['options'])) {
8250 $tmpparamoptions = array_keys($param['options']);
8251 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
8252
8253 $InfoFieldList = explode(":", $paramoptions[0], 5);
8254 // 0 : tableName
8255 // 1 : label field name
8256 // 2 : key fields name (if different of rowid)
8257 // optional parameters...
8258 // 3 : key field parent (for dependent lists). How this is used ?
8259 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field='value'. Or use USF on a second line separated by "\n".
8260 // 5 : string category type. This replace the filter.
8261 // 6 : ids categories list separated by comma for category root. This replace the filter.
8262 // 7 : sort field
8263
8264 // If there is filter
8265 if (! empty($InfoFieldList[4])) {
8266 $pos = 0;
8267 $parenthesisopen = 0;
8268 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
8269 if (substr($InfoFieldList[4], $pos, 1) == '(') {
8270 $parenthesisopen++;
8271 }
8272 if (substr($InfoFieldList[4], $pos, 1) == ')') {
8273 $parenthesisopen--;
8274 }
8275 $pos++;
8276 }
8277 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8278 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8279 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
8280 $InfoFieldList[4] = $tmpbefore;
8281 if ($tmpafter !== '') {
8282 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
8283 }
8284 //var_dump($InfoFieldList);
8285
8286 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
8287 $reg = array();
8288 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
8289 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
8290 }
8291
8292 //var_dump($InfoFieldList);
8293 }
8294
8295 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
8296
8297 $parentName = '';
8298 $parentField = '';
8299
8300 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
8301
8302 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8303 if (strpos($InfoFieldList[4], 'extra.') !== false) {
8304 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
8305 } else {
8306 $keyList = $InfoFieldList[2].' as rowid';
8307 }
8308 }
8309 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8310 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
8311 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra.') !== false) {
8312 $keyList .= ', main.'.$parentField;
8313 } else {
8314 $keyList .= ', '.$parentField;
8315 }
8316 }
8317
8318 $filter_categorie = false;
8319 if (count($InfoFieldList) > 5) {
8320 if ($InfoFieldList[0] == 'categorie') {
8321 $filter_categorie = true;
8322 }
8323 }
8324
8325 if (!$filter_categorie) {
8326 $fields_label = isset($InfoFieldList[1]) ? explode('|', $InfoFieldList[1]) : array();
8327 if (!empty($fields_label)) {
8328 $keyList .= ', ';
8329 $keyList .= implode(', ', $fields_label);
8330 }
8331
8332 $sqlwhere = '';
8333 $sql = "SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8334 $sql .= " FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8335
8336 if (!empty($InfoFieldList[4])) {
8337 // can use SELECT request
8338 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
8339 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
8340 }
8341
8342 // current object id can be use into filter
8343 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
8344 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
8345 } else {
8346 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
8347 }
8348
8349 // We have to join on extrafield table
8350 $errstr = '';
8351 if (strpos($InfoFieldList[4], 'extra') !== false) {
8352 $sql .= " as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . "_extrafields as extra";
8353 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8354 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8355 } else {
8356 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8357 }
8358 } else {
8359 $sqlwhere .= ' WHERE 1=1';
8360 }
8361
8362 // Add Usf filter on second line
8363 /*
8364 if ($Usf) {
8365 $errorstr = '';
8366 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
8367 if (!$errorstr) {
8368 $sqlwhere .= $sqlusf;
8369 } else {
8370 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
8371 }
8372 }
8373 */
8374
8375 // Some tables may have field, some other not. For the moment we disable it.
8376 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
8377 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
8378 }
8379 $sql .= $sqlwhere;
8380
8381 // Note: $InfoFieldList can be 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:Sortfield]]]]]]'
8382 if (isset($InfoFieldList[7]) && preg_match('/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8383 $sql .= " ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8384 } else {
8385 $sql .= " ORDER BY ".$this->db->sanitize(implode(', ', $fields_label));
8386 }
8387 $sql .= ' LIMIT ' . getDolGlobalInt('MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8388 // print $sql;
8389
8390 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
8391 $resql = $this->db->query($sql);
8392 if ($resql) {
8393 $out .= '<option value="0">&nbsp;</option>';
8394 $num = $this->db->num_rows($resql);
8395 $i = 0;
8396 while ($i < $num) {
8397 $labeltoshow = '';
8398 $obj = $this->db->fetch_object($resql);
8399
8400 // Several field into label (eq table:code|libelle:rowid)
8401 $notrans = false;
8402 $fields_label = explode('|', $InfoFieldList[1]);
8403 if (count($fields_label) > 1) {
8404 $notrans = true;
8405 foreach ($fields_label as $field_toshow) {
8406 $labeltoshow .= $obj->$field_toshow . ' ';
8407 }
8408 } else {
8409 $labeltoshow = $obj->{$InfoFieldList[1]};
8410 }
8411 $labeltoshow = dol_trunc($labeltoshow, 45);
8412
8413 if ($value == $obj->rowid) {
8414 foreach ($fields_label as $field_toshow) {
8415 $translabel = $langs->trans($obj->$field_toshow);
8416 if ($translabel != $obj->$field_toshow) {
8417 $labeltoshow = dol_trunc($translabel) . ' ';
8418 } else {
8419 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
8420 }
8421 }
8422 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
8423 } else {
8424 if (!$notrans) {
8425 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8426 if ($translabel != $obj->{$InfoFieldList[1]}) {
8427 $labeltoshow = dol_trunc($translabel, 18);
8428 } else {
8429 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
8430 }
8431 }
8432 if (empty($labeltoshow)) {
8433 $labeltoshow = '(not defined)';
8434 }
8435 if ($value == $obj->rowid) {
8436 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
8437 }
8438
8439 if (!empty($InfoFieldList[3]) && $parentField) {
8440 $parent = $parentName . ':' . $obj->{$parentField};
8441 $isDependList = 1;
8442 }
8443
8444 $out .= '<option value="' . $obj->rowid . '"';
8445 $out .= ($value == $obj->rowid ? ' selected' : '');
8446 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
8447 $out .= '>' . $labeltoshow . '</option>';
8448 }
8449
8450 $i++;
8451 }
8452 $this->db->free($resql);
8453 } else {
8454 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
8455 }
8456 } else {
8457 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
8458 $categcode = $InfoFieldList[5];
8459 if (is_numeric($categcode)) { // deprecated: must use the category code instead of id. For backward compatibility.
8460 $tmpcategory = new Categorie($this->db);
8461 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8462 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8463 }
8464
8465 $data = $form->select_all_categories($categcode, '', 'parent', 64, $InfoFieldList[6], 1, 1);
8466 $out .= '<option value="0">&nbsp;</option>';
8467 foreach ($data as $data_key => $data_value) {
8468 $out .= '<option value="' . $data_key . '"';
8469 $out .= ($value == $data_key ? ' selected' : '');
8470 $out .= '>' . $data_value . '</option>';
8471 }
8472 }
8473 }
8474 $out .= '</select>';
8475 } elseif ($type == 'checkbox') {
8476 $value_arr = explode(',', $value);
8477 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, 0, 0, $morecss, 0, '100%');
8478 } elseif ($type == 'radio') {
8479 $out = '';
8480 foreach ($param['options'] as $keyopt => $valopt) {
8481 $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
8482 $out .= ' value="'.$keyopt.'"';
8483 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
8484 $out .= ($value == $keyopt ? 'checked' : '');
8485 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
8486 }
8487 } elseif ($type == 'chkbxlst') {
8488 if (is_array($value)) {
8489 $value_arr = $value;
8490 } else {
8491 $value_arr = explode(',', $value);
8492 }
8493
8494 if (is_array($param['options'])) {
8495 $tmpparamoptions = array_keys($param['options']);
8496 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
8497
8498 $InfoFieldList = explode(":", $paramoptions[0], 5);
8499 // 0 : tableName
8500 // 1 : label field name
8501 // 2 : key fields name (if different of rowid)
8502 // optional parameters...
8503 // 3 : key field parent (for dependent lists). How this is used ?
8504 // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value. Or use USF on a second line separated by "\n".
8505 // 5 : string category type. This replace the filter.
8506 // 6 : ids categories list separated by comma for category root. This replace the filter.
8507 // 7 : sort field
8508
8509 // If there is a filter
8510 if (! empty($InfoFieldList[4])) {
8511 $pos = 0;
8512 $parenthesisopen = 0;
8513 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
8514 if (substr($InfoFieldList[4], $pos, 1) == '(') {
8515 $parenthesisopen++;
8516 }
8517 if (substr($InfoFieldList[4], $pos, 1) == ')') {
8518 $parenthesisopen--;
8519 }
8520 $pos++;
8521 }
8522 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8523 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8524 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
8525 $InfoFieldList[4] = $tmpbefore;
8526 if ($tmpafter !== '') {
8527 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
8528 }
8529
8530 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
8531 $reg = array();
8532 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
8533 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
8534 }
8535
8536 //var_dump($InfoFieldList);
8537 }
8538
8539 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
8540
8541 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8542
8543 $parentName = '';
8544 $parentField = '';
8545
8546 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
8547
8548 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8549 if (strpos($InfoFieldList[4], 'extra.') !== false) {
8550 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
8551 } else {
8552 $keyList = $InfoFieldList[2].' as rowid';
8553 }
8554 }
8555 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8556 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
8557 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra.') !== false) {
8558 $keyList .= ', main.'.$parentField;
8559 } else {
8560 $keyList .= ', '.$parentField;
8561 }
8562 }
8563
8564 $filter_categorie = false;
8565 if (count($InfoFieldList) > 5) {
8566 if ($InfoFieldList[0] == 'categorie') {
8567 $filter_categorie = true;
8568 }
8569 }
8570
8571 // Common filter
8572 if (!$filter_categorie) {
8573 $fields_label = explode('|', $InfoFieldList[1]);
8574 if (is_array($fields_label)) {
8575 $keyList .= ', ';
8576 $keyList .= implode(', ', $fields_label);
8577 }
8578
8579 $sqlwhere = '';
8580 $sql = "SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8581 $sql .= ' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8582
8583 if (!empty($InfoFieldList[4])) {
8584 // can use SELECT request
8585 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
8586 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
8587 }
8588
8589 // current object id can be use into filter
8590 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
8591 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
8592 } else {
8593 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
8594 }
8595
8596 // We have to join on extrafield table
8597 $errstr = '';
8598 if (strpos($InfoFieldList[4], 'extra') !== false) {
8599 $sql .= ' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . '_extrafields as extra';
8600 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8601 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8602 } else {
8603 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8604 }
8605 } else {
8606 $sqlwhere .= ' WHERE 1=1';
8607 }
8608
8609 // Add Usf filter on second line
8610 /*
8611 if ($Usf) {
8612 $errorstr = '';
8613 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
8614 if (!$errorstr) {
8615 $sqlwhere .= $sqlusf;
8616 } else {
8617 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
8618 }
8619 }
8620 */
8621
8622 // Some tables may have field, some other not. For the moment we disable it.
8623 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
8624 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
8625 }
8626 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
8627 // print $sql;
8628
8629 $sql .= $sqlwhere;
8630
8631 dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
8632
8633 $resql = $this->db->query($sql);
8634 if ($resql) {
8635 $num = $this->db->num_rows($resql);
8636 $i = 0;
8637
8638 $data = array();
8639
8640 while ($i < $num) {
8641 $labeltoshow = '';
8642 $obj = $this->db->fetch_object($resql);
8643
8644 $notrans = false;
8645 // Several field into label (eq table:code|libelle:rowid)
8646 $fields_label = explode('|', $InfoFieldList[1]);
8647 if (count($fields_label) > 1) {
8648 $notrans = true;
8649 foreach ($fields_label as $field_toshow) {
8650 $labeltoshow .= $obj->$field_toshow . ' ';
8651 }
8652 } else {
8653 $labeltoshow = $obj->{$InfoFieldList[1]};
8654 }
8655 $labeltoshow = dol_trunc($labeltoshow, 45);
8656
8657 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8658 foreach ($fields_label as $field_toshow) {
8659 $translabel = $langs->trans($obj->$field_toshow);
8660 if ($translabel != $obj->$field_toshow) {
8661 $labeltoshow = dol_trunc($translabel, 18) . ' ';
8662 } else {
8663 $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
8664 }
8665 }
8666
8667 $data[$obj->rowid] = $labeltoshow;
8668 } else {
8669 if (!$notrans) {
8670 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8671 if ($translabel != $obj->{$InfoFieldList[1]}) {
8672 $labeltoshow = dol_trunc($translabel, 18);
8673 } else {
8674 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
8675 }
8676 }
8677 if (empty($labeltoshow)) {
8678 $labeltoshow = '(not defined)';
8679 }
8680
8681 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8682 $data[$obj->rowid] = $labeltoshow;
8683 }
8684
8685 if (!empty($InfoFieldList[3]) && $parentField) {
8686 $parent = $parentName . ':' . $obj->{$parentField};
8687 $isDependList = 1;
8688 }
8689
8690 $data[$obj->rowid] = $labeltoshow; // Warning: $obj->rowid is an alias and can be an int, but also a string ref.
8691 }
8692
8693 $i++;
8694 }
8695 $this->db->free($resql);
8696
8697 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
8698 } else {
8699 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
8700 }
8701 } else {
8702 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
8703 $categcode = $InfoFieldList[5];
8704 if (is_numeric($categcode)) { // deprecated: must use the category code instead of id. For backward compatibility.
8705 $tmpcategory = new Categorie($this->db);
8706 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8707 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8708 }
8709
8710 $data = $form->select_all_categories($categcode, '', 'parent', 64, $InfoFieldList[6], 1, 1);
8711 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
8712 }
8713 }
8714 } elseif ($type == 'link') {
8715 // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
8716 // Filter can contains some ':' inside.
8717 $param_list = array_keys($param['options']);
8718 $param_list_array = explode(':', $param_list[0], 4);
8719
8720 $showempty = (($required && $default != '') ? 0 : 1);
8721
8722 if (!preg_match('/search_/', $keyprefix)) {
8723 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
8724 // @phan-suppress-next-line PhanTypeMismatchProperty
8725 if (!empty($this->fields[$key]['picto'])) {
8726 $morecss .= ' widthcentpercentminusxx';
8727 } else {
8728 $morecss .= ' widthcentpercentminusx';
8729 }
8730 } else {
8731 // @phan-suppress-next-line PhanTypeMismatchProperty
8732 if (!empty($this->fields[$key]['picto'])) {
8733 $morecss .= ' widthcentpercentminusx';
8734 }
8735 }
8736 }
8737
8738 // $param_list_array[0] can be the name of object (Example 'User' the field is linked to). Not as taking the information from the record in ->fields found from $objectfield.
8739
8740 // $val is already the record field found at same place than found by $valparent but already loaded and may have been modified by parent caller.
8741
8742 $objectfield = $val;
8743
8744 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
8745 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (int) $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), '', $objectfield);
8746
8747 if (!empty($param_list_array[2])) { // If the entry into $fields is set, we must add a create button
8748 if ((!GETPOSTISSET('backtopage') || strpos(GETPOST('backtopage'), $_SERVER['PHP_SELF']) === 0) // // To avoid to open several times the 'Plus' button (we accept only one level)
8749 && empty($val['disabled']) && empty($nonewbutton)) { // and to avoid to show the button if the field is protected by a "disabled".
8750 list($class, $classfile) = explode(':', $param_list[0]);
8751 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
8752 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
8753 } else {
8754 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
8755 }
8756 $paramforthenewlink = '';
8757 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
8758 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOSTINT('id') : '');
8759 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
8760 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOSTINT('originid') : '');
8761 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
8762 // TODO Add JavaScript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
8763 $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>';
8764 }
8765 }
8766 } elseif ($type == 'password') {
8767 // If prefix is 'search_', field is used as a filter, we use a common text field.
8768 if ($keyprefix.$key.$keysuffix == 'pass_crypted') {
8769 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="pass" id="pass" value="" '.($moreparam ? $moreparam : '').'>';
8770 $out .= '<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
8771 } else {
8772 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
8773 }
8774 } elseif ($type == 'array') {
8775 $newval = $val;
8776 $newval['type'] = 'varchar(256)';
8777
8778 $out = '';
8779 if (!empty($value)) {
8780 foreach ($value as $option) {
8781 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8782 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
8783 }
8784 }
8785 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8786
8787 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8788 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
8789
8790 if (!empty($conf->use_javascript_ajax)) {
8791 $out .= '
8792 <script nonce="'.getNonce().'">
8793 $(document).ready(function() {
8794 $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
8795 $("'.dol_escape_js($newInput).'").insertBefore(this);
8796 });
8797
8798 $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
8799 $(this).parent().remove();
8800 });
8801 });
8802 </script>';
8803 }
8804 }
8805 if (!empty($hidden)) {
8806 $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
8807 }
8808
8809 if ($isDependList == 1) {
8810 $out .= $this->getJSListDependancies('_common');
8811 }
8812 /* Add comments
8813 if ($type == 'date') $out.=' (YYYY-MM-DD)';
8814 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
8815 */
8816
8817 // Display error message for field
8818 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
8819 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
8820 }
8821
8822 return $out;
8823 }
8824
8838 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
8839 {
8840 global $conf, $langs, $form;
8841
8842 // TODO pass the current object as a parameter to give more flexibility (like disable ajax update when canAlwaysBeEdited is false and $object->status is not draft...)
8843
8844 if (!is_object($form)) {
8845 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
8846 $form = new Form($this->db);
8847 }
8848
8849 //$label = empty($val['label']) ? '' : $val['label'];
8850 $type = empty($val['type']) ? '' : $val['type'];
8851 $size = empty($val['css']) ? '' : $val['css'];
8852
8853 $reg = array();
8854
8855 // Convert var to be able to share same code than showOutputField of extrafields
8856 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8857 $type = 'varchar'; // convert varchar(xx) int varchar
8858 $size = $reg[1];
8859 } elseif (preg_match('/varchar/', $type)) {
8860 $type = 'varchar'; // convert varchar(xx) int varchar
8861 }
8862 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8863 // @phan-suppress-next-line PhanTypeMismatchProperty
8864 if (empty($this->fields[$key]['multiinput'])) {
8865 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
8866 }
8867 }
8868 if (isset($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8869 $type = 'link';
8870 }
8871
8872 $default = empty($val['default']) ? '' : $val['default'];
8873 $computed = empty($val['computed']) ? '' : $val['computed'];
8874 $unique = empty($val['unique']) ? '' : $val['unique'];
8875 $required = empty($val['required']) ? '' : $val['required'];
8876 $param = array();
8877 $param['options'] = array();
8878
8879 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8880 $param['options'] = $val['arrayofkeyval'];
8881 }
8882 if (isset($val['type']) && preg_match('/^integer:([^:]*):([^:]*)/i', $val['type'], $reg)) { // ex: integer:User:user/class/user.class.php
8883 $type = 'link';
8884 $stringforoptions = $reg[1].':'.$reg[2];
8885 // Special case: Force addition of getnomurlparam1 to -1 for users
8886 if ($reg[1] == 'User') {
8887 $stringforoptions .= ':#getnomurlparam1=-1';
8888 }
8889 $param['options'] = array($stringforoptions => $stringforoptions);
8890 } elseif (isset($val['type']) && preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8891 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8892 $type = 'sellist';
8893 } elseif (isset($val['type']) && preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8894 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8895 $type = 'sellist';
8896 } elseif (isset($val['type']) && preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8897 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8898 $type = 'sellist';
8899 } elseif (isset($val['type']) && preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
8900 $param['options'] = array($reg[1] => 'N');
8901 $type = 'chkbxlst';
8902 } elseif (isset($val['type']) && preg_match('/stars\‍((\d+)\‍)/', $val['type'], $reg)) {
8903 $param['options'] = array();
8904 $type = 'stars';
8905 $size = $reg[1];
8906 }
8907
8908 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
8909 $list = (empty($val['list']) ? '' : $val['list']);
8910 $help = (empty($val['help']) ? '' : $val['help']);
8911 $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)
8912
8913 if ($hidden) {
8914 return '';
8915 }
8916
8917 // If field is a computed field, value must become result of compute
8918 if ($computed) {
8919 // Make the eval of compute string
8920 //var_dump($computed);
8921 $value = dol_eval((string) $computed, 1, 0, '2');
8922 }
8923
8924 if (empty($morecss)) {
8925 if ($type == 'date') {
8926 $morecss = 'minwidth100imp';
8927 } elseif ($type == 'datetime' || $type == 'timestamp') {
8928 $morecss = 'minwidth200imp';
8929 } elseif (in_array($type, array('int', 'double', 'price'))) {
8930 $morecss = 'maxwidth75';
8931 } elseif ($type == 'url') {
8932 $morecss = 'minwidth400';
8933 } elseif ($type == 'boolean') {
8934 $morecss = '';
8935 } else {
8936 if (is_numeric($size) && round((float) $size) < 12) {
8937 $morecss = 'minwidth100';
8938 } elseif (is_numeric($size) && round((float) $size) <= 48) {
8939 $morecss = 'minwidth200';
8940 } else {
8941 $morecss = 'minwidth400';
8942 }
8943 }
8944 }
8945
8946 // Format output value differently according to properties of field
8947 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
8948 // @phan-suppress-next-line PhanTypeMismatchProperty
8949 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.
8950 $value = $this->getNomUrl(1, '', 0, '', 1);
8951 }
8952 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
8953 $value = $this->getLibStatut(3);
8954 } elseif ($type == 'date') {
8955 if (!empty($value)) {
8956 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
8957 } else {
8958 $value = '';
8959 }
8960 } elseif ($type == 'datetime' || $type == 'timestamp') {
8961 if (!empty($value)) {
8962 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
8963 } else {
8964 $value = '';
8965 }
8966 } elseif ($type == 'duration') {
8967 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
8968 if (!is_null($value) && $value !== '') {
8969 $value = convertSecondToTime((int) $value, 'allhourmin');
8970 }
8971 } elseif ($type == 'double' || $type == 'real') {
8972 if (!is_null($value) && $value !== '') {
8973 $value = price($value);
8974 }
8975 } elseif ($type == 'boolean') {
8976 $checked = '';
8977 if (!empty($value)) {
8978 $checked = ' checked ';
8979 }
8980 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
8981 $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
8982 } else {
8983 $value = yn($value ? 1 : 0);
8984 }
8985 } elseif ($type == 'mail' || $type == 'email') {
8986 $value = dol_print_email((string) $value, 0, 0, 0, 64, 1, 1);
8987 } elseif ($type == 'url') {
8988 $value = dol_print_url((string) $value, '_blank', 32, 1);
8989 } elseif ($type == 'phone') {
8990 $value = dol_print_phone((string) $value, '', 0, 0, '', '&nbsp;', 'phone');
8991 } elseif ($type == 'ip') {
8992 $value = dol_print_ip((string) $value, 0);
8993 } elseif ($type == 'stars') {
8994 $value = '<input type="hidden" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.$this->id.'" value="'.dol_escape_htmltag((string) $value).'"'.($moreparam ? $moreparam : '').'>';
8995 $value .= '<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.'_selection">';
8996 $i = 1;
8997 while ($i <= $size) {
8998 $value .= '<span class="star" data-value="'.$i.'">'.img_picto('', 'fontawesome_star_fas').'</span>';
8999 $i++;
9000 }
9001 $value .= '</div>';
9002 $value .= '<script>
9003 $(document).ready(function() { /* commonobject.class.php 2 */
9004 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.'_selection");
9005 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.'").val()) || 0;
9006 container.find(".star").each(function() {
9007 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9008 });
9009 container.find(".star").on("mouseover", function() {
9010 let selectedStar = $(this).data("value");
9011 container.find(".star").each(function() {
9012 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9013 });
9014 });
9015 container.on("mouseout", function() {
9016 container.find(".star").each(function() {
9017 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9018 });
9019 });
9020 container.find(".star").off("click").on("click", function() {
9021 selectedStars = $(this).data("value");
9022 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.'").val() == 1) {
9023 selectedStars = 0;
9024 }
9025 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.'").val(selectedStars);
9026 container.find(".star").each(function() {
9027 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9028 });
9029 $.ajax({
9030 url: "ajax/'.$this->element.'.php",
9031 method: "POST",
9032 data: {
9033 objectId: "'.$this->id.'",
9034 field: "'.$keyprefix.$key.$keysuffix.'",
9035 value: selectedStars,
9036 token: "'.newToken().'"
9037 },
9038 success: function(response) {
9039 var res = JSON.parse(response);
9040 console[res.status === "success" ? "log" : "error"](res.message);
9041 },
9042 error: function(xhr, status, error) {
9043 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.':", error);
9044 }
9045 });
9046 });
9047 });
9048 </script>';
9049 } elseif ($type == 'price') {
9050 if (!is_null($value) && $value !== '') {
9051 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
9052 }
9053 } elseif ($type == 'select') {
9054 $value = isset($param['options'][(string) $value]) ? $param['options'][(string) $value] : '';
9055 if (strpos($value, "|") !== false) {
9056 $value = $langs->trans(explode('|', $value)[0]);
9057 } elseif (! is_numeric($value)) {
9058 $value = $langs->trans($value);
9059 }
9060 } elseif ($type == 'sellist') {
9061 $param_list = array_keys($param['options']);
9062 $InfoFieldList = explode(":", $param_list[0]);
9063
9064 $selectkey = "rowid";
9065 $keyList = 'rowid';
9066
9067 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9068 $selectkey = $InfoFieldList[2];
9069 $keyList = $InfoFieldList[2].' as rowid';
9070 }
9071
9072 $fields_label = explode('|', $InfoFieldList[1]);
9073 if (is_array($fields_label)) {
9074 $keyList .= ', ';
9075 $keyList .= implode(', ', $fields_label);
9076 }
9077
9078 $filter_categorie = false;
9079 if (count($InfoFieldList) > 5) {
9080 if ($InfoFieldList[0] == 'categorie') {
9081 $filter_categorie = true;
9082 }
9083 }
9084
9085 $sql = "SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9086 $sql .= ' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9087 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra') !== false) {
9088 $sql .= ' as main';
9089 }
9090 if ($selectkey == 'rowid' && empty($value)) {
9091 $sql .= " WHERE ".$this->db->sanitize($selectkey)." = 0";
9092 } elseif ($selectkey == 'rowid') {
9093 $sql .= " WHERE ".$this->db->sanitize($selectkey)." = ".((int) $value);
9094 } else {
9095 $sql .= " WHERE ".$this->db->sanitize($selectkey)." = '".$this->db->escape((string) $value)."'";
9096 }
9097
9098 //$sql.= ' AND entity = '.((int) $conf->entity);
9099
9100 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
9101 $resql = $this->db->query($sql);
9102 if ($resql) {
9103 if (!$filter_categorie) {
9104 $value = ''; // value was used, so now we reset it to use it to build final output
9105 $numrows = $this->db->num_rows($resql);
9106 if ($numrows) {
9107 $obj = $this->db->fetch_object($resql);
9108
9109 // Several field into label (eq table:code|libelle:rowid)
9110 $fields_label = explode('|', $InfoFieldList[1]);
9111
9112 if (is_array($fields_label) && count($fields_label) > 1) {
9113 foreach ($fields_label as $field_toshow) {
9114 $translabel = '';
9115 if (!empty($obj->$field_toshow)) {
9116 $translabel = $langs->trans($obj->$field_toshow);
9117 }
9118 if ($translabel != $field_toshow) {
9119 $value .= dol_trunc($translabel, 18) . ' ';
9120 } else {
9121 $value .= $obj->$field_toshow . ' ';
9122 }
9123 }
9124 } else {
9125 $translabel = '';
9126 if (!empty($obj->{$InfoFieldList[1]})) {
9127 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9128 }
9129 if ($translabel != $obj->{$InfoFieldList[1]}) {
9130 $value = dol_trunc($translabel, 18);
9131 } else {
9132 $value = $obj->{$InfoFieldList[1]};
9133 }
9134 }
9135 }
9136 } else {
9137 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
9138
9139 $toprint = array();
9140 $obj = $this->db->fetch_object($resql);
9141 $c = new Categorie($this->db);
9142 $c->fetch($obj->rowid);
9143 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
9144 foreach ($ways as $way) {
9145 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
9146 }
9147 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
9148 }
9149 } else {
9150 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9151 }
9152 } elseif ($type == 'radio') {
9153 $value = $param['options'][(string) $value];
9154 } elseif ($type == 'checkbox') {
9155 $value_arr = explode(',', (string) $value);
9156 $value = '';
9157 if (is_array($value_arr) && count($value_arr) > 0) {
9158 $toprint = array();
9159 foreach ($value_arr as $keyval => $valueval) {
9160 if (!empty($valueval)) {
9161 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param['options'][$valueval] . '</li>';
9162 }
9163 }
9164 if (!empty($toprint)) {
9165 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
9166 }
9167 }
9168 } elseif ($type == 'chkbxlst') {
9169 $value_arr = (isset($value) ? explode(',', $value) : array());
9170
9171 $param_list = array_keys($param['options']);
9172 $InfoFieldList = explode(":", $param_list[0]);
9173
9174 $selectkey = "rowid";
9175 $keyList = 'rowid';
9176
9177 if (count($InfoFieldList) >= 3) {
9178 $selectkey = $InfoFieldList[2];
9179 $keyList = $InfoFieldList[2].' as rowid';
9180 }
9181
9182 $fields_label = explode('|', $InfoFieldList[1]);
9183 if (is_array($fields_label)) {
9184 $keyList .= ', ';
9185 $keyList .= implode(', ', $fields_label);
9186 }
9187
9188 $filter_categorie = false;
9189 if (count($InfoFieldList) > 5) {
9190 if ($InfoFieldList[0] == 'categorie') {
9191 $filter_categorie = true;
9192 }
9193 }
9194
9195 $sql = "SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9196 $sql .= ' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9197 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra') !== false) {
9198 $sql .= ' as main';
9199 }
9200 // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
9201 // $sql.= ' AND entity = '.((int) $conf->entity);
9202
9203 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
9204 $resql = $this->db->query($sql);
9205 if ($resql) {
9206 if (!$filter_categorie) {
9207 $value = ''; // value was used, so now we reset it to use it to build final output
9208 $toprint = array();
9209 while ($obj = $this->db->fetch_object($resql)) {
9210 // Several field into label (eq table:code|libelle:rowid)
9211 $fields_label = explode('|', $InfoFieldList[1]);
9212 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9213 if (is_array($fields_label) && count($fields_label) > 1) {
9214 foreach ($fields_label as $field_toshow) {
9215 $translabel = '';
9216 if (!empty($obj->$field_toshow)) {
9217 $translabel = $langs->trans($obj->$field_toshow);
9218 }
9219 if ($translabel != $field_toshow) {
9220 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
9221 } else {
9222 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
9223 }
9224 }
9225 } else {
9226 $translabel = '';
9227 if (!empty($obj->{$InfoFieldList[1]})) {
9228 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9229 }
9230 if ($translabel != $obj->{$InfoFieldList[1]}) {
9231 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
9232 } else {
9233 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
9234 }
9235 }
9236 }
9237 }
9238 } else {
9239 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
9240
9241 $toprint = array();
9242 while ($obj = $this->db->fetch_object($resql)) {
9243 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9244 $c = new Categorie($this->db);
9245 $c->fetch($obj->rowid);
9246 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
9247 foreach ($ways as $way) {
9248 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
9249 }
9250 }
9251 }
9252 }
9253 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
9254 } else {
9255 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9256 }
9257 } elseif ($type == 'link') {
9258 $out = '';
9259
9260 // only if something to display (perf)
9261 if ($value) {
9262 $param_list = array_keys($param['options']);
9263 // Example: $param_list='ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
9264 // Example: $param_list='ObjectClass:PathToClass:#getnomurlparam1=-1#getnomurlparam2=customer'
9265
9266 $InfoFieldList = explode(":", $param_list[0]);
9267
9268 $classname = $InfoFieldList[0];
9269 $classpath = $InfoFieldList[1];
9270
9271 // Set $getnomurlparam1 et getnomurlparam2
9272 $getnomurlparam = 3;
9273 $getnomurlparam2 = '';
9274 $regtmp = array();
9275 if (preg_match('/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9276 $getnomurlparam = $regtmp[1];
9277 }
9278 if (preg_match('/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9279 $getnomurlparam2 = $regtmp[1];
9280 }
9281
9282 if (!empty($classpath)) {
9283 dol_include_once($InfoFieldList[1]);
9284
9285 if ($classname && !class_exists($classname)) {
9286 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
9287 // TODO use newObjectByElement() introduce in V20 by PR #30036 for better errors management
9288 $element_prop = getElementProperties($classname);
9289 if ($element_prop) {
9290 $classname = $element_prop['classname'];
9291 }
9292 }
9293
9294
9295 if ($classname && class_exists($classname)) {
9296 $object = new $classname($this->db);
9297 '@phan-var-force CommonObject $object';
9298 if ($object->element === 'product') { // Special case for product because default valut of fetch are wrong
9299 '@phan-var-force Product $object';
9300 $result = $object->fetch((int) $value, '', '', '', 0, 1, 1);
9301 } else {
9302 $result = $object->fetch($value);
9303 }
9304 if ($result > 0) {
9305 if ($object->element === 'product') {
9306 '@phan-var-force Product $object';
9307 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
9308 if (isset($val['get_name_url_params'])) {
9309 $get_name_url_params = explode(':', $val['get_name_url_params']);
9310 if (!empty($get_name_url_params)) {
9311 $param_num_max = count($get_name_url_param_arr) - 1;
9312 foreach ($get_name_url_params as $param_num => $param_value) {
9313 if ($param_num > $param_num_max) {
9314 break;
9315 }
9316 $get_name_url_param_arr[$param_num] = $param_value;
9317 }
9318 }
9319 }
9320
9324 $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]);
9325 } else {
9326 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
9327 }
9328 } else {
9329 $value = '';
9330 }
9331 }
9332 } else {
9333 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
9334 return 'Error bad setup of extrafield';
9335 }
9336 } else {
9337 $value = '';
9338 }
9339 } elseif ($type == 'password') {
9340 $value = '<span class="opacitymedium">'.$langs->trans("Encrypted").'</span>';
9341 //$value = preg_replace('/./i', '*', $value);
9342 } elseif ($type == 'array') {
9343 if (is_array($value)) {
9344 $value = implode('<br>', $value);
9345 } else {
9346 dol_syslog(__METHOD__.' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9347 return 'Error unexpected result from code evaluation';
9348 }
9349 } else { // text|html|varchar
9350 if (!empty($value) && preg_match('/^text/', (string) $type) && !preg_match('/search_/', $keyprefix) && !empty($param['options'])) {
9351 $value = str_replace(',', "\n", $value);
9352 }
9353 $value = dol_htmlentitiesbr((string) $value);
9354 }
9355
9356 //print $type.'-'.$size.'-'.$value;
9357 $out = $value;
9358
9359 return is_null($out) ? '' : $out;
9360 }
9361
9368 public function clearFieldError($fieldKey)
9369 {
9370 $this->error = '';
9371 unset($this->validateFieldsErrors[$fieldKey]);
9372 }
9373
9381 public function setFieldError($fieldKey, $msg = '')
9382 {
9383 global $langs;
9384 if (empty($msg)) {
9385 $msg = $langs->trans("UnknownError");
9386 }
9387
9388 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9389 }
9390
9397 public function getFieldError($fieldKey)
9398 {
9399 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9400 return $this->validateFieldsErrors[$fieldKey];
9401 }
9402 return '';
9403 }
9404
9413 public function validateField($fields, $fieldKey, $fieldValue)
9414 {
9415 global $langs;
9416
9417 if (!class_exists('Validate')) {
9418 require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
9419 }
9420
9421 $this->clearFieldError($fieldKey);
9422
9423 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9424 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
9425 return false;
9426 }
9427
9428 $val = $fields[$fieldKey];
9429
9430 $param = array();
9431 $param['options'] = array();
9432 $type = $val['type'];
9433
9434 $required = false;
9435 if (isset($val['notnull']) && $val['notnull'] === 1) {
9436 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
9437 $required = true;
9438 }
9439
9440 $maxSize = 0;
9441 $minSize = 0;
9442
9443 //
9444 // PREPARE Elements
9445 //
9446 $reg = array();
9447
9448 // Convert var to be able to share same code than showOutputField of extrafields
9449 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
9450 $type = 'varchar'; // convert varchar(xx) int varchar
9451 $maxSize = (int) $reg[1];
9452 } elseif (preg_match('/varchar/', $type)) {
9453 $type = 'varchar'; // convert varchar(xx) int varchar
9454 }
9455
9456 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
9457 $type = 'select';
9458 }
9459
9460 if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
9461 $type = 'link';
9462 }
9463
9464 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
9465 $param['options'] = $val['arrayofkeyval'];
9466 }
9467
9468 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
9469 $type = 'link';
9470 $param['options'] = array($reg[1].':'.$reg[2] => $reg[1].':'.$reg[2]);
9471 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
9472 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
9473 $type = 'sellist';
9474 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
9475 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
9476 $type = 'sellist';
9477 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
9478 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
9479 $type = 'sellist';
9480 }
9481
9482 //
9483 // TEST Value
9484 //
9485
9486 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
9487 $validate = new Validate($this->db, $langs);
9488
9489
9490 // little trick : to perform tests with good performances sort tests by quick to low
9491
9492 //
9493 // COMMON TESTS
9494 //
9495
9496 // Required test and empty value
9497 if ($required && !$validate->isNotEmptyString($fieldValue)) {
9498 $this->setFieldError($fieldKey, $validate->error);
9499 return false;
9500 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
9501 // if no value sent and the field is not mandatory, no need to perform tests
9502 return true;
9503 }
9504
9505 // MAX Size test
9506 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
9507 $this->setFieldError($fieldKey, $validate->error);
9508 return false;
9509 }
9510
9511 // MIN Size test
9512 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
9513 $this->setFieldError($fieldKey, $validate->error);
9514 return false;
9515 }
9516
9517 //
9518 // TESTS for TYPE
9519 //
9520
9521 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
9522 if (!$validate->isTimestamp($fieldValue)) {
9523 $this->setFieldError($fieldKey, $validate->error);
9524 return false;
9525 } else {
9526 return true;
9527 }
9528 } elseif ($type == 'duration') {
9529 if (!$validate->isDuration($fieldValue)) {
9530 $this->setFieldError($fieldKey, $validate->error);
9531 return false;
9532 } else {
9533 return true;
9534 }
9535 } elseif (in_array($type, array('double', 'real', 'price'))) {
9536 // is numeric
9537 if (!$validate->isNumeric($fieldValue)) {
9538 $this->setFieldError($fieldKey, $validate->error);
9539 return false;
9540 } else {
9541 return true;
9542 }
9543 } elseif ($type == 'boolean') {
9544 if (!$validate->isBool($fieldValue)) {
9545 $this->setFieldError($fieldKey, $validate->error);
9546 return false;
9547 } else {
9548 return true;
9549 }
9550 } elseif ($type == 'mail' || $type == 'email') {
9551 if (!$validate->isEmail($fieldValue)) {
9552 $this->setFieldError($fieldKey, $validate->error);
9553 return false;
9554 }
9555 } elseif ($type == 'url') {
9556 if (!$validate->isUrl($fieldValue)) {
9557 $this->setFieldError($fieldKey, $validate->error);
9558 return false;
9559 } else {
9560 return true;
9561 }
9562 } elseif ($type == 'phone') {
9563 if (!$validate->isPhone($fieldValue)) {
9564 $this->setFieldError($fieldKey, $validate->error);
9565 return false;
9566 } else {
9567 return true;
9568 }
9569 } elseif ($type == 'select' || $type == 'radio') {
9570 if (!isset($param['options'][$fieldValue])) {
9571 $this->error = $langs->trans('RequireValidValue');
9572 return false;
9573 } else {
9574 return true;
9575 }
9576 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
9577 $param_list = array_keys($param['options']);
9578 $InfoFieldList = explode(":", $param_list[0]);
9579 $value_arr = explode(',', $fieldValue);
9580
9581 $selectkey = "rowid";
9582 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9583 $selectkey = $InfoFieldList[2];
9584 }
9585
9586 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9587 $this->setFieldError($fieldKey, $validate->error);
9588 return false;
9589 } else {
9590 return true;
9591 }
9592 } elseif ($type == 'link') {
9593 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
9594 $InfoFieldList = explode(":", $param_list[0]);
9595 $classname = $InfoFieldList[0];
9596 $classpath = $InfoFieldList[1];
9597 if (!$validate->isFetchable((int) $fieldValue, $classname, $classpath)) {
9598 $lastIsFetchableError = $validate->error;
9599
9600 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
9601 if ($validate->isFetchableElement((int) $fieldValue, $classname)) {
9602 return true;
9603 }
9604
9605 $this->setFieldError($fieldKey, $lastIsFetchableError);
9606 return false;
9607 } else {
9608 return true;
9609 }
9610 }
9611
9612 // if no test failed all is ok
9613 return true;
9614 }
9615
9629 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = '', $display_type = 'card')
9630 {
9631 global $db, $conf, $langs, $action, $form, $hookmanager;
9632 global $objectoffield;
9633
9634 if (!is_object($form)) {
9635 $form = new Form($db);
9636 }
9637 if (!is_object($extrafields)) {
9638 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
9639 return 'Bad parameter extrafields for showOptionals';
9640 }
9641 if (!is_array($extrafields->attributes[$this->table_element])) {
9642 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9643 }
9644
9645 // Ensure $objectoffield is available for dol_eval visibility formulas.
9646 $objectoffield = $this;
9647
9648 $out = '';
9649
9650 $parameters = array('mode' => $mode, 'params' => $params, 'keysuffix' => $keysuffix, 'keyprefix' => $keyprefix, 'display_type' => $display_type);
9651 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
9652 $hookResPrint = $hookmanager->resPrint;
9653
9654 if (empty($reshook)) {
9655 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) {
9656 $out .= "\n";
9657 $out .= '<!-- commonobject:showOptionals --> ';
9658 $out .= "\n";
9659
9660 $nbofextrafieldsshown = 0;
9661 $e = 0; // var to manage the modulo (odd/even)
9662
9663 $lastseparatorkeyfound = '';
9664 $extrafields_collapse_num = '';
9665 $extrafields_collapse_num_old = '';
9666 $i = 0;
9667
9668 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
9669 $i++;
9670
9671 // Show only the key field in params @phan-suppress-next-line PhanTypeArraySuspiciousNullable
9672 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
9673 continue;
9674 }
9675
9676 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
9677 $enabled = 1;
9678 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
9679 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
9680 }
9681 if (empty($enabled)) {
9682 continue;
9683 }
9684
9685 $visibility = 1;
9686 if (isset($extrafields->attributes[$this->table_element]['list'][$key])) {
9687 $visibility = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
9688 }
9689
9690 $perms = 1;
9691 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
9692 $perms = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
9693 }
9694
9695 if (($mode == 'create') && !in_array(abs($visibility), array(1, 3))) {
9696 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
9697 } elseif (($mode == 'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9698 // We need to make sure, that the values of hidden extrafields are also part of $_POST.
9699 // Otherwise, they would be empty after an update of the object. See also getOptionalsFromPost
9700 // TODO: We should not have this hidden field, and action='update' should be done only if field was POSTED by form.
9701 $ef_name = 'options_' . $key;
9702 $ef_value = $this->array_options[$ef_name] ?? '';
9703 $out .= '<input type="hidden" name="' . $ef_name . '" id="' . $ef_name . '" value="' . dolPrintHTMLForAttribute($ef_value) . '" />' . "\n"; // If trouble to preserve content, we can try dol_htmlentities() instead, but real solution is to remove completely the hidden field (see previous TODO).
9704 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
9705 } elseif ($mode == 'view' && empty($visibility)) {
9706 continue;
9707 }
9708 if (empty($perms)) {
9709 continue;
9710 }
9711
9712 // Load language if required
9713 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
9714 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
9715 }
9716
9717 $colspan = 0;
9718 $value = null;
9719 if (is_array($params) && count($params) > 0 && $display_type == 'card') {
9720 if (array_key_exists('cols', $params)) {
9721 $colspan = $params['cols'];
9722 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
9723 $reg = array();
9724 if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
9725 $colspan = $reg[1];
9726 } else {
9727 $colspan = $params['colspan'];
9728 }
9729 }
9730 }
9731 $colspan = intval($colspan);
9732
9733 switch ($mode) {
9734 case "view":
9735 $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
9736 break;
9737 case "create":
9738 case "edit":
9739 // We get the value of property found with GETPOST so it takes into account:
9740 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
9741 $check = 'alphanohtml';
9742 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
9743 $check = 'restricthtml';
9744 }
9745 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
9746 // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
9747 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
9748 if (is_array($getposttemp)) {
9749 // $getposttemp is an array but following code expects a comma separated string
9750 $value = implode(",", $getposttemp);
9751 } else {
9752 $value = $getposttemp;
9753 }
9754 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('int'))) {
9755 $value = (!empty($this->array_options["options_".$key]) || (isset($this->array_options["options_".$key]) && $this->array_options["options_".$key] === '0')) ? $this->array_options["options_".$key] : '';
9756 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('varchar', 'char'))) {
9757 $value = (isset($this->array_options["options_".$key]) && $this->array_options["options_".$key] !== '') ? $this->array_options["options_".$key] : '';
9758 } else {
9759 $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.
9760 }
9761 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
9762 break;
9763 }
9764
9765 $nbofextrafieldsshown++;
9766
9767 // Output value of the current field
9768 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
9769 $extrafields_collapse_num = $key;
9770 /*
9771 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
9772 if (!empty($extrafield_param) && is_array($extrafield_param)) {
9773 $extrafield_param_list = array_keys($extrafield_param['options']);
9774
9775 if (count($extrafield_param_list) > 0) {
9776 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
9777
9778 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
9779 //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
9780 $extrafields_collapse_num = $key;
9781 }
9782 }
9783 }
9784 */
9785
9786 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
9787 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9788
9789 $lastseparatorkeyfound = $key;
9790 } else {
9791 $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
9792
9793 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
9794 $csstyle = '';
9795 if (is_array($params) && count($params) > 0) {
9796 if (array_key_exists('class', $params)) {
9797 $class .= $params['class'].' ';
9798 }
9799 if (array_key_exists('style', $params)) {
9800 $csstyle = $params['style'];
9801 }
9802 }
9803
9804 // add html5 elements
9805 $domData = ' data-element="extrafield"';
9806 $domData .= ' data-targetelement="'.$this->element.'"';
9807 $domData .= ' data-targetid="'.$this->id.'"';
9808
9809 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
9810 if ($display_type == 'card') {
9811 if (getDolGlobalString('MAIN_EXTRAFIELDS_USE_TWO_COLUMS') && ($e % 2) == 0) {
9812 $colspan = 0;
9813 }
9814
9815 if ($action == 'selectlines') {
9816 $colspan++;
9817 }
9818 }
9819
9820 // Expected behavior : if THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_XXX is set, when we change company,
9821 // Then we use the extrafields of the object (they are filled in the card when constant THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_XXX is set)
9822 $force_values_on_change_company = (
9823 ($this->element == 'facture' && getDolGlobalInt('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
9824 || ($this->element == 'commande' && getDolGlobalInt('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
9825 || ($this->element == 'order_supplier' && getDolGlobalInt('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
9826 );
9827 if ($force_values_on_change_company && GETPOSTINT('changecompany')) {
9828 $value = $this->array_options['options_'.$key] ?? $value;
9829 }
9830
9831 // Convert date into timestamp format (value in memory must be a timestamp)
9832 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
9833 $datenotinstring = null;
9834 if (array_key_exists('options_'.$key, $this->array_options)) {
9835 $datenotinstring = $this->array_options['options_'.$key];
9836 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
9837 $datenotinstring = $this->db->jdate($datenotinstring);
9838 }
9839 }
9840 $datekey = $keyprefix.'options_'.$key.$keysuffix;
9841 $value = (GETPOSTISSET($datekey) && $this->id == GETPOST('elrowid', 'int')) ? dol_mktime(12, 0, 0, GETPOSTINT($datekey.'month', 3), GETPOSTINT($datekey.'day', 3), GETPOSTINT($datekey.'year', 3)) : $datenotinstring;
9842 }
9843 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
9844 $datenotinstring = null;
9845 if (array_key_exists('options_'.$key, $this->array_options)) {
9846 $datenotinstring = $this->array_options['options_'.$key];
9847 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
9848 $datenotinstring = $this->db->jdate($datenotinstring);
9849 }
9850 }
9851 $timekey = $keyprefix.'options_'.$key.$keysuffix;
9852 $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;
9853 }
9854 // Convert float submitted string into real php numeric (value in memory must be a php numeric)
9855 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
9856 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
9857 $value = price2num($value);
9858 } elseif (isset($this->array_options['options_'.$key])) {
9859 $value = $this->array_options['options_'.$key];
9860 }
9861 }
9862
9863 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
9864 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'radio', 'int', 'boolean'))) {
9865 if ($action == 'create' || $mode == 'create') {
9866 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
9867 }
9868 }
9869
9870 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('checkbox'))) {
9871 if ($action == 'create') {
9872 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : explode(',', $extrafields->attributes[$this->table_element]['default'][$key]);
9873 }
9874 }
9875
9876
9877 $labeltoshow = $langs->trans($label);
9878 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
9879 if ($display_type == 'card') {
9880 $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields'.($extrafields_collapse_num ? ' trextrafieldsgroup' : '').' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9881 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER') && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
9882 $out .= '<td></td>';
9883 }
9884 $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldmax45' : $params['tdclass']).' wordbreak';
9885 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'text') {
9886 $out .= ' tdtop';
9887 }
9888 } elseif ($display_type == 'line') {
9889 $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9890 $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
9891 }
9892 //$out .= "titlefield";
9893 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
9894 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
9895 $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
9896 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
9897 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9898 $out .= ' fieldrequired';
9899 }
9900 }
9901 $out .= '">';
9902 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
9903 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9904 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9905 } else {
9906 $out .= $labeltoshow;
9907 }
9908 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9909 $out .= '&nbsp;<span style="color: red">*</span>';
9910 }
9911 } else {
9912 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9913 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9914 } else {
9915 $out .= $labeltoshow;
9916 }
9917 }
9918
9919 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9920
9921 // Second column
9922 $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
9923 if ($display_type == 'card') {
9924 // 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
9925 $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key;
9926 $out .= '" '.($colspan ? ' colspan="'.$colspan.'"' : '');
9927 $out .= '>';
9928 } elseif ($display_type == 'line') {
9929 $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].'">';
9930 }
9931
9932 switch ($mode) {
9933 case "view":
9934 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
9935 break;
9936 case "create":
9937 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICTO', 'email,phone,ip,password'));
9938 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9939 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9940 }
9941 //$out .= '<!-- type = '.$extrafields->attributes[$this->table_element]['type'][$key].' -->';
9942 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', '', $this, $this->table_element);
9943 break;
9944 case "edit":
9945 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICTO', 'email,phone,ip,password'));
9946 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9947 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9948 }
9949 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', '', $this, $this->table_element);
9950 break;
9951 }
9952
9953 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9954 $out .= ($display_type == 'card' ? '</tr>'."\n" : '</div>');
9955 $e++;
9956 }
9957 }
9958 $out .= "\n";
9959 // Add code to manage list depending on others
9960 if (!empty($conf->use_javascript_ajax)) {
9961 $out .= $this->getJSListDependancies();
9962 }
9963
9964 $out .= '<!-- commonobject:showOptionals end --> '."\n";
9965
9966 if (empty($nbofextrafieldsshown)) {
9967 $out = '';
9968 }
9969 }
9970 }
9971
9972 $out .= $hookResPrint;
9973
9974 return $out;
9975 }
9976
9981 public function getJSListDependancies($type = '_extra')
9982 {
9983 $out = '
9984 <script nonce="'.getNonce().'">
9985 jQuery(document).ready(function() {
9986 function showOptions'.$type.'(child_list, parent_list, orig_select)
9987 {
9988 var val = $("select[name=\""+parent_list+"\"]").val();
9989 var parentVal = parent_list + ":" + val;
9990 if(typeof val == "string"){
9991 if(val != "") {
9992 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9993 $("select[name=\""+child_list+"\"] option[parent]").remove();
9994 $("select[name=\""+child_list+"\"]").append(options);
9995 } else {
9996 var options = orig_select.find("option[parent]").clone();
9997 $("select[name=\""+child_list+"\"] option[parent]").remove();
9998 $("select[name=\""+child_list+"\"]").append(options);
9999 }
10000 } else if(val > 0) {
10001 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10002 $("select[name=\""+child_list+"\"] option[parent]").remove();
10003 $("select[name=\""+child_list+"\"]").append(options);
10004 } else {
10005 var options = orig_select.find("option[parent]").clone();
10006 $("select[name=\""+child_list+"\"] option[parent]").remove();
10007 $("select[name=\""+child_list+"\"]").append(options);
10008 }
10009 }
10010 function setListDependencies'.$type.'() {
10011 jQuery("select option[parent]").parent().each(function() {
10012 var orig_select = {};
10013 var child_list = $(this).attr("name");
10014 orig_select[child_list] = $(this).clone();
10015 var parent = $(this).find("option[parent]:first").attr("parent");
10016 var infos = parent.split(":");
10017 var parent_list = infos[0];
10018
10019 //Hide daughters lists
10020 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10021 $("#"+child_list).hide();
10022 //Show mother lists
10023 } else if ($("#"+parent_list).val() != 0){
10024 $("#"+parent_list).show();
10025 }
10026 //Show the child list if the parent list value is selected
10027 $("select[name=\""+parent_list+"\"]").click(function() {
10028 if ($(this).val() != 0){
10029 $("#"+child_list).show()
10030 }
10031 });
10032
10033 //When we change parent list
10034 $("select[name=\""+parent_list+"\"]").change(function() {
10035 showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
10036 //Select the value 0 on child list after a change on the parent list
10037 $("#"+child_list).val(0).trigger("change");
10038 //Hide child lists if the parent value is set to 0
10039 if ($(this).val() == 0){
10040 $("#"+child_list).hide();
10041 }
10042 });
10043 });
10044 }
10045
10046 setListDependencies'.$type.'();
10047 });
10048 </script>'."\n";
10049 return $out;
10050 }
10051
10057 public function getRights()
10058 {
10059 global $user;
10060
10061 $module = empty($this->module) ? '' : $this->module;
10062 $element = $this->element;
10063
10064 if ($element == 'facturerec') {
10065 $element = 'facture';
10066 } elseif ($element == 'invoice_supplier_rec') {
10067 return !$user->hasRight('fournisseur', 'facture') ? null : $user->hasRight('fournisseur', 'facture');
10068 } elseif ($module && $user->hasRight($module, $element)) {
10069 // for modules built with ModuleBuilder
10070 return $user->hasRight($module, $element);
10071 }
10072
10073 return isset($user->rights->$element) ? $user->rights->$element : null;
10074 }
10075
10088 public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
10089 {
10090 global $hookmanager;
10091
10092 $parameters = array(
10093 'origin_id' => $origin_id,
10094 'dest_id' => $dest_id,
10095 'tables' => $tables,
10096 );
10097 $reshook = $hookmanager->executeHooks('commonReplaceThirdparty', $parameters);
10098 if ($reshook) {
10099 return true; // replacement code
10100 } elseif ($reshook < 0) {
10101 return $ignoreerrors === 1; // failure
10102 } // reshook = 0 => execute normal code
10103
10104 foreach ($tables as $table) {
10105 $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
10106
10107 if (!$dbs->query($sql)) {
10108 if ($ignoreerrors) {
10109 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.
10110 }
10111 //$this->errors = $db->lasterror();
10112 return false;
10113 }
10114 }
10115
10116 return true;
10117 }
10118
10131 public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
10132 {
10133 foreach ($tables as $table) {
10134 $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
10135
10136 if (!$dbs->query($sql)) {
10137 if ($ignoreerrors) {
10138 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.
10139 }
10140 //$this->errors = $db->lasterror();
10141 return false;
10142 }
10143 }
10144
10145 return true;
10146 }
10147
10161 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0, $qty = 0)
10162 {
10163 global $conf;
10164
10165 $buyPrice = 0;
10166
10167 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && getDolGlobalInt('ForceBuyingPriceIfNull') > 0)) {
10168 // When ForceBuyingPriceIfNull is set
10169 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
10170 } else {
10171 // Get cost price for margin calculation
10172 if (!empty($fk_product) && $fk_product > 0) {
10173 $result = 0;
10174 if (getDolGlobalString('MARGIN_TYPE') == 'costprice') {
10175 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
10176 $product = new Product($this->db);
10177 $result = $product->fetch($fk_product);
10178 if ($result <= 0) {
10179 $this->errors[] = 'ErrorProductIdDoesNotExists';
10180 return -1;
10181 }
10182 if ($product->cost_price > 0) {
10183 $buyPrice = $product->cost_price;
10184 } elseif ($product->pmp > 0) {
10185 $buyPrice = $product->pmp;
10186 }
10187 } elseif (getDolGlobalString('MARGIN_TYPE') == 'pmp') {
10188 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
10189 $product = new Product($this->db);
10190 $result = $product->fetch($fk_product);
10191 if ($result <= 0) {
10192 $this->errors[] = 'ErrorProductIdDoesNotExists';
10193 return -1;
10194 }
10195 if ($product->pmp > 0) {
10196 $buyPrice = $product->pmp;
10197 }
10198 }
10199
10200 if (empty($buyPrice) && in_array(getDolGlobalString('MARGIN_TYPE'), array('1', 'pmp', 'costprice'))) {
10201 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
10202 $productFournisseur = new ProductFournisseur($this->db);
10203 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product, $qty);
10204 if ($result == 0 && $qty > 0) {
10205 // No supplier price defined for such a low quantity, fall back on the lowest known price
10206 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product);
10207 }
10208 if ($result > 0) {
10209 $buyPrice = $productFournisseur->fourn_unitprice;
10210 } elseif ($result < 0) {
10211 $this->errors[] = $productFournisseur->error;
10212 return -2;
10213 }
10214 }
10215 }
10216 }
10217
10218 return (float) $buyPrice;
10219 }
10220
10228 public function getDataToShowPhoto($modulepart, $imagesize)
10229 {
10230 // See getDataToShowPhoto() implemented by Product for example.
10231 return array('dir' => '', 'file' => '', 'originalfile' => '', 'altfile' => '', 'email' => '', 'capture' => '');
10232 }
10233
10234
10235 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
10255 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')
10256 {
10257 // phpcs:enable
10258 global $user, $langs;
10259
10260 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
10261 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
10262 include_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
10263
10264 $sortfield = 'position_name';
10265 $sortorder = 'asc';
10266
10267 $dir = $sdir.'/';
10268 $pdir = '/';
10269
10270 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
10271 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
10272
10273 // For backward compatibility
10274 if ($modulepart == 'product') {
10275 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
10276 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
10277 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
10278 }
10279 }
10280 if ($modulepart == 'category') {
10281 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
10282 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
10283 }
10284
10285 // Defined relative dir to DOL_DATA_ROOT
10286 $relativedir = '';
10287 if ($dir) {
10288 $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
10289 $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
10290 $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
10291 }
10292
10293 $dirthumb = $dir.'thumbs/';
10294 $pdirthumb = $pdir.'thumbs/';
10295
10296 $return = '<!-- Photo -->'."\n";
10297 $nbphoto = 0;
10298
10299 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
10300
10301 /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatibility, we scan also old dirs
10302 {
10303 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
10304 $filearray=array_merge($filearray, $filearrayold);
10305 }*/
10306
10307 completeFileArrayWithDatabaseInfo($filearray, $relativedir, $this);
10308 '@phan-var-force array<array{name:string,path:string,level1name:string,relativename:string,fullname:string,date:string,size:int,perm:int,type:string,position_name:string,cover:string,keywords:string,acl:string,rowid:int,label:string,share:string}> $filearray';
10309
10310 $useLinkPathPhoto = false;
10311
10312 if (getDolGlobalInt('PRODUCT_USE_LINK_PATH_FOR_PHOTO')) {
10313 $link = new Link($this->db);
10314 $links = array();
10315 $link->fetchAll($links, 'product', $this->id);
10316
10317 if (count($links) > 0) {
10318 $useLinkPathPhoto = true;
10319 }
10320
10321 if ($useLinkPathPhoto) {
10322 // Start table or div based on nbbyrow
10323 if ($nbbyrow > 0) {
10324 $return .= '<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
10325 }
10326
10327 $i = 0;
10328 foreach ($links as $link) {
10329 if (!empty($link->url) && preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
10330 $url = dol_escape_htmltag($link->url);
10331 $i++;
10332 $nbphoto++;
10333
10334 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
10335 $return .= '<tr class="center valignmiddle">';
10336 }
10337
10338 if ($nbbyrow > 0) {
10339 $return .= '<td style="width:'.ceil(100 / $nbbyrow).'%" class="photo">';
10340 } else {
10341 $return .= '<div class="inline-block">';
10342 }
10343
10344 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'"'.($maxHeight ? ' height="'.$maxHeight.'"' : '').' src="'.$url.'" title="External image">';
10345
10346 if ($nbbyrow > 0) {
10347 $return .= '</td>';
10348 if ($i % $nbbyrow == 0) {
10349 $return .= '</tr>';
10350 }
10351 } else {
10352 $return .= '</div>';
10353 }
10354
10355 if ($nbmax && $nbphoto >= $nbmax) {
10356 break;
10357 }
10358 }
10359 }
10360
10361 if ($nbbyrow > 0) {
10362 while ($i % $nbbyrow) {
10363 $return .= '<td style="width:'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
10364 $i++;
10365 }
10366 if ($nbphoto) {
10367 $return .= '</table>';
10368 }
10369 }
10370 }
10371 }
10372
10373 if (count($filearray)) {
10374 if ($sortfield && $sortorder) {
10375 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
10376 }
10377
10378 foreach ($filearray as $key => $val) {
10379 $photo = '';
10380 $file = $val['name'];
10381
10382 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
10383 if (image_format_supported($file) >= 0) {
10384 $nbphoto++;
10385 $photo = $file;
10386 $viewfilename = $file;
10387
10388 if ($size == 1 || $size == 'small') { // Format vignette
10389 // Find name of thumb file
10390 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
10391 if (!dol_is_file($dirthumb.$photo_vignette)) {
10392 // The thumb does not exists, so we will use the original file
10393 $dirthumb = $dir;
10394 $pdirthumb = $pdir;
10395 $photo_vignette = basename($file);
10396 }
10397
10398 // Get filesize of original file
10399 $imgarray = dol_getImageSize($dir.$photo);
10400
10401 if ($nbbyrow > 0) {
10402 if ($nbphoto == 1) {
10403 $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
10404 }
10405
10406 if ($nbphoto % $nbbyrow == 1) {
10407 $return .= '<tr class="center valignmiddle" style="border: 1px">';
10408 }
10409 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
10410 } elseif ($nbbyrow < 0) {
10411 $return .= '<div class="inline-block">'."\n";
10412 }
10413
10414 $relativefile = preg_replace('/^\//', '', $pdir.$photo);
10415 if (empty($nolink)) {
10416 $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
10417 if ($urladvanced) {
10418 $return .= '<a href="'.$urladvanced.'">';
10419 } else {
10420 $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
10421 }
10422 }
10423
10424 // Show image (width height=$maxHeight)
10425 // If thumb file available and image source is too large, we use the thumb, otherwise we use the original photo
10426 $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
10427 $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
10428 if ($overwritetitle) {
10429 if (is_numeric($overwritetitle)) {
10430 $alt = '';
10431 } else {
10432 $alt = $overwritetitle;
10433 }
10434 }
10435 if (empty($cache) && !empty($val['label'])) {
10436 // label is md5 of file
10437 // use it in url to say we want to cache this version of the file
10438 $cache = $val['label'];
10439 }
10440 if ($usesharelink) {
10441 if (array_key_exists('share', $val) && $val['share']) {
10442 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
10443 $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
10444 $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).'">';
10445 } else {
10446 $return .= '<!-- Show original file -->';
10447 $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).'">';
10448 }
10449 } else {
10450 $return .= '<!-- Show nophoto file (because file is not shared) -->';
10451 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
10452 }
10453 } else {
10454 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
10455 $return .= '<!-- Show thumb -->';
10456 $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).'">';
10457 } else {
10458 $return .= '<!-- Show original file -->';
10459 $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).'">';
10460 }
10461 }
10462
10463 if (empty($nolink)) {
10464 $return .= '</a>';
10465 }
10466
10467 if ($showfilename) {
10468 $return .= '<br>'.$viewfilename;
10469 }
10470 if ($showaction) {
10471 $return .= '<br>';
10472 // If $photo_vignette set, we add a link to generate thumbs if file is an image and width or height higher than limits
10473 if ($photo_vignette && (image_format_supported($photo) > 0) && ((isset($imgarray['width']) && $imgarray['width'] > $maxWidth) || (isset($imgarray['width']) && $imgarray['width'] > $maxHeight))) {
10474 $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>';
10475 }
10476 // Special case for product
10477 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
10478 // Link to resize
10479 $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; ';
10480
10481 // Link to delete
10482 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
10483 $return .= img_delete().'</a>';
10484 }
10485 }
10486 $return .= "\n";
10487
10488 if ($nbbyrow > 0) {
10489 $return .= '</td>';
10490 if (($nbphoto % $nbbyrow) == 0) {
10491 $return .= '</tr>';
10492 }
10493 } elseif ($nbbyrow < 0) {
10494 $return .= '</div>'."\n";
10495 }
10496 }
10497
10498 if (empty($size)) { // Format origine
10499 $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
10500
10501 if ($showfilename) {
10502 $return .= '<br>'.$viewfilename;
10503 }
10504 if ($showaction) {
10505 // Special case for product
10506 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
10507 // Link to resize
10508 $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; ';
10509
10510 // Link to delete
10511 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
10512 $return .= img_delete().'</a>';
10513 }
10514 }
10515 }
10516
10517 // On continue ou on arrete de boucler ?
10518 if ($nbmax && $nbphoto >= $nbmax) {
10519 break;
10520 }
10521 }
10522 }
10523
10524 if ($size == 1 || $size == 'small') {
10525 if ($nbbyrow > 0) {
10526 // Ferme tableau
10527 while ($nbphoto % $nbbyrow) {
10528 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
10529 $nbphoto++;
10530 }
10531
10532 if ($nbphoto) {
10533 $return .= '</table>';
10534 }
10535 }
10536 }
10537 }
10538
10539 $this->nbphoto = $nbphoto;
10540
10541 return $return;
10542 }
10543
10544
10551 protected function isArray($info)
10552 {
10553 if (is_array($info)) {
10554 if (isset($info['type']) && $info['type'] == 'array') {
10555 return true;
10556 } else {
10557 return false;
10558 }
10559 }
10560 return false;
10561 }
10562
10569 public function isDate($info)
10570 {
10571 if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
10572 return true;
10573 }
10574 return false;
10575 }
10576
10583 public function isDuration($info)
10584 {
10585 if (is_array($info)) {
10586 if (isset($info['type']) && ($info['type'] == 'duration')) {
10587 return true;
10588 } else {
10589 return false;
10590 }
10591 } else {
10592 return false;
10593 }
10594 }
10595
10602 public function isInt($info)
10603 {
10604 if (is_array($info)) {
10605 if (isset($info['type']) && (preg_match('/^(?:tiny|small|medium|big)?int|int$/i', $info['type']))) {
10606 return true;
10607 } else {
10608 return false;
10609 }
10610 } else {
10611 return false;
10612 }
10613 }
10614
10621 public function isFloat($info)
10622 {
10623 if (is_array($info)) {
10624 if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
10625 return true;
10626 } else {
10627 return false;
10628 }
10629 }
10630 return false;
10631 }
10632
10639 public function isText($info)
10640 {
10641 if (is_array($info)) {
10642 if (isset($info['type']) && $info['type'] == 'text') {
10643 return true;
10644 } else {
10645 return false;
10646 }
10647 }
10648 return false;
10649 }
10650
10657 protected function canBeNull($info)
10658 {
10659 if (is_array($info)) {
10660 if (array_key_exists('notnull', $info) && $info['notnull'] != '1') {
10661 return true;
10662 } else {
10663 return false;
10664 }
10665 }
10666 return true;
10667 }
10668
10675 protected function isForcedToNullIfZero($info)
10676 {
10677 if (is_array($info)) {
10678 if (array_key_exists('notnull', $info) && $info['notnull'] == '-1') {
10679 return true;
10680 } else {
10681 return false;
10682 }
10683 }
10684 return false;
10685 }
10686
10693 protected function isIndex($info)
10694 {
10695 if (is_array($info)) {
10696 if (array_key_exists('index', $info) && $info['index'] == true) {
10697 return true;
10698 } else {
10699 return false;
10700 }
10701 }
10702 return false;
10703 }
10704
10705
10715 protected function setSaveQuery()
10716 {
10717 global $conf;
10718
10719 $queryarray = array();
10720 foreach ($this->fields as $field => $info) { // Loop on definition of fields
10721 // Depending on field type ('datetime', ...)
10722 if ($this->isDate($info)) {
10723 if (empty($this->{$field})) {
10724 $queryarray[$field] = null;
10725 } else {
10726 $queryarray[$field] = $this->db->idate($this->{$field});
10727 }
10728 } elseif ($this->isDuration($info)) {
10729 // $this->{$field} may be null, '', 0, '0', 123, '123'
10730 if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
10731 if (!isset($this->{$field})) {
10732 if (!empty($info['default'])) {
10733 $queryarray[$field] = $info['default']; // From safe source @phan-suppress-current-line SqlInjection
10734 } else {
10735 $queryarray[$field] = 0;
10736 }
10737 } else {
10738 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
10739 }
10740 } else {
10741 $queryarray[$field] = null;
10742 }
10743 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10744 if ($field == 'entity' && is_null($this->{$field})) {
10745 $queryarray[$field] = ((int) $conf->entity);
10746 } else {
10747 // $this->{$field} may be null, '', 0, '0', 123, '123'
10748 if ((isset($this->{$field}) && ((string) $this->{$field}) != '') || !empty($info['notnull'])) {
10749 if (!isset($this->{$field})) {
10750 $queryarray[$field] = 0;
10751 } elseif ($this->isInt($info)) {
10752 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
10753 } elseif ($this->isFloat($info)) {
10754 $queryarray[$field] = (float) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
10755 }
10756 } else {
10757 $queryarray[$field] = null;
10758 }
10759 }
10760 } else {
10761 // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
10762 // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
10763 $queryarray[$field] = $this->{$field}; // @phan-suppress-current-line SqlInjection
10764 }
10765
10766 if (is_array($info) && array_key_exists('type', $info) && !empty($info['type']) && $info['type'] == 'timestamp' && empty($queryarray[$field])) {
10767 unset($queryarray[$field]);
10768 }
10769 if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
10770 $queryarray[$field] = null; // May force 0 to null
10771 }
10772 }
10773
10774 return $queryarray;
10775 }
10776
10783 public function setVarsFromFetchObj(&$obj)
10784 {
10785 global $db;
10786
10787 foreach ($this->fields as $field => $info) {
10788 if ($this->isDate($info)) {
10789 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') {
10790 $this->$field = '';
10791 } else {
10792 $this->$field = $db->jdate($obj->$field);
10793 }
10794 } elseif ($this->isInt($info)) {
10795 if ($field == 'rowid') {
10796 $this->id = (int) $obj->$field;
10797 } else {
10798 if ($this->isForcedToNullIfZero($info)) {
10799 if (empty($obj->$field)) {
10800 $this->$field = null;
10801 } else {
10802 $this->$field = (int) $obj->$field;
10803 }
10804 } else {
10805 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
10806 $this->$field = (int) $obj->$field;
10807 } else {
10808 $this->$field = null;
10809 }
10810 }
10811 }
10812 } elseif ($this->isFloat($info)) {
10813 if ($this->isForcedToNullIfZero($info)) {
10814 if (empty($obj->$field)) {
10815 $this->$field = null;
10816 } else {
10817 $this->$field = (float) $obj->$field;
10818 }
10819 } else {
10820 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
10821 $this->$field = (float) $obj->$field;
10822 } else {
10823 $this->$field = null;
10824 }
10825 }
10826 } else {
10827 $this->$field = isset($obj->$field) ? $obj->$field : null;
10828 }
10829 }
10830
10831 // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
10832 if (!isset($this->fields['ref']) && isset($this->id)) {
10833 $this->ref = (string) $this->id;
10834 }
10835 }
10836
10841 public function emtpyObjectVars()
10842 {
10843 foreach ($this->fields as $field => $arr) {
10844 $this->$field = null;
10845 }
10846 }
10847
10855 public function getFieldList($alias = '', $excludefields = array())
10856 {
10857 $keys = array_keys($this->fields);
10858 if (!empty($alias)) {
10859 $keys_with_alias = array();
10860 foreach ($keys as $fieldname) {
10861 if (!empty($excludefields)) {
10862 if (in_array($fieldname, $excludefields)) { // The field is excluded and must not be in output
10863 continue;
10864 }
10865 }
10866 $keys_with_alias[] = $this->db->sanitize($alias . '.' . $fieldname);
10867 }
10868 return implode(', ', $keys_with_alias);
10869 } else {
10870 return implode(', ', $keys);
10871 }
10872 }
10873
10881 protected function quote($value, $fieldsentry)
10882 {
10883 if (is_null($value)) {
10884 return 'NULL';
10885 } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
10886 return price2num((string) $value);
10887 } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
10888 return (int) $value;
10889 } elseif ($fieldsentry['type'] == 'boolean') {
10890 if ($value) {
10891 return 'true';
10892 } else {
10893 return 'false';
10894 }
10895 } else {
10896 return "'".$this->db->escape($value)."'";
10897 }
10898 }
10899
10900
10908 public function createCommon(User $user, $notrigger = 0)
10909 {
10910 global $conf;
10911 //global $langs; // Should be able to work with $langs loaded
10912
10913 dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
10914
10915 $error = 0;
10916
10917 $now = dol_now();
10918
10919 $fieldvalues = $this->setSaveQuery();
10920
10921 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
10922
10923 if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
10924 $fieldvalues['date_creation'] = $this->db->idate($now);
10925 $this->date_creation = $now;
10926 }
10927 // For backward compatibility, if a property ->fk_user_creat exists and not filled.
10928 if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
10929 $fieldvalues['fk_user_creat'] = $user->id;
10930 $this->fk_user_creat = $user->id;
10931 }
10932 if (array_key_exists('user_creation_id', $fieldvalues) && !($fieldvalues['user_creation_id'] > 0)) {
10933 $fieldvalues['user_creation_id'] = $user->id;
10934 $this->user_creation_id = $user->id;
10935 }
10936 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass')) {
10937 // @phan-suppress-next-line PhanUndeclaredProperty
10938 $tmparray = dol_hash($this->pass, '0', 0, 1);
10939 $fieldvalues['pass_crypted'] = $tmparray['pass_encrypted'];
10940 if (array_key_exists('pass_encoding', $fieldvalues) && property_exists($this, 'pass_encoding')) {
10941 $fieldvalues['pass_encoding'] = $tmparray['pass_encoding'];
10942 }
10943 }
10944 if (array_key_exists('ref', $fieldvalues)) {
10945 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
10946 }
10947 if (getDolGlobalString('MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists('tms', $fieldvalues)) { // If we want the explicit update of tms fields instead of the deprecated update by database
10948 $fieldvalues['tms'] = $this->db->idate($now);
10949 }
10950
10951 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
10952
10953 $sanitized_keys = array();
10954 $sanitized_values = array(); // Array to store string forged for SQL syntax
10955 foreach ($fieldvalues as $k => $v) {
10956 $sanitized_keys[$k] = $k; // Safe source @phan-suppress-current-line SqlInjection
10957 $value = $this->fields[$k];
10958 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10959 $sanitized_values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
10960 }
10961
10962 // Clean and check mandatory
10963 foreach ($sanitized_keys as $key) {
10964 if (!isset($this->fields[$key])) {
10965 continue;
10966 }
10967 $key_fields = $this->fields[$key];
10968
10969 // If field is an implicit foreign key field (so type = 'integer:...')
10970 if (preg_match('/^integer:/i', $key_fields['type']) && $sanitized_values[$key] == '-1') {
10971 $sanitized_values[$key] = '';
10972 }
10973 if (!empty($key_fields['foreignkey']) && $sanitized_values[$key] == '-1') {
10974 $sanitized_values[$key] = '';
10975 }
10976
10977 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($sanitized_values[$key]) || $sanitized_values[$key] === 'NULL') && (!isset($key_fields['default']) || is_null($key_fields['default']))) {
10978 $error++;
10979 global $langs;
10980 if (empty($langs)) {
10981 require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
10982 $langs = new Translate('', $conf);
10983 $langs->setDefaultLang();
10984 $langs->load("errors");
10985 }
10986 dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
10987 $this->errors[] = $langs->trans("ErrorFieldRequired", isset($key_fields['label']) ? $key_fields['label'] : $key);
10988 }
10989
10990 // If value is null and there is a default value for field @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10991 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($sanitized_values[$key]) || $sanitized_values[$key] === 'NULL') && array_key_exists('default', $key_fields) && !is_null($key_fields['default'])) {
10992 $sanitized_values[$key] = $this->quote($key_fields['default'], $key_fields);
10993 }
10994
10995 // If field is an implicit foreign key field (so type = 'integer:...')
10996 if (isset($key_fields['type']) && preg_match('/^integer:/i', $key_fields['type']) && empty($sanitized_values[$key])) {
10997 if (isset($key_fields['default'])) {
10998 $sanitized_values[$key] = ((int) $key_fields['default']);
10999 } else {
11000 $sanitized_values[$key] = 'null';
11001 }
11002 }
11003 if (!empty($key_fields['foreignkey']) && empty($sanitized_values[$key])) {
11004 $sanitized_values[$key] = 'null';
11005 }
11006 }
11007
11008 if ($error) {
11009 return -1;
11010 }
11011
11012 $this->db->begin();
11013
11014 if (!$error) {
11015 $sql = "INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
11016 $sql .= " (".implode(", ", $sanitized_keys).')';
11017 $sql .= " VALUES (".implode(", ", $sanitized_values).")"; // $sanitized_values can contains 'abc' or 123
11018
11019 $res = $this->db->query($sql);
11020 if (!$res) {
11021 $error++;
11022 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
11023 $this->errors[] = "ErrorRefAlreadyExists";
11024 } else {
11025 $this->errors[] = $this->db->lasterror();
11026 }
11027 }
11028 }
11029
11030 if (!$error) {
11031 $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
11032 }
11033
11034 // If we have a field ref with a default value of (PROV)
11035 if (!$error) {
11036 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
11037 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)') {
11038 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11039 $sql .= " SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
11040 $resqlupdate = $this->db->query($sql);
11041
11042 if ($resqlupdate === false) {
11043 $error++;
11044 $this->errors[] = $this->db->lasterror();
11045 } else {
11046 $this->ref = '(PROV'.$this->id.')';
11047 }
11048 }
11049 }
11050
11051 // Create extrafields
11052 if (!$error) {
11053 $result = $this->insertExtraFields();
11054 if ($result < 0) {
11055 $error++;
11056 }
11057 }
11058
11059 // Create lines
11060 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
11061 foreach ($this->lines as $line) {
11062 $keyforparent = $this->fk_element;
11063 $line->$keyforparent = $this->id;
11064
11065 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
11066 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
11067 if (!is_object($line)) {
11068 $line = (object) $line;
11069 }
11070
11071 $result = 0;
11072 if (method_exists($line, 'insert')) {
11073 $result = $line->insert($user, 1);
11074 } elseif (method_exists($line, 'create')) {
11075 $result = $line->create($user, 1);
11076 }
11077 if ($result < 0) {
11078 $this->error = $line->error;
11079 $this->db->rollback();
11080 return -1;
11081 }
11082 }
11083 }
11084
11085 // Triggers
11086 if (!$error && !$notrigger) {
11087 // Call triggers
11088 $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
11089 if ($result < 0) {
11090 $error++;
11091 }
11092 // End call triggers
11093 }
11094
11095 // Commit or rollback
11096 if ($error) {
11097 $this->db->rollback();
11098 return -1;
11099 } else {
11100 $this->db->commit();
11101 return $this->id;
11102 }
11103 }
11104
11105
11115 public function fetchCommon($id, $ref = null, $morewhere = '', $noextrafields = 0)
11116 {
11117 if (empty($id) && empty($ref) && empty($morewhere)) {
11118 return -1;
11119 }
11120
11121 $fieldlist = $this->getFieldList('t');
11122 if (empty($fieldlist)) {
11123 return 0;
11124 }
11125
11126 $sql = "SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
11127 $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
11128
11129 if (!empty($id)) {
11130 $sql .= ' WHERE t.rowid = '.((int) $id);
11131 } elseif (!empty($ref)) {
11132 $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
11133 } else {
11134 $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
11135 }
11136 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
11137 $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
11138 }
11139 if ($morewhere) {
11140 $sql .= $morewhere;
11141 }
11142 $sql .= ' LIMIT 1'; // This is a fetch, to be certain to get only one record
11143
11144 $res = $this->db->query($sql);
11145 if ($res) {
11146 $obj = $this->db->fetch_object($res);
11147 if ($obj) {
11148 $this->setVarsFromFetchObj($obj);
11149
11150 // Retrieve all extrafield
11151 // fetch optionals attributes and labels
11152 if (empty($noextrafields)) {
11153 $result = $this->fetch_optionals();
11154 if ($result < 0) {
11155 $this->error = $this->db->lasterror();
11156 $this->errors[] = $this->error;
11157 return -4;
11158 }
11159 }
11160
11161 return $this->id;
11162 } else {
11163 return 0;
11164 }
11165 } else {
11166 $this->error = $this->db->lasterror();
11167 $this->errors[] = $this->error;
11168 return -1;
11169 }
11170 }
11171
11179 public function fetchLinesCommon($morewhere = '', $noextrafields = 0)
11180 {
11181 $objectlineclassname = get_class($this).'Line';
11182 if (!class_exists($objectlineclassname)) {
11183 $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
11184 return -1;
11185 }
11186
11187 $objectline = new $objectlineclassname($this->db);
11188 '@phan-var-force CommonObjectLine $objectline';
11189
11190 $sql = "SELECT ".$objectline->getFieldList('l');
11191 $sql .= " FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element)." as l";
11192 $sql .= " WHERE l.fk_".$this->db->sanitize($this->element)." = ".((int) $this->id);
11193 if ($morewhere) {
11194 $sql .= $morewhere;
11195 }
11196 if (isset($objectline->fields['position'])) {
11197 $sql .= $this->db->order('position', 'ASC');
11198 }
11199
11200 $resql = $this->db->query($sql);
11201 if ($resql) {
11202 $num_rows = $this->db->num_rows($resql);
11203 $i = 0;
11204 $this->lines = array();
11205 while ($i < $num_rows) {
11206 $obj = $this->db->fetch_object($resql);
11207 if ($obj) {
11208 $newline = new $objectlineclassname($this->db);
11209 '@phan-var-force CommonObjectLine $newline';
11210 $newline->setVarsFromFetchObj($obj);
11211
11212 // Load also extrafields for the line
11213 if (empty($noextrafields)) {
11214 $newline->fetch_optionals();
11215 }
11216
11217 $this->lines[] = $newline;
11218 }
11219 $i++;
11220 }
11221
11222 return 1;
11223 } else {
11224 $this->error = $this->db->lasterror();
11225 $this->errors[] = $this->error;
11226 return -1;
11227 }
11228 }
11229
11237 public function updateCommon(User $user, $notrigger = 0)
11238 {
11239 dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
11240
11241 $error = 0;
11242
11243 $now = dol_now();
11244
11245 // $this->oldcopy should have been set by the caller of update
11246 //if (empty($this->oldcopy)) {
11247 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
11248 // $this->oldcopy = dol_clone($this, 2);
11249 //}
11250
11251 $fieldvalues = $this->setSaveQuery();
11252
11253 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
11254
11255 if (array_key_exists('date_modification', $fieldvalues)) {
11256 $fieldvalues['date_modification'] = $this->db->idate($now);
11257 }
11258 if (getDolGlobalString('MAIN_DISABLE_AUTO_UPDATE_OF_TMS_FIELDS') && array_key_exists('tms', $fieldvalues)) { // If we want the explicit update of tms fields instead of deprecated update by database
11259 $fieldvalues['tms'] = $this->db->idate($now);
11260 }
11261 if (array_key_exists('fk_user_modif', $fieldvalues)) {
11262 $fieldvalues['fk_user_modif'] = $user->id;
11263 }
11264 if (array_key_exists('user_modification_id', $fieldvalues)) {
11265 $fieldvalues['user_modification_id'] = $user->id;
11266 }
11267 // @phan-suppress-next-line PhanUndeclaredProperty
11268 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass') && !empty($this->pass)) {
11269 // @phan-suppress-next-line PhanUndeclaredProperty
11270 $tmparray = dol_hash($this->pass, '0', 0, 1);
11271 $fieldvalues['pass_crypted'] = $tmparray['pass_encrypted'];
11272 if (array_key_exists('pass_encoding', $fieldvalues) && property_exists($this, 'pass_encoding')) {
11273 $fieldvalues['pass_encoding'] = $tmparray['pass_encoding'];
11274 }
11275 }
11276 if (array_key_exists('ref', $fieldvalues)) {
11277 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
11278 }
11279
11280 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
11281
11282 // Add quotes and escape on fields with type string
11283 $keys = array();
11284 $values = array();
11285 $sanitized_tmp = array();
11286 foreach ($fieldvalues as $k => $v) {
11287 $keys[$k] = $k;
11288 $value = $this->fields[$k];
11289 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
11290 $values[$k] = $this->quote($v, $value);
11291 if ((!empty($value["type"]) && $value["type"] == "text") && !empty($value['arrayofkeyval']) && is_array($value['arrayofkeyval'])) {
11292 // Clean values for text with selectbox
11293 $v = preg_replace('/\s/', ',', $v);
11294 $v = preg_replace('/,+/', ',', $v);
11295 }
11296 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition, SqlInjection
11297 $sanitized_tmp[] = $this->db->sanitize($k).'='.$this->quote($v, $this->fields[$k]);
11298 }
11299
11300 // Clean and check mandatory fields
11301 foreach ($keys as $key) {
11302 if (!empty($this->fields[$key]['type']) && preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
11303 $values[$key] = ''; // This is an implicit foreign key field
11304 }
11305 if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
11306 $values[$key] = ''; // This is an explicit foreign key field
11307 }
11308
11309 //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
11310 /*
11311 if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
11312 {
11313 $error++;
11314 $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
11315 }*/
11316 }
11317
11318 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11319 $sql.= " SET ".implode(', ', $sanitized_tmp);
11320 $sql.= " WHERE rowid = ".((int) $this->id);
11321
11322 $this->db->begin();
11323
11324 if (!$error) {
11325 $res = $this->db->query($sql);
11326 if (!$res) {
11327 $error++;
11328 $this->errors[] = $this->db->lasterror();
11329 }
11330 }
11331
11332 // Update extrafield
11333 if (!$error) {
11334 $result = $this->insertExtraFields(); // This update extrafields
11335 if ($result < 0) {
11336 $error++;
11337 }
11338 }
11339
11340 // Triggers
11341 if (!$error && !$notrigger) {
11342 // Call triggers
11343 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
11344 if ($result < 0) {
11345 $error++;
11346 } //Do also here what you must do to rollback action if trigger fail
11347 // End call triggers
11348 }
11349
11350 // Commit or rollback
11351 if ($error) {
11352 $this->db->rollback();
11353 return -1;
11354 } else {
11355 $this->db->commit();
11356 return $this->id;
11357 }
11358 }
11359
11368 public function deleteCommon(User $user, $notrigger = 0, $forcechilddeletion = 0)
11369 {
11370 dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
11371
11372 $error = 0;
11373
11374 $this->db->begin();
11375
11376 if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
11377 foreach ($this->childtables as $table) {
11378 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
11379 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
11380 $resql = $this->db->query($sql);
11381 if (!$resql) {
11382 $this->error = $this->db->lasterror();
11383 $this->errors[] = $this->error;
11384 $this->db->rollback();
11385 return -1;
11386 }
11387 }
11388 } elseif (!empty($this->childtables)) { // If object has children linked with a foreign key field, we check all child tables.
11389 $objectisused = $this->isObjectUsed($this->id);
11390 if (!empty($objectisused)) {
11391 dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
11392 $this->error = 'ErrorRecordHasChildren';
11393 $this->errors[] = $this->error;
11394 $this->db->rollback();
11395 return 0;
11396 }
11397 }
11398
11399 // Delete cascade first
11400 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
11401 foreach ($this->childtablesoncascade as $tabletodelete) {
11402 $deleteFromObject = explode(':', $tabletodelete, 4);
11403 if (count($deleteFromObject) >= 2) {
11404 $className = str_replace('@', '', $deleteFromObject[0]);
11405 $filePath = $deleteFromObject[1];
11406 $columnName = $deleteFromObject[2];
11407 $filter = '';
11408 if (!empty($deleteFromObject[3])) {
11409 $filter = $deleteFromObject[3];
11410 }
11411
11412 if (dol_include_once($filePath)) {
11413 $childObject = new $className($this->db);
11414 if (method_exists($childObject, 'deleteByParentField')) {
11415 '@phan-var-force CommonObject $childObject';
11416 $result = $childObject->deleteByParentField($this->id, $columnName, $filter);
11417 if ($result < 0) {
11418 $error++;
11419 $this->errors[] = $childObject->error;
11420 break;
11421 }
11422 } else {
11423 $error++;
11424 $this->errors[] = "You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
11425 break;
11426 }
11427 } else {
11428 $error++;
11429 $this->errors[] = 'Cannot include child class file '.$filePath;
11430 break;
11431 }
11432 } else {
11433 // Delete record in child table
11434 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete)." WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
11435
11436 $resql = $this->db->query($sql);
11437 if (!$resql) {
11438 $error++;
11439 $this->error = $this->db->lasterror();
11440 $this->errors[] = $this->error;
11441 break;
11442 }
11443 }
11444 }
11445 }
11446
11447 if (!$error) {
11448 if (!$notrigger) {
11449 // Call triggers
11450 $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
11451 if ($result < 0) {
11452 $error++;
11453 } // Do also here what you must do to rollback action if trigger fail
11454 // End call triggers
11455 }
11456 }
11457
11458 // Delete llx_ecm_files
11459 if (!$error) {
11460 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
11461 if (!$res) {
11462 $error++;
11463 }
11464 }
11465
11466 if (!$error) {
11467 $dir = getMultidirOutput($this)."/".dol_sanitizeFileName($this->ref);
11468 // For remove dir
11469 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
11470 if (dol_is_dir($dir)) {
11471 if (!dol_delete_dir_recursive($dir)) {
11472 $this->errors[] = 'ErrorFailToDeleteDir';
11473 }
11474 }
11475 }
11476
11477 // Delete linked object
11478 $res = $this->deleteObjectLinked();
11479 if ($res < 0) {
11480 $error++;
11481 }
11482
11483 if (!$error && !empty($this->isextrafieldmanaged)) {
11484 $result = $this->deleteExtraFields();
11485 if ($result < 0) {
11486 $error++;
11487 }
11488 }
11489
11490 if (!$error) {
11491 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11492 $sql .= " WHERE rowid = ".((int) $this->id);
11493
11494 $resql = $this->db->query($sql);
11495 if (!$resql) {
11496 $error++;
11497 $this->errors[] = $this->db->lasterror();
11498 }
11499 }
11500
11501 // Commit or rollback
11502 if ($error) {
11503 $this->db->rollback();
11504 return -1;
11505 } else {
11506 $this->db->commit();
11507 return 1;
11508 }
11509 }
11510
11522 public function deleteByParentField($parentId = 0, $parentField = '', $filter = '', $filtermode = "AND")
11523 {
11524 global $user;
11525
11526 $error = 0;
11527 $deleted = 0;
11528
11529 //dol_syslog("deleteByParentField for ".$parentId.' '.$parentField);
11530
11531 if (!empty($parentId) && !empty($parentField)) {
11532 if (empty($this->table_element)) {
11533 $this->error = 'Property table_element for object is not defined';
11534 $this->errors[] = $this->error;
11535 $error++;
11536 return -1;
11537 }
11538 if (!method_exists($this, 'fetch')) {
11539 $this->error = 'Method fetch for object is not defined';
11540 $this->errors[] = $this->error;
11541 $error++;
11542 return -1;
11543 }
11544 if (!method_exists($this, 'delete')) {
11545 $this->error = 'Method delete for object is not defined';
11546 $this->errors[] = $this->error;
11547 $error++;
11548 return -1;
11549 }
11550
11551 $this->db->begin();
11552
11553 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
11554 $sql .= " WHERE ".$this->db->sanitize($parentField)." = ".(int) $parentId;
11555
11556 // Manage filter
11557 $errormessage = '';
11558 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
11559 if ($errormessage) {
11560 $this->errors[] = $errormessage;
11561 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
11562 return -1;
11563 }
11564
11565 $resql = $this->db->query($sql);
11566 if (!$resql) {
11567 $this->errors[] = $this->db->lasterror();
11568 $error++;
11569 } else {
11570 while ($obj = $this->db->fetch_object($resql)) {
11571 $result = $this->fetch($obj->rowid); // @phpstan-ignore-line
11572 if ($result < 0) {
11573 $error++;
11574 $this->errors[] = $this->error;
11575 } else {
11576 $result = $this->delete($user); // @phpstan-ignore-line
11577 if ($result < 0) {
11578 $error++;
11579 $this->errors[] = $this->error;
11580 } else {
11581 $deleted++;
11582 }
11583 }
11584 }
11585 }
11586
11587 if (empty($error)) {
11588 $this->db->commit();
11589 return $deleted;
11590 } else {
11591 $this->error = implode(', ', $this->errors);
11592 $this->db->rollback();
11593 return $error * -1;
11594 }
11595 }
11596
11597 return $deleted;
11598 }
11599
11607 public function isLineOfObject($lineid)
11608 {
11609 if (!($this->id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
11610 return true;
11611 }
11612
11613 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11614 $sql .= " WHERE rowid = ".((int) $lineid)." AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
11615 $resql = $this->db->query($sql);
11616
11617 return ($resql && $this->db->num_rows($resql) > 0);
11618 }
11619
11628 public function deleteLineCommon(User $user, $idline, $notrigger = 0)
11629 {
11630 $error = 0;
11631
11632 $tmpforobjectclass = get_class($this);
11633 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
11634
11635 if ($this->id > 0 && !empty($this->fk_element)) {
11636 // The line must belong to this object
11637 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
11638 $sql .= " WHERE rowid = ".((int) $idline)." AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
11639 $resql = $this->db->query($sql);
11640 if (!$resql || !$this->db->num_rows($resql)) {
11641 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
11642 return -1;
11643 }
11644 }
11645
11646 $this->db->begin();
11647
11648 // Call trigger
11649 $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
11650 if ($result < 0) {
11651 $error++;
11652 }
11653 // End call triggers
11654
11655 if (empty($error)) {
11656 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
11657 $sql .= " WHERE rowid = ".((int) $idline);
11658
11659 $resql = $this->db->query($sql);
11660 if (!$resql) {
11661 $this->error = "Error ".$this->db->lasterror();
11662 $error++;
11663 }
11664 }
11665
11666 if (empty($error)) {
11667 // Remove extrafields
11668 $tmpobjectline = new $tmpforobjectlineclass($this->db);
11669 '@phan-var-force CommonObjectLine $tmpobjectline';
11670 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
11671 $tmpobjectline->id = $idline;
11672 $result = $tmpobjectline->deleteExtraFields();
11673 if ($result < 0) {
11674 $error++;
11675 $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
11676 }
11677 }
11678 }
11679
11680 if (empty($error)) {
11681 $this->db->commit();
11682 return 1;
11683 } else {
11684 dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
11685 $this->db->rollback();
11686 return -1;
11687 }
11688 }
11689
11690
11701 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
11702 {
11703 $error = 0;
11704
11705 $this->db->begin();
11706
11707 $statusfield = 'status';
11708 if (in_array($this->element, array('don', 'donation', 'shipping', 'project_task'))) {
11709 $statusfield = 'fk_statut';
11710 }
11711
11712 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
11713 $sql .= " SET ".$this->db->sanitize($statusfield)." = ".((int) $status);
11714 $sql .= " WHERE rowid = ".((int) $this->id);
11715
11716 if ($this->db->query($sql)) {
11717 if (!$error) {
11718 $this->oldcopy = clone $this;
11719 }
11720
11721 if (!$error && !$notrigger) {
11722 // Call trigger
11723 $result = $this->call_trigger($triggercode, $user);
11724 if ($result < 0) {
11725 $error++;
11726 }
11727 }
11728
11729 if (!$error) {
11730 $this->status = $status;
11731 if (property_exists($this, 'statut')) { // For backward compatibility
11732 $this->statut = $status;
11733 }
11734 $this->db->commit();
11735 return 1;
11736 } else {
11737 $this->db->rollback();
11738 return -1;
11739 }
11740 } else {
11741 $this->error = $this->db->error();
11742 $this->db->rollback();
11743 return -1;
11744 }
11745 }
11746
11753 public function initAsSpecimenCommon()
11754 {
11755 global $user;
11756
11757 $this->id = 0;
11758 $this->specimen = 1;
11759 $fields = array(
11760 'label' => 'This is label',
11761 'ref' => 'ABCD1234',
11762 'description' => 'This is a description',
11763 'qty' => 123.12,
11764 'note_public' => 'Public note',
11765 'note_private' => 'Private note',
11766 'date_creation' => (dol_now() - 3600 * 48),
11767 'date_modification' => (dol_now() - 3600 * 24),
11768 'fk_user_creat' => $user->id,
11769 'fk_user_modif' => $user->id,
11770 'date' => dol_now(),
11771 );
11772 foreach ($fields as $key => $value) {
11773 if (array_key_exists($key, $this->fields)) {
11774 $this->{$key} = $value; // @phpstan-ignore-line
11775 }
11776 }
11777
11778 // Force values to default values when known
11779 if (property_exists($this, 'fields')) {
11780 foreach ($this->fields as $key => $value) {
11781 // If fields are already set, do nothing
11782 if (array_key_exists($key, $fields)) {
11783 continue;
11784 }
11785
11786 if (!empty($value['default'])) {
11787 $this->$key = $value['default'];
11788 }
11789 }
11790 }
11791
11792 return 1;
11793 }
11794
11795
11796 /* Part for comments */
11797
11803 public function fetchComments()
11804 {
11805 require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
11806
11807 $comment = new Comment($this->db);
11808 $result = $comment->fetchAllFor($this->element, $this->id);
11809 if ($result < 0) {
11810 $this->setErrorsFromObject($comment);
11811 return -1;
11812 } else {
11813 $this->comments = $comment->comments;
11814 }
11815 return count($this->comments);
11816 }
11817
11823 public function getNbComments()
11824 {
11825 return count($this->comments);
11826 }
11827
11834 public function trimParameters($parameters)
11835 {
11836 if (!is_array($parameters)) {
11837 return;
11838 }
11839 foreach ($parameters as $parameter) {
11840 if (isset($this->$parameter)) {
11841 $this->$parameter = trim($this->$parameter);
11842 }
11843 }
11844 }
11845
11846 /* Part for categories/tags */
11847
11858 public function getCategoriesCommon($type_categ)
11859 {
11860 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11861
11862 // Get current categories
11863 $c = new Categorie($this->db);
11864 $existing = $c->containing($this->id, $type_categ, 'id');
11865
11866 return $existing;
11867 }
11868
11881 public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
11882 {
11883 // Handle single category
11884 if (!is_array($categories)) {
11885 $categories = array($categories);
11886 }
11887
11888 dol_syslog(get_class($this)."::setCategoriesCommon Object Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
11889
11890 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11891
11892 if (empty($type_categ)) {
11893 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
11894 return -1;
11895 }
11896
11897 // Get current categories
11898 $c = new Categorie($this->db);
11899 $existing = $c->containing($this->id, $type_categ, 'id');
11900 // containing() returns an integer < 0 on error (e.g. when the categorie_xxx table does not exist).
11901 // Normalize to an empty array to avoid array_diff()/foreach() warnings below.
11902 if (!is_array($existing)) {
11903 $existing = array();
11904 }
11905 if ($remove_existing) {
11906 // Diff
11907 $to_del = array_diff($existing, $categories);
11908 $to_add = array_diff($categories, $existing);
11909 } else {
11910 $to_del = array(); // Nothing to delete
11911 $to_add = array_diff($categories, $existing);
11912 }
11913
11914 $error = 0;
11915 $ok = 0;
11916
11917 // Process
11918 foreach ($to_del as $del) {
11919 if ($c->fetch($del) > 0) {
11920 $result = $c->del_type($this, $type_categ);
11921 if ($result < 0) {
11922 $error++;
11923 $this->error = $c->error;
11924 $this->errors = $c->errors;
11925 break;
11926 } else {
11927 $ok += $result;
11928 }
11929 }
11930 }
11931 foreach ($to_add as $add) {
11932 if ($c->fetch($add) > 0) {
11933 $result = $c->add_type($this, $type_categ);
11934 if ($result < 0) {
11935 $error++;
11936 $this->error = $c->error;
11937 $this->errors = $c->errors;
11938 break;
11939 } else {
11940 $ok += $result;
11941 }
11942 }
11943 }
11944
11945 return $error ? (-1 * $error) : $ok;
11946 }
11947
11956 public function cloneCategories($fromId, $toId, $type = '')
11957 {
11958 $this->db->begin();
11959
11960 if (empty($type)) {
11961 $type = $this->table_element;
11962 }
11963
11964 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11965 $categorystatic = new Categorie($this->db);
11966
11967 $tablename = $this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11968 $fkname = 'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
11969
11970 $sql = "INSERT INTO ".$this->db->sanitize($tablename)." (fk_categorie, ".$this->db->sanitize($fkname).")";
11971 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->sanitize($tablename);
11972 $sql .= " WHERE ".$this->db->sanitize($fkname)." = ".((int) $fromId);
11973
11974 if (!$this->db->query($sql)) {
11975 $this->error = $this->db->lasterror();
11976 $this->db->rollback();
11977 return -1;
11978 }
11979
11980 $this->db->commit();
11981 return 1;
11982 }
11983
11990 public function deleteEcmFiles($mode = 0)
11991 {
11992 global $conf;
11993
11994 $this->db->begin();
11995
11996 // Delete in database with mode 0
11997 if ($mode == 0) {
11998 switch ($this->element) {
11999 case 'propal':
12000 $element = 'propale';
12001 break;
12002 case 'product':
12003 $element = 'produit';
12004 break;
12005 case 'order_supplier':
12006 $element = 'fournisseur/commande';
12007 break;
12008 case 'invoice_supplier':
12009 // Special cases that need to use get_exdir to get real dir of object
12010 // In future, all object should use this to define path of documents.
12011 $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
12012 break;
12013 case 'shipping':
12014 $element = 'expedition/sending';
12015 break;
12016 case 'task':
12017 case 'project_task':
12018 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
12019
12020 $project_result = $this->fetchProject();
12021 if ($project_result >= 0) {
12022 $element = 'projet/'.dol_sanitizeFileName($this->project->ref).'/';
12023 }
12024 // no break
12025 case 'contrat':
12026 $element = 'contract';
12027 break;
12028 default:
12029 $element = $this->element;
12030 }
12031 '@phan-var-force string $element';
12032
12033 // Delete ecm_files_extrafields with mode 0 (using name)
12034 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
12035 $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
12036 $sql .= " AND filepath = '".$this->db->escape($element."/".$this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
12037 $sql .= ")";
12038
12039 if (!$this->db->query($sql)) {
12040 $this->error = $this->db->lasterror();
12041 $this->db->rollback();
12042 return false;
12043 }
12044
12045 // Delete ecm_files with mode 0 (using name)
12046 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
12047 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
12048 $sql .= " AND filepath = '".$this->db->escape($element."/".$this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
12049
12050 if (!$this->db->query($sql)) {
12051 $this->error = $this->db->lasterror();
12052 $this->db->rollback();
12053 return false;
12054 }
12055 }
12056
12057 // Delete in database with mode 1
12058 if ($mode == 1) {
12059 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
12060 $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).")";
12061 $resql = $this->db->query($sql);
12062 if (!$resql) {
12063 $this->error = $this->db->lasterror();
12064 $this->db->rollback();
12065 return false;
12066 }
12067
12068 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
12069 $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
12070 $resql = $this->db->query($sql);
12071 if (!$resql) {
12072 $this->error = $this->db->lasterror();
12073 $this->db->rollback();
12074 return false;
12075 }
12076 }
12077
12078 $this->db->commit();
12079 return true;
12080 }
12081
12090 public function checkActiveProductInLines($status = 'onsale')
12091 {
12092 global $langs;
12093
12094 if (isModEnabled('product') || isModEnabled('service')) {
12095 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
12096
12097 $ret = true;
12098 $tmpproduct = new Product($this->db);
12099 foreach ($this->lines as $line) {
12100 if ($line->fk_product > 0) {
12101 $tmpproduct->fetch($line->fk_product);
12102 $statustotest = ($status == 'onsale' ? 'status' : 'status_buy');
12103 if (!$tmpproduct->$statustotest) {
12104 $langs->load('products');
12105 $statuskey4lang = ($status == 'onsale' ? 'ProductStatusNotOnSell' : 'ProductStatusNotOnBuy');
12106 $ret = false;
12107 $this->errors[] = $langs->trans('ProductRef').' '.$tmpproduct->ref.' '.$langs->trans($statuskey4lang);
12108 break;
12109 }
12110 }
12111 }
12112 if (!$ret) {
12113 $this->error = 'ErrorOneLineContainsADisactivatedProduct';
12114 }
12115 return $ret;
12116 } else {
12117 return true;
12118 }
12119 }
12120
12127 public function setErrorWithoutLog($message)
12128 {
12129 $this->error = $message;
12130 $this->errors[] = $message;
12131 }
12132
12140 public function setErrorWithLog($message, $loglevel = LOG_ERR)
12141 {
12142 global $dolibarr_main_document_root;
12143
12144 $this->setErrorWithoutLog($message);
12145 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
12146 $file = str_replace($dolibarr_main_document_root, '', $trace[0]['file'] ?? 'file unknown');
12147 $line = $trace[0]['line'] ?? 'line unknown';
12148 $syslogMessage = sprintf('%s:%s %s', $file, $line, $message);
12149 dol_syslog($syslogMessage, $loglevel);
12150 }
12151}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
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:476
$c
Definition line.php:334
$object ref
Definition info.php:90
Class to manage members of a foundation.
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
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='')
Set status of an object.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
setErrorWithoutLog($message)
Set the error message for the object without logging it.
roundQtyToPackaging($qty, $packaging)
Round a quantity up to the next multiple of a packaging quantity (options PRODUCT_USE_CUSTOMER_PACKAG...
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.
fetchProject()
Load the project with id $this->fk_project into this->project.
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.
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.
delete_resource($rowid, $element='', $notrigger=0)
Delete a link to resource line.
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)
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
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.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0, $notrigger=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
checkActiveProductInLines($status='onsale')
Check if all products have the right status (on sale, on buy) called during validation of propal,...
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.
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.
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) Used for ex...
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra languages 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.
fetchBarCode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
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.
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...
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.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0, $qty=0)
Get buy price to use for margin calculation.
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.
setErrorWithLog($message, $loglevel=LOG_ERR)
Set the error message for the object and logs it, including the file name and line number.
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.
getRights()
Returns the rights used for this class.
addThumbs($file, $quality=50)
Build thumb.
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 donations.
Definition don.class.php:41
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.
Parent class of subscription templates.
Parent class to manage intervention document templates.
static getIdAndTxFromCode($dbs, $code, $date_document=0)
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.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
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:263
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_meta_create($object)
Create a meta file with document file into same directory.
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir, $object=null)
Complete $filearray with data from database.
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_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
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:64
dol_is_dir($folder)
Test if filename is a directory.
dol_delete_preview($object)
Delete all preview files linked to object instance.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
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...
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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_ip($ip, $mode=0, $showname=0)
Return an IP formatted to be shown on screen.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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.
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
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_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.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
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.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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 a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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_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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:141
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.