dolibarr 25.0.0-alpha
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 * Copyright (C) 2026 Anthony Berton <anthony.berton@bb2a.fr>
26
27 * Copyright (C) 2026 José MARTINEZ <jose.martinez@pichinov.com>
28 *
29 * This program is free software; you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation; either version 3 of the License, or
32 * (at your option) any later version.
33 *
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
38 *
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <https://www.gnu.org/licenses/>.
41 */
42
49require_once DOL_DOCUMENT_ROOT.'/core/class/doldeprecationhandler.class.php';
50require_once DOL_DOCUMENT_ROOT.'/core/class/commontrigger.class.php';
51
59abstract class CommonObject
60{
61 use DolDeprecationHandler;
62 use CommonTrigger;
63
67 public $module;
68
72 public $db;
73
77 public $id;
78
82 public $entity;
83
88 public $error;
89
93 public $errorhidden;
94
98 public $errors = array();
99
104 public $warning;
105
109 public $warnings = array();
110
114 private $validateFieldsErrors = array();
115
119 public $element;
120
125 public $fk_element;
126
132 public $element_for_permission;
133
137 public $table_element;
138
142 public $table_rowid;
143
147 public $table_element_line = '';
148
153 public $ismultientitymanaged;
154
158 public $import_key;
159
163 public $array_options = array();
164
165
248 public $fields = array();
249
255 public $array_languages = null; // Value is array() when load already tried
256
260 public $contacts_ids;
261
265 public $contacts_ids_internal;
266
270 public $linked_objects;
271
275 public $other_linked_objects;
276
280 public $linkedObjectsIds;
281
285 public $linkedObjects;
286
290 private $linkedObjectsFullLoaded = array();
291
295 public $oldcopy;
296
300 public $oldref;
301
305 protected $table_ref_field = '';
306
310 public $restrictiononfksoc = 0;
311
312
313 // The following vars are used by some objects only.
314 // We keep these properties in CommonObject in order to provide common methods using them.
315
319 public $context = array();
320
324 public $actionmsg;
328 public $actionmsg2;
329
333 public $canvas;
334
339 public $project;
340
345 public $fk_project;
346
352 public $fk_projet;
353
358 public $contact;
359
364 public $contact_id;
365
370 public $thirdparty;
371
376 public $user;
377
382 public $product;
383
388 public $warehouse;
389
394 public $origin_type;
395
400 public $origin_id;
401
406
412 public $origin;
413
422 private $expedition;
423
429 private $livraison;
430
436 private $commandeFournisseur;
437
438
442 public $ref;
443
447 public $ref_ext;
448
452 public $ref_previous;
453
457 public $ref_next;
458
462 public $newref;
463
470 public $statut;
471
480 public $status;
481
486 public $country;
487
492 public $country_id;
493
498 public $country_code;
499
504 public $state;
505
510 public $state_id;
511
516 public $state_code;
517
522 public $region_id;
523
528 public $region_code;
529
534 public $region;
535
536
541 public $barcode_type;
542
547 public $barcode_type_code;
548
553 public $barcode_type_label;
554
559 public $barcode_type_coder;
560
565 public $mode_reglement_id;
566
571 public $cond_reglement_id;
572
576 public $demand_reason_id;
577
582 public $transport_mode_id;
583
594 protected $depr_cond_reglement; // Internal value for deprecation
595
601 public $fk_delivery_address;
602
607 public $shipping_method_id;
608
613 public $shipping_method;
614
615 // Multicurrency
619 public $fk_multicurrency;
620
625 public $multicurrency_code;
626
631 public $multicurrency_tx;
632
636 public $multicurrency_total_ht;
637
641 public $multicurrency_total_tva;
642
646 public $multicurrency_total_localtax1; // not in database
647
651 public $multicurrency_total_localtax2; // not in database
652
656 public $multicurrency_total_ttc;
657
658
663 public $model_pdf;
664
669 public $last_main_doc;
670
676 public $fk_bank;
677
682 public $fk_account;
683
688 public $note_public;
689
694 public $note_private;
695
701 public $note;
702
707 public $total_ht;
708
713 public $total_tva;
714
719 public $total_localtax1;
720
725 public $total_localtax2;
726
731 public $total_ttc;
732
733
737 public $lines;
738
742 public $actiontypecode;
743
748 public $comments = array();
749
753 public $name;
754
758 public $lastname;
759
763 public $firstname;
764
769 public $civility_id;
770
774 public $civility_code;
775
776 // Dates
780 public $date_creation;
781
785 public $date_validation;
786
790 public $date_modification;
791
797 public $tms;
798
804 private $date_update;
805
809 public $date_cloture;
810
814 public $user_creation_id;
815
819 public $user_validation_id;
820
824 public $user_closing_id;
825
829 public $user_modification_id;
830
835 public $fk_user_creat;
836
841 public $fk_user_modif;
842
843
847 public $next_prev_filter;
848
852 public $specimen = 0;
853
857 public $sendtoid;
858
859
864 public $alreadypaid;
865
870 public $totalpaid;
871
876 public $totalpaid_multicurrency;
877
878
882 public $labelStatus = array();
883
887 public $labelStatusShort = array();
888
892 public $tpl;
893
894
898 public $showphoto_on_popup;
899
903 public $nb = array();
904
908 public $nbphoto;
909
913 public $output;
914
918 public $extraparams = array();
919
923 protected $childtables = array();
924
930 protected $childtablesoncascade = array();
931
935 public $cond_reglement_supplier_id;
936
942 public $deposit_percent;
943
944
948 public $warehouse_id;
949
953 public $isextrafieldmanaged = 0;
954
963 public $attachedfiles;
964
965
966
967 // No constructor as it is an abstract class
968
974 protected function deprecatedProperties()
975 {
976 return array(
977 'alreadypaid' => 'totalpaid',
978 'cond_reglement' => 'depr_cond_reglement',
979 //'note' => 'note_private', // Some classes needs ->note and others need ->note_public/private so we can't manage deprecation for this field with dolDeprecationHandler
980 'commandeFournisseur' => 'origin_object',
981 'expedition' => 'origin_object',
982 'fk_project' => 'fk_project',
983 'livraison' => 'origin_object',
984 'projet' => 'project',
985 'statut' => 'status',
986 );
987 }
988
989
1000 public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
1001 {
1002 global $db, $conf;
1003
1004 $sql = "SELECT rowid";
1005 $sql .= " FROM ".$db->prefix().$element;
1006 $sql .= " WHERE entity IN (".getEntity($element).")";
1007
1008 if ($id > 0) {
1009 $sql .= " AND rowid = ".((int) $id);
1010 } elseif ($ref) {
1011 $sql .= " AND ref = '".$db->escape($ref)."'";
1012 } elseif ($ref_ext) {
1013 $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
1014 } else {
1015 $error = 'ErrorWrongParameters';
1016 dol_syslog(get_class()."::isExistingObject ".$error, LOG_ERR);
1017 return -1;
1018 }
1019 if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
1020 $sql .= " AND entity = ".((int) $conf->entity);
1021 }
1022
1023 dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
1024 $resql = $db->query($sql);
1025 if ($resql) {
1026 $num = $db->num_rows($resql);
1027 if ($num > 0) {
1028 return 1;
1029 } else {
1030 return 0;
1031 }
1032 }
1033 return -1;
1034 }
1035
1043 {
1044 if (!empty($object->error)) {
1045 $this->error = $object->error;
1046 }
1047 if (!empty($object->errors)) {
1048 $this->errors = array_merge($this->errors, $object->errors);
1049 }
1050 }
1051
1059 public function getTooltipContentArray($params)
1060 {
1061 return [];
1062 }
1063
1071 public function getTooltipContent($params)
1072 {
1073 global $action, $extrafields, $langs, $hookmanager;
1074
1075 // If there is too much extrafields, we do not include them into tooltip
1076 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
1077
1078 $data = $this->getTooltipContentArray($params);
1079 $count = 0;
1080
1081 // Add extrafields
1082 if (!empty($extrafields->attributes[$this->table_element]['label'])) {
1083 $data['opendivextra'] = '<div class="centpercent wordbreak divtooltipextra">';
1084 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
1085 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
1086 continue;
1087 }
1088
1089 if (empty($extrafields->attributes[$this->table_element]['showintooltip'][$key])) {
1090 continue;
1091 }
1092
1093
1094 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1095 $data['more_extrafields'] = '<br>...';
1096 break;
1097 }
1098 $enabled = 1;
1099 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
1100 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
1101 }
1102 if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
1103 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
1104 }
1105 $perms = 1;
1106 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
1107 $perms = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
1108 }
1109 if (empty($enabled)) {
1110 continue; // 0 = Never visible field
1111 }
1112 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1113 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation
1114 }
1115 if (empty($perms)) {
1116 continue; // 0 = Not visible
1117 }
1118 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
1119 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
1120 }
1121 $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
1122 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
1123 $data[$key] = '<br><b><u>'. $labelextra . '</u></b>';
1124 } else {
1125 $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
1126 $data[$key] = '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
1127 $count++;
1128 }
1129 }
1130 $data['closedivextra'] = '</div>';
1131 }
1132
1133 $hookmanager->initHooks(array($this->element . 'dao'));
1134 $parameters = array(
1135 'tooltipcontentarray' => &$data,
1136 'params' => $params,
1137 );
1138 // Note that $action and $object may have been modified by some hooks
1139 $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
1140
1141 //var_dump($data);
1142 $label = implode($data);
1143
1144 return $label;
1145 }
1146
1147
1153 public function errorsToString()
1154 {
1155 return $this->error.(is_array($this->errors) && count($this->errors) > 0 ? (($this->error != '' ? ', ' : '').implode(', ', $this->errors)) : '');
1156 }
1157
1158
1165 public function getFormatedCustomerRef($objref)
1166 {
1167 global $hookmanager;
1168
1169 $parameters = array('objref' => $objref);
1170 $action = '';
1171 $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1172 if ($reshook > 0) {
1173 return $hookmanager->resArray['objref'];
1174 }
1175 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1176 }
1177
1184 public function getFormatedSupplierRef($objref)
1185 {
1186 global $hookmanager;
1187
1188 $parameters = array('objref' => $objref);
1189 $action = '';
1190 $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1191 if ($reshook > 0) {
1192 return $hookmanager->resArray['objref'];
1193 }
1194 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1195 }
1196
1206 public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
1207 {
1208 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1209 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1210 $tmparray = getCountry($this->country_id, 'all');
1211 $this->country_code = $tmparray['code'];
1212 $this->country = $tmparray['label'];
1213 }
1214
1215 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1216 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1217 $tmparray = getState($this->state_id, 'all', null, 1);
1218 $this->state_code = $tmparray['code'];
1219 $this->state = $tmparray['label'];
1220 $this->region_code = $tmparray['region_code'];
1221 $this->region = $tmparray['region'];
1222 }
1223
1224 return dol_format_address($this, $withcountry, $sep, null, 0, $extralangcode);
1225 }
1226
1227
1236 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1237 {
1238 global $user, $dolibarr_main_url_root;
1239
1240 if (empty($this->last_main_doc)) {
1241 return ''; // No way to known which document name to use
1242 }
1243
1244 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1245 $ecmfile = new EcmFiles($this->db);
1246 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1247 if ($result < 0) {
1248 $this->error = $ecmfile->error;
1249 $this->errors = $ecmfile->errors;
1250 return -1;
1251 }
1252
1253 if (empty($ecmfile->id)) { // No entry into file index already exists, we should initialize the shared key manually.
1254 // Add entry into index
1255 if ($initsharekey) {
1256 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1257
1258 // 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
1259 /*
1260 $ecmfile->filepath = $rel_dir;
1261 $ecmfile->filename = $filename;
1262 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1263 $ecmfile->fullpath_orig = '';
1264 $ecmfile->gen_or_uploaded = 'generated';
1265 $ecmfile->description = ''; // indexed content
1266 $ecmfile->keywords = ''; // keyword content
1267 $ecmfile->share = getRandomPassword(true);
1268 $result = $ecmfile->create($user);
1269 if ($result < 0)
1270 {
1271 $this->error = $ecmfile->error;
1272 $this->errors = $ecmfile->errors;
1273 }
1274 */
1275 } else {
1276 return '';
1277 }
1278 } elseif (empty($ecmfile->share)) { // Entry into file index already exists but no share key is defined.
1279 // Add entry into index
1280 if ($initsharekey) {
1281 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1282 $ecmfile->share = getRandomPassword(true);
1283 $ecmfile->update($user);
1284 } else {
1285 return '';
1286 }
1287 }
1288 // Define $urlwithroot
1289 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1290 // This is to use external domain name found into config file
1291 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1292 //else
1293 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1294 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1295
1296 $forcedownload = 0;
1297
1298 $paramlink = '';
1299 //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1300 //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1301 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1302 if (!empty($ecmfile->share)) {
1303 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1304 }
1305 if ($forcedownload) {
1306 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1307 }
1308
1309 if ($relativelink) {
1310 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1311 } else {
1312 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1313 }
1314
1315 // Here $ecmfile->share is defined
1316 return $linktoreturn;
1317 }
1318
1319
1320 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1330 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1331 {
1332 // phpcs:enable
1333 global $user, $langs;
1334
1335 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1336
1337 // Check parameters
1338 if ($fk_socpeople <= 0) {
1339 $langs->load("errors");
1340 $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1341 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1342 return -1;
1343 }
1344
1345 // Check that the contact actually exists in database
1346 $sql_check = "SELECT rowid FROM ".$this->db->prefix().($source == 'internal' ? "user" : "socpeople")." WHERE rowid = ".((int) $fk_socpeople);
1347 $resql_check = $this->db->query($sql_check);
1348 if ($resql_check) {
1349 if (!$this->db->num_rows($resql_check)) {
1350 $langs->load("errors");
1351 $this->error = $langs->trans("ErrorRecordNotFound");
1352 dol_syslog(get_class($this)."::add_contact Contact/user id ".$fk_socpeople." does not exist", LOG_ERR);
1353 return -1;
1354 }
1355 } else {
1356 $this->error = $this->db->lasterror();
1357 return -1;
1358 }
1359
1360 if (!$type_contact) {
1361 $langs->load("errors");
1362 $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1363 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1364 return -2;
1365 }
1366
1367 // socid is checked: @phan-suppress-next-line PhanUndeclaredProperty
1368 if ($this->restrictiononfksoc && property_exists($this, 'socid') && !empty($this->socid) && $user->id > 0 && !$user->hasRight('societe', 'client', 'voir')) {
1369 $sql_allowed_contacts = 'SELECT COUNT(*) as cnt FROM '.$this->db->prefix().'societe_commerciaux as sc';
1370 // socid is checked: @phan-suppress-next-line PhanUndeclaredProperty
1371 $sql_allowed_contacts .= ' WHERE sc.fk_soc = '.(int) $this->socid;
1372 $sql_allowed_contacts .= ' AND sc.fk_user = '.(int) $user->id;
1373
1374 $resql_allowed_contacts = $this->db->query($sql_allowed_contacts);
1375
1376 if (!$resql_allowed_contacts) {
1377 $this->errors[] = $this->db->lasterror();
1378 return -3;
1379 } elseif ($obj = $this->db->fetch_object($resql_allowed_contacts)) {
1380 if ($obj->cnt == 0) {
1381 $langs->load("companies");
1382 $this->error = $langs->trans("ErrorCommercialNotAllowedForThirdparty", $user->id);
1383 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1384 return -4;
1385 }
1386 }
1387 }
1388
1389 $id_type_contact = 0;
1390 if (is_numeric($type_contact)) {
1391 $id_type_contact = $type_contact;
1392 } else {
1393 // We look for id type_contact
1394 $sql = "SELECT tc.rowid";
1395 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1396 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1397 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1398 $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1399 //print $sql;
1400 $resql = $this->db->query($sql);
1401 if ($resql) {
1402 $obj = $this->db->fetch_object($resql);
1403 if ($obj) {
1404 $id_type_contact = $obj->rowid;
1405 }
1406 }
1407 }
1408 if ($id_type_contact == 0) {
1409 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");
1410 return 0;
1411 }
1412
1413 $datecreate = dol_now();
1414
1415 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1416 $TListeContacts = $this->liste_contact(-1, $source);
1417 $already_added = false;
1418 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1419 foreach ($TListeContacts as $array_contact) {
1420 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1421 $already_added = true;
1422 break;
1423 }
1424 }
1425 }
1426
1427 if (!$already_added) {
1428 $this->db->begin();
1429
1430 // Insert into database
1431 $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1432 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1433 $sql .= " VALUES (".((int) $this->id).", ".((int) $fk_socpeople)." , ";
1434 $sql .= "'".$this->db->idate($datecreate)."'";
1435 $sql .= ", 4, ".((int) $id_type_contact);
1436 $sql .= ")";
1437
1438 $resql = $this->db->query($sql);
1439 if ($resql) {
1440 if (!$notrigger) {
1441 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1442 $result = $this->call_trigger($triggerPrefix.'_ADD_CONTACT', $user);
1443 if ($result < 0) {
1444 $this->db->rollback();
1445 return -5;
1446 }
1447 }
1448
1449 $this->db->commit();
1450 return 1;
1451 } else {
1452 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1453 $this->error = $this->db->errno();
1454 $this->db->rollback();
1455 return -6;
1456 } else {
1457 $this->error = $this->db->lasterror();
1458 $this->db->rollback();
1459 return -7;
1460 }
1461 }
1462 } else {
1463 return 0;
1464 }
1465 }
1466
1467 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1475 public function copy_linked_contact($objFrom, $source = 'internal')
1476 {
1477 // phpcs:enable
1478 $contacts = $objFrom->liste_contact(-1, $source);
1479 foreach ($contacts as $contact) {
1480 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1481 return -1;
1482 }
1483 }
1484 return 1;
1485 }
1486
1487 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1497 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1498 {
1499 // phpcs:enable
1500 // Insert into database
1501 $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1502 $sql .= " statut = ".((int) $statut);
1503 if ($type_contact_id) {
1504 $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1505 }
1506 if ($fk_socpeople) {
1507 $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1508 }
1509 $sql .= " where rowid = ".((int) $rowid);
1510
1511 $resql = $this->db->query($sql);
1512 if ($resql) {
1513 return 0;
1514 } else {
1515 $this->error = $this->db->lasterror();
1516 return -1;
1517 }
1518 }
1519
1520 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1528 public function delete_contact($rowid, $notrigger = 0)
1529 {
1530 // phpcs:enable
1531 global $user;
1532
1533 $error = 0;
1534
1535 // When called on a loaded object, the link must be one of its own contacts (same filter as liste_contact())
1536 if ($this->id > 0) {
1537 $sql = "SELECT ec.rowid FROM ".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc";
1538 $sql .= " WHERE ec.rowid = ".((int) $rowid)." AND ec.element_id = ".((int) $this->id);
1539 $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element = '".$this->db->escape($this->element)."'";
1540 $resql = $this->db->query($sql);
1541 if (!$resql || !$this->db->num_rows($resql)) {
1542 $this->error = 'ErrorRecordNotFound';
1543 return -1;
1544 }
1545 }
1546
1547 $this->db->begin();
1548
1549 if (!$error && empty($notrigger)) {
1550 // Call trigger
1551 $this->context['contact_id'] = ((int) $rowid);
1552 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper($this->element) : $this->TRIGGER_PREFIX);
1553 $result = $this->call_trigger($triggerPrefix.'_DELETE_CONTACT', $user);
1554 if ($result < 0) {
1555 $error++;
1556 }
1557 // End call triggers
1558 }
1559
1560 if (!$error) {
1561 dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1562
1563 $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1564 $sql .= " WHERE rowid = ".((int) $rowid);
1565
1566 $result = $this->db->query($sql);
1567 if (!$result) {
1568 $error++;
1569 $this->errors[] = $this->db->lasterror();
1570 }
1571 }
1572
1573 if (!$error) {
1574 $this->db->commit();
1575 return 1;
1576 } else {
1577 $this->error = $this->db->lasterror();
1578 $this->db->rollback();
1579 return -1;
1580 }
1581 }
1582
1583 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1591 public function delete_linked_contact($source = '', $code = '')
1592 {
1593 // phpcs:enable
1594 $listId = '';
1595 $temp = array();
1596 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1597
1598 if (!empty($typeContact)) {
1599 foreach ($typeContact as $key => $value) {
1600 array_push($temp, $key);
1601 }
1602 $listId = implode(",", $temp);
1603 }
1604
1605 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1606 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1607 if (empty($listId)) {
1608 return 0;
1609 }
1610
1611 $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1612 $sql .= " WHERE element_id = ".((int) $this->id);
1613 $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1614
1615 dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1616 if ($this->db->query($sql)) {
1617 return 1;
1618 } else {
1619 $this->error = $this->db->lasterror();
1620 return -1;
1621 }
1622 }
1623
1624 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1636 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1637 {
1638 // phpcs:enable
1639 global $langs;
1640
1641 $tab = array();
1642
1643 $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
1644 if ($source == 'internal') {
1645 $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender, t.fk_country as country_id";
1646 }
1647 if ($source == 'external' || $source == 'thirdparty') {
1648 $sql .= ", t.fk_soc as socid, t.statut as statuscontact, t.fk_pays as country_id";
1649 }
1650 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email, t.address, t.zip, t.town";
1651 if (empty($arrayoftcids)) {
1652 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label, co.label as country";
1653 }
1654 $sql .= " FROM";
1655 if (empty($arrayoftcids)) {
1656 $sql .= " ".$this->db->prefix()."c_type_contact as tc,";
1657 }
1658 $sql .= " ".$this->db->prefix()."element_contact as ec";
1659 if ($source == 'internal') { // internal contact (user)
1660 $sql .= " LEFT JOIN ".$this->db->prefix()."user as t on ec.fk_socpeople = t.rowid";
1661 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as co ON co.rowid = t.fk_country";
1662 }
1663 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1664 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople as t on ec.fk_socpeople = t.rowid";
1665 $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as co ON co.rowid = t.fk_pays";
1666 }
1667 $sql .= " WHERE ec.element_id = ".((int) $this->id);
1668 if (empty($arrayoftcids)) {
1669 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1670 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1671 if ($code) {
1672 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1673 }
1674 if ($source == 'internal') {
1675 $sql .= " AND tc.source = 'internal'";
1676 }
1677 if ($source == 'external' || $source == 'thirdparty') {
1678 $sql .= " AND tc.source = 'external'";
1679 }
1680 $sql .= " AND tc.active = 1";
1681 } else {
1682 $sql .= " AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', $arrayoftcids)).")";
1683 }
1684 if ($status >= 0) {
1685 $sql .= " AND t.statut = ".((int) $status); // t is llx_user or llx_socpeople
1686 }
1687 if ($statusoflink >= 0) {
1688 $sql .= " AND ec.statut = ".((int) $statusoflink);
1689 }
1690 $sql .= " ORDER BY t.lastname ASC";
1691
1692 dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1693 $resql = $this->db->query($sql);
1694 if ($resql) {
1695 $num = $this->db->num_rows($resql);
1696 $i = 0;
1697 while ($i < $num) {
1698 $obj = $this->db->fetch_object($resql);
1699
1700 if (!$list) {
1701 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1702 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1703 $tab[$i] = array(
1704 'parentId' => $this->id,
1705 'source' => $obj->source,
1706 'socid' => $obj->socid,
1707 'id' => $obj->id,
1708 'nom' => $obj->lastname, // For backward compatibility
1709 'civility' => $obj->civility,
1710 'lastname' => $obj->lastname,
1711 'firstname' => $obj->firstname,
1712 'email' => $obj->email,
1713 'address' => $obj->address,
1714 'zip' => $obj->zip,
1715 'town' => $obj->town,
1716 'country_id' => $obj->country_id,
1717 'country' => $obj->country,
1718 'login' => (empty($obj->login) ? '' : $obj->login),
1719 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1720 'gender' => (empty($obj->gender) ? '' : $obj->gender),
1721 'statuscontact' => $obj->statuscontact,
1722 'rowid' => $obj->rowid,
1723 'code' => $obj->code,
1724 'libelle' => $label_type,
1725 'status' => (int) $obj->statuslink,
1726 'fk_c_type_contact' => $obj->fk_c_type_contact
1727 );
1728 } else {
1729 $tab[$i] = $obj->id;
1730 }
1731
1732 $i++;
1733 }
1734
1735 return $tab;
1736 } else {
1737 $this->error = $this->db->lasterror();
1738 dol_print_error($this->db);
1739 return -1;
1740 }
1741 }
1742
1743
1750 public function swapContactStatus($rowid)
1751 {
1752 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1753 $sql .= " tc.code, tc.libelle as type_label";
1754 $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1755 $sql .= " WHERE ec.rowid =".((int) $rowid);
1756 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1757 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1758
1759 dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1760 $resql = $this->db->query($sql);
1761 if ($resql) {
1762 $obj = $this->db->fetch_object($resql);
1763 $newstatut = ($obj->statut == 4) ? 5 : 4;
1764 $result = $this->update_contact($rowid, $newstatut);
1765 $this->db->free($resql);
1766 return $result;
1767 } else {
1768 $this->error = $this->db->error();
1769 dol_print_error($this->db);
1770 return -1;
1771 }
1772 }
1773
1774 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1785 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1786 {
1787 // phpcs:enable
1788 global $langs;
1789
1790 $sanitized_order = $order; // @phan-suppress-current-line SqlInjection
1791
1792 if (empty($sanitized_order)) {
1793 $sanitized_order = 'position';
1794 }
1795 if ($sanitized_order == 'position') {
1796 $sanitized_order .= ',code';
1797 }
1798
1799 $tab = array();
1800
1801 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1802 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1803 $sql .= " WHERE tc.element = '".$this->db->escape($this->element)."'";
1804 if ($activeonly == 1) {
1805 $sql .= " AND tc.active = 1"; // only the active types
1806 }
1807 if (!empty($source) && $source != 'all') {
1808 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1809 }
1810 if (!empty($code)) {
1811 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1812 }
1813 $sql .= $this->db->order($sanitized_order, 'ASC');
1814
1815 //print "sql=".$sql;
1816 $resql = $this->db->query($sql);
1817 if (!$resql) {
1818 $this->error = $this->db->lasterror();
1819 //dol_print_error($this->db);
1820 return null;
1821 }
1822
1823 $num = $this->db->num_rows($resql);
1824 $i = 0;
1825 while ($i < $num) {
1826 $obj = $this->db->fetch_object($resql);
1827
1828 $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1829 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $langs->trans($obj->type_label));
1830 if (empty($option)) {
1831 $tab[$obj->rowid] = $label_type;
1832 } elseif ($option == 1) {
1833 $tab[$obj->code] = $label_type;
1834 } else {
1835 $tab[$obj->rowid] = array('id' => $obj->rowid, 'code' => $obj->code, 'label' => $label_type);
1836 }
1837 $i++;
1838 }
1839
1840 return $tab;
1841 }
1842
1854 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1855 {
1856 global $langs;
1857
1858 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1859
1860 $tab = array();
1861
1862 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element, tc.module";
1863 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1864
1865 $sqlWhere = array();
1866 if (!empty($element)) {
1867 $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1868 }
1869 if (!empty($excludeelement)) {
1870 $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1871 }
1872
1873 if ($activeonly == 1) {
1874 $sqlWhere[] = " tc.active=1"; // only the active types
1875 }
1876
1877 if (!empty($source) && $source != 'all') {
1878 $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1879 }
1880
1881 if (!empty($code)) {
1882 $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1883 }
1884
1885 if (count($sqlWhere) > 0) {
1886 $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1887 }
1888
1889 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1890
1891 dol_syslog(__METHOD__, LOG_DEBUG);
1892 $resql = $this->db->query($sql);
1893 if ($resql) {
1894 $num = $this->db->num_rows($resql);
1895 if ($num > 0) {
1896 $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1897
1898 while ($obj = $this->db->fetch_object($resql)) {
1899 $modulename = $obj->module ?? $obj->element;
1900 if (strpos($obj->element, 'project') !== false) {
1901 $modulename = 'projet';
1902 } elseif ($obj->element == 'contrat') {
1903 $element = 'contract';
1904 } elseif ($obj->element == 'action') {
1905 $modulename = 'agenda';
1906 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1907 $modulename = 'fournisseur';
1908 }
1909 if (isModEnabled($modulename)) {
1910 $label_element = $langs->trans('ContactDefault_'.$obj->element);
1911 $tmpelement = $obj->element;
1912 $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1913 $label_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1914 $tab[$obj->rowid] = $label_element.' - '.$label_type;
1915 }
1916 }
1917 }
1918 return $tab;
1919 } else {
1920 $this->error = $this->db->lasterror();
1921 return null;
1922 }
1923 }
1924
1936 public function getIdContact($source, $code, $status = 0)
1937 {
1938 $result = array();
1939 $i = 0;
1940 // Particular case for shipping
1941 if (!getDolGlobalInt('SHIPPING_USE_ITS_OWN_CONTACTS') && $this->element == 'shipping' && $this->origin_id != 0) {
1942 $id = $this->origin_id;
1943 $element = 'commande';
1944 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1945 $id = $this->origin_id;
1946 $element = 'order_supplier';
1947 } else {
1948 $id = $this->id;
1949 $element = $this->element;
1950 }
1951
1952 $sql = "SELECT ec.fk_socpeople";
1953 $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1954 if ($source == 'internal') {
1955 $sql .= " ".$this->db->prefix()."user as c,";
1956 }
1957 if ($source == 'external') {
1958 $sql .= " ".$this->db->prefix()."socpeople as c,";
1959 }
1960 $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1961 $sql .= " WHERE ec.element_id = ".((int) $id);
1962 $sql .= " AND ec.fk_socpeople = c.rowid";
1963 if ($source == 'internal') {
1964 $sql .= " AND c.entity IN (".getEntity('user').")";
1965 }
1966 if ($source == 'external') {
1967 $sql .= " AND c.entity IN (".getEntity('societe').")";
1968 }
1969 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1970 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1971 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1972 if ($code) {
1973 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1974 }
1975 $sql .= " AND tc.active = 1";
1976 if ($status) {
1977 $sql .= " AND ec.statut = ".((int) $status);
1978 }
1979
1980 dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1981 $resql = $this->db->query($sql);
1982 if ($resql) {
1983 while ($obj = $this->db->fetch_object($resql)) {
1984 $result[$i] = $obj->fk_socpeople;
1985 $i++;
1986 }
1987 } else {
1988 $this->error = $this->db->error();
1989 return null;
1990 }
1991
1992 return $result;
1993 }
1994
1995 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2002 public function fetch_contact($contactid = null)
2003 {
2004 // phpcs:enable
2005 if (empty($contactid)) {
2006 $contactid = $this->contact_id;
2007 }
2008
2009 if (empty($contactid)) {
2010 return 0;
2011 }
2012
2013 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
2014 $contact = new Contact($this->db);
2015 $result = $contact->fetch($contactid);
2016 $this->contact = $contact;
2017 return $result;
2018 }
2019
2020 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2028 public function fetch_thirdparty($force_thirdparty_id = 0)
2029 {
2030 // phpcs:enable
2031 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
2032 return 0;
2033 }
2034
2035 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
2036
2037 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
2038 if ($force_thirdparty_id) {
2039 $idtofetch = $force_thirdparty_id;
2040 }
2041
2042 if ($idtofetch) {
2043 $thirdparty = new Societe($this->db);
2044 $result = $thirdparty->fetch($idtofetch);
2045 if ($result < 0) {
2046 $this->errors = array_merge($this->errors, $thirdparty->errors);
2047 }
2048 $this->thirdparty = $thirdparty;
2049
2050 // Use first price level if level not defined for third party
2051 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->thirdparty->price_level)) {
2052 $this->thirdparty->price_level = 1;
2053 }
2054
2055 return $result;
2056 } else {
2057 return -1;
2058 }
2059 }
2060
2061
2069 public function fetchOneLike($ref)
2070 {
2071 if (!$this->table_ref_field) {
2072 return 0;
2073 }
2074
2075 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
2076 $sql .= " WHERE ".$this->db->sanitize($this->table_ref_field)." LIKE '".$this->db->escape($ref)."'"; // no escapeforlike here
2077 $sql .= " LIMIT 1";
2078
2079 $query = $this->db->query($sql);
2080
2081 if (!$this->db->num_rows($query)) {
2082 return 0;
2083 }
2084
2085 $result = $this->db->fetch_object($query);
2086
2087 if (method_exists($this, 'fetch')) {
2088 return $this->fetch($result->rowid);
2089 } else {
2090 $this->error = 'Fetch method not implemented on '.get_class($this);
2091 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2092 array_push($this->errors, $this->error);
2093 return -1;
2094 }
2095 }
2096
2097 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2106 public function fetch_barcode()
2107 {
2108 // phpcs:enable
2109 return $this->fetchBarCode();
2110 }
2111
2119 public function fetchBarCode()
2120 {
2121 dol_syslog(get_class($this).'::fetchBarCode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
2122
2123 $idtype = $this->barcode_type;
2124 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
2125 if ($this->element == 'product' && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) {
2126 $idtype = getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE');
2127 } elseif ($this->element == 'societe') {
2128 $idtype = getDolGlobalString('GENBARCODE_BARCODETYPE_THIRDPARTY');
2129 } else {
2130 dol_syslog('Call fetchBarCode with barcode_type not defined and cannot be guessed', LOG_WARNING);
2131 }
2132 }
2133
2134 if ($idtype > 0) {
2135 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
2136 $sql = "SELECT rowid, code, libelle as label, coder";
2137 $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
2138 $sql .= " WHERE rowid = ".((int) $idtype);
2139
2140 $resql = $this->db->query($sql);
2141 if ($resql) {
2142 $obj = $this->db->fetch_object($resql);
2143
2144 $this->barcode_type = $obj->rowid;
2145 $this->barcode_type_code = $obj->code;
2146 $this->barcode_type_label = $obj->label;
2147 $this->barcode_type_coder = $obj->coder;
2148 return 1;
2149 } else {
2150 dol_print_error($this->db);
2151 return -1;
2152 }
2153 }
2154 }
2155 return 0;
2156 }
2157
2163 public function fetchProject()
2164 {
2165 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
2166
2167 /* Done with DolDeprecationHandler
2168 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2169 $this->fk_project = $this->fk_projet; // For backward compatibility
2170 }
2171 */
2172 if (empty($this->fk_project)) {
2173 return 0;
2174 }
2175
2176 $project = new Project($this->db);
2177 $result = $project->fetch($this->fk_project);
2178
2179 $this->project = $project;
2180
2181 return $result;
2182 }
2183
2184 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2192 public function fetch_project()
2193 {
2194 // phpcs:enable
2195 return $this->fetchProject();
2196 }
2197
2198 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2206 public function fetch_projet()
2207 {
2208 // phpcs:enable
2209 return $this->fetchProject();
2210 }
2211
2212 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2218 public function fetch_product()
2219 {
2220 // phpcs:enable
2221 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2222
2223 // @phan-suppress-next-line PhanUndeclaredProperty
2224 if (empty($this->fk_product)) {
2225 return 0;
2226 }
2227
2228 $product = new Product($this->db);
2229 // @phan-suppress-next-line PhanUndeclaredProperty
2230 $result = $product->fetch($this->fk_product);
2231
2232 $this->product = $product;
2233 return $result;
2234 }
2235
2242 public function fetchWarehouse($force_warehouse_id = 0)
2243 {
2244 // testing through empty: @phan-suppress-next-line PhanUndeclaredProperty
2245 if (empty($this->warehouse_id) && empty($this->fk_warehouse) && empty($force_warehouse_id)) {
2246 return 0;
2247 }
2248
2249 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2250
2251 // testing through isset: @phan-suppress-next-line PhanUndeclaredProperty
2252 $idtofetch = isset($this->warehouse_id) ? $this->warehouse_id : (isset($this->fk_warehouse) ? $this->fk_warehouse : 0);
2253 if (!empty($force_warehouse_id)) {
2254 $idtofetch = $force_warehouse_id;
2255 }
2256
2257 if ($idtofetch) {
2258 $warehouse = new Entrepot($this->db);
2259 $result = $warehouse->fetch($idtofetch);
2260 if ($result < 0) {
2261 $this->errors = array_merge($this->errors, $warehouse->errors);
2262 }
2263 $this->warehouse = $warehouse;
2264
2265 return $result;
2266 } else {
2267 return -1;
2268 }
2269 }
2270
2271 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2278 public function fetch_user($userid)
2279 {
2280 // phpcs:enable
2281 $user = new User($this->db);
2282 $result = $user->fetch($userid);
2283 $this->user = $user;
2284 return $result;
2285 }
2286
2287 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2294 public function fetch_origin()
2295 {
2296 // phpcs:enable
2297 $tmpclassname = $this->origin ? $this->origin : $this->origin_type;
2298
2299 // Manage classes with non standard name
2300 if ($tmpclassname == 'shipping') {
2301 $tmpclassname = 'Expedition';
2302 }
2303 if ($tmpclassname == 'delivery') {
2304 $tmpclassname = 'Livraison';
2305 }
2306 if ($tmpclassname == 'order_supplier' || $tmpclassname == 'supplier_order') {
2307 $tmpclassname = 'CommandeFournisseur';
2308 }
2309
2310 $classname = ucfirst($tmpclassname);
2311
2312 $this->origin_object = new $classname($this->db);
2313 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
2314 $this->origin_object->fetch($this->origin_id);
2315 }
2316
2326 public function fetchObjectFrom($table, $field, $key, $element = null)
2327 {
2328 global $conf;
2329
2330 $result = false;
2331
2332 $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
2333 $sql .= " WHERE ".$this->db->sanitize($field)." = '".$this->db->escape($key)."'";
2334 if (!empty($element)) {
2335 $sql .= " AND entity IN (".getEntity($element).")";
2336 } else {
2337 $sql .= " AND entity = ".((int) $conf->entity);
2338 }
2339
2340 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
2341 $resql = $this->db->query($sql);
2342 if ($resql) {
2343 $obj = $this->db->fetch_object($resql);
2344 // Test for avoid error -1
2345 if ($obj) {
2346 if (method_exists($this, 'fetch')) {
2347 $result = $this->fetch($obj->rowid);
2348 } else {
2349 $this->error = 'fetch() method not implemented on '.get_class($this);
2350 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2351 array_push($this->errors, $this->error);
2352 $result = -1;
2353 }
2354 }
2355 }
2356
2357 return $result;
2358 }
2359
2368 public function getValueFrom($table, $id, $field)
2369 {
2370 $result = false;
2371 if (!empty($id) && !empty($field) && !empty($table)) {
2372 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2373 dol_syslog(get_class($this).'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2374 return -1;
2375 }
2376 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2377 dol_syslog(get_class($this).'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2378 return -1;
2379 }
2380
2381 $sql = "SELECT ".$this->db->sanitize($field)." FROM ".$this->db->prefix().$this->db->sanitize($table);
2382 $sql .= " WHERE rowid = ".((int) $id);
2383
2384 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2385 $resql = $this->db->query($sql);
2386 if ($resql) {
2387 $row = $this->db->fetch_row($resql);
2388 $result = $row[0];
2389 }
2390 }
2391 return $result;
2392 }
2393
2394
2400 protected $fieldValueBeingSet = array();
2401
2423 public function setFieldValue(User $user, $fieldKey, $value, $byPassUserPermission = false)
2424 {
2425 global $langs;
2426
2427 if (!empty($this->fieldValueBeingSet[$fieldKey])) {
2428 // A side effect (onFieldValueChanged) is trying to set this same field again while it is
2429 // still being processed higher up the call stack: this would cause infinite recursion.
2430 dol_syslog(get_class($this)."::setFieldValue recursive call detected on field '".$fieldKey."', aborting to avoid infinite loop", LOG_WARNING);
2431 return false;
2432 }
2433
2434 if (!$this->isFieldDefined($fieldKey)) {
2435 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
2436 return false;
2437 }
2438
2439 if (!$this->isFieldEditAllowed($user, $fieldKey, $byPassUserPermission)) {
2440 $this->setFieldError($fieldKey, $langs->trans('FieldNotAllowedForEdit'));
2441 return false;
2442 }
2443
2444 if ($this->isFieldValidationRequired($fieldKey) && !$this->validateField($this->fields, $fieldKey, $value)) {
2445 return false;
2446 }
2447
2448 if ($this->oldcopy === null || !is_object($this->oldcopy)) {
2449 $this->oldcopy = clone $this;
2450 }
2451
2452
2453 // Property holding the value, ex: opp_status for the field fk_opp_status of a project
2454 $property = $this->getFieldPropertyName($fieldKey);
2455
2456 if (is_object($this->oldcopy) && property_exists($this, $property) && property_exists($this->oldcopy, $property)) {
2457 $this->oldcopy->$property = $this->$property;
2458 }
2459
2460 $this->fieldValueBeingSet[$fieldKey] = true;
2461
2462 // Set new value
2463 $this->$property = $value;
2464
2465 // Some deprecated/replacement property pairs (ex: statut/status, alreadypaid/totalpaid) are still
2466 // both declared as real properties on the object for backward compatibility, so PHP never triggers
2467 // DolDeprecationHandler magic methods for them (magic only fires for undefined/inaccessible properties).
2468 // We must keep such pairs manually in sync, but only the pair that actually matches $fieldKey.
2469 $deprecatedProperties = $this->deprecatedProperties();
2470 if (!empty($deprecatedProperties) && is_array($deprecatedProperties)) {
2471 foreach ($deprecatedProperties as $oldProperty => $newProperty) {
2472 if ($fieldKey === $oldProperty && property_exists($this, $newProperty)) {
2473 if (is_object($this->oldcopy) && property_exists($this->oldcopy, $newProperty) && property_exists($this->oldcopy, $oldProperty)) {
2474 $this->oldcopy->$newProperty = $this->oldcopy->$oldProperty;
2475 }
2476 $this->$newProperty = $value;
2477 } elseif ($fieldKey === $newProperty && property_exists($this, $oldProperty)) {
2478 if (is_object($this->oldcopy) && property_exists($this->oldcopy, $oldProperty) && property_exists($this->oldcopy, $newProperty)) {
2479 $this->oldcopy->$oldProperty = $this->oldcopy->$newProperty;
2480 }
2481 $this->$oldProperty = $value;
2482 }
2483 }
2484 }
2485
2486 // Let child classes recompute dependent fields (ex: TTC amount when HT amount changes on a line).
2487 // Left as a no-op by default in CommonObject, which is shared by every kind of object.
2488 $this->onFieldValueChanged($fieldKey, $value);
2489
2490 unset($this->fieldValueBeingSet[$fieldKey]);
2491
2492 return true;
2493 }
2494
2508 protected function onFieldValueChanged($fieldKey, $value)
2509 {
2510 // Nothing to do by default.
2511 }
2512
2522 protected function getFieldPropertyName($field)
2523 {
2524 return $field;
2525 }
2526
2534 public function getFieldUiValue($field)
2535 {
2536 $property = $this->getFieldPropertyName($field);
2537
2538 return property_exists($this, $property) ? $this->$property : null;
2539 }
2540
2550 protected function persistFieldValue(User $user, $field)
2551 {
2552 if ($field == 'note_public' || $field == 'note_private') {
2553 return $this->update_note((string) $this->$field, $field == 'note_public' ? '_public' : '_private');
2554 }
2555
2556 $type = $this->fields[$field]['type'];
2557 if (preg_match('/^(int|integer)\b/', $type)) {
2558 $format = 'int';
2559 } elseif (in_array($type, array('date', 'datetime', 'timestamp'))) {
2560 $format = 'date';
2561 } else {
2562 $format = 'text';
2563 }
2564 $trigkey = (property_exists($this, 'TRIGGER_PREFIX') && !empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)).'_MODIFY';
2565
2566 return $this->setValueFrom($field, $this->getFieldUiValue($field), '', null, $format, '', $user, $trigkey);
2567 }
2568
2579 public function updateFieldFromUi(User $user, $field, $value)
2580 {
2581 global $langs;
2582
2583 if (!$this->isFieldEditableFromUi($user, $field)) {
2584 $langs->load('errors');
2585 $this->error = $langs->trans('ErrorFieldIsNotEditable');
2586 $this->errors[] = $this->error;
2587 return -1;
2588 }
2589
2590 $property = $this->getFieldPropertyName($field);
2591 $oldvalue = $this->getFieldUiValue($field);
2592
2593 if (!$this->setFieldValue($user, $field, $value)) {
2594 if (empty($this->error)) {
2595 $this->error = $this->getFieldError($field);
2596 }
2597 $this->errors[] = $this->error;
2598 return -2;
2599 }
2600
2601 $result = $this->persistFieldValue($user, $field);
2602 if ($result <= 0) {
2603 // Keep the object consistent with the database
2604 $this->$property = $oldvalue;
2605 if (empty($this->error) && !empty($this->errors)) {
2606 $this->error = implode(', ', $this->errors);
2607 }
2608 return -3;
2609 }
2610
2611 return 1;
2612 }
2613
2625 public function getFieldValueFromAjaxPost($field)
2626 {
2627 $key = 'ajaxfield_'.$field;
2628 $type = $this->fields[$field]['type'];
2629
2630 if (!GETPOSTISSET($key) && !GETPOSTISSET($key.'year')) {
2631 return null;
2632 }
2633
2634 if ($type == 'html') {
2635 return dol_html_entity_decode(GETPOST($key, 'restricthtml'), ENT_QUOTES | ENT_HTML5, 'UTF-8', 1);
2636 } elseif (preg_match('/^(varchar|text)\b/', $type)) {
2637 return GETPOST($key, 'alphanohtml');
2638 } elseif (preg_match('/^(int|integer)\b/', $type)) {
2639 return GETPOSTINT($key);
2640 } elseif ($type == 'date') {
2641 // At noon like the cards, so the day does not change with the time zone
2642 return GETPOSTDATE($key, '12:00:00');
2643 } elseif (in_array($type, array('datetime', 'timestamp'))) {
2644 return GETPOSTDATE($key, 'getpost');
2645 }
2646
2647 // Other types (lists, amounts...) are not supported yet
2648 return null;
2649 }
2650
2660 public function ajaxOutputField($field)
2661 {
2662 // Fields like notes are hidden from generic forms and lists (visible = 0) but shown by their own block of the card,
2663 // so the output is forced visible: the field is already allowed by isFieldReadableFromUi().
2664 $fielddef = $this->fields[$field];
2665 $fielddef['visible'] = 1;
2666
2667 return $this->showOutputField($fielddef, $field, $this->getFieldUiValue($field));
2668 }
2669
2679 public function ajaxInputField($field)
2680 {
2681 $value = $this->getFieldUiValue($field);
2682 $htmlname = 'ajaxfield_'.$field;
2683
2684 // Same editor as the notes of the card (core/tpl/notes.tpl.php)
2685 if ($field == 'note_public' || $field == 'note_private') {
2686 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
2687 $withckeditor = isModEnabled('fckeditor') && getDolGlobalString($field == 'note_public' ? 'FCKEDITOR_ENABLE_NOTE_PUBLIC' : 'FCKEDITOR_ENABLE_NOTE_PRIVATE');
2688 $doleditor = new DolEditor($htmlname, (string) $value, '100%', 200, 'dolibarr_notes', 'In', true, false, $withckeditor, 12, '95%');
2689
2690 return (string) $doleditor->Create(1);
2691 }
2692
2693 // Fields like notes are hidden from generic forms (visible = 0), the field is already allowed by isFieldEditableFromUi()
2694 $fielddef = $this->fields[$field];
2695 $fielddef['visible'] = 1;
2696
2697 return $this->showInputField($fielddef, $field, $value, '', '', 'ajaxfield_');
2698 }
2699
2716 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2717 {
2718 global $user;
2719
2720 if (empty($table)) {
2721 $table = $this->table_element;
2722 }
2723 if (empty($id)) {
2724 $id = $this->id;
2725 }
2726 if (empty($format)) {
2727 $format = 'text';
2728 }
2729 if (empty($id_field)) {
2730 $id_field = 'rowid';
2731 }
2732
2733 $propfield = $field;
2734
2735 // Special case
2736 // TODO move special case to product class and/or create a propfield/field (table col name ) mapping key in object fields parameters ?
2737 if ($table == 'product') {
2738 if ($field == 'note_private') {
2739 $field = 'note';
2740 $propfield = 'note_private';
2741 } elseif ($field == 'status') {
2742 $field = 'tosell';
2743 $propfield = 'status';
2744 } elseif ($field == 'status_buy') {
2745 $field = 'tobuy';
2746 $propfield = 'status_buy';
2747 } elseif ($field == 'status_batch') {
2748 $field = 'tobatch';
2749 $propfield = 'status_batch';
2750 }
2751 }
2752
2753 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2754 $fk_user_field = 'fk_user_mod';
2755 }
2756 if (in_array($table, array('prelevement_bons'))) { // TODO Add a field fk_user_modif into llx_prelevement_bons
2757 $fk_user_field = '';
2758 }
2759
2760 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $table)) {
2761 dol_syslog(get_class($this).'::getValueFrom Bad table name: '.$table, LOG_WARNING);
2762 return -1;
2763 }
2764 if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $field)) {
2765 dol_syslog(get_class($this).'::getValueFrom Bad field name: '.$field, LOG_WARNING);
2766 return -1;
2767 }
2768
2769 $oldvalue = null;
2770 if ($trigkey) {
2771 $sql = "SELECT " . $this->db->sanitize($field);
2772 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($table);
2773 $sql .= " WHERE " . $this->db->sanitize($id_field) . " = " . ((int) $id);
2774
2775 $resql = $this->db->query($sql);
2776 if ($resql) {
2777 if ($obj = $this->db->fetch_object($resql)) {
2778 if ($format == 'date') {
2779 $oldvalue = $this->db->jdate($obj->$field);
2780 } else {
2781 $oldvalue = $obj->$field;
2782 }
2783 }
2784 } else {
2785 $this->error = $this->db->lasterror();
2786 return -1;
2787 }
2788 }
2789
2790 $error = 0;
2791
2792 dol_syslog(__METHOD__, LOG_DEBUG);
2793
2794 $this->db->begin();
2795
2796 $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2797
2798 if ($format == 'text') {
2799 $sql .= $this->db->sanitize($field)." = '".$this->db->escape($value)."'";
2800 } elseif ($format == 'int') {
2801 $sql .= $this->db->sanitize($field)." = ".((int) $value);
2802 } elseif ($format == 'date') {
2803 $sql .= $this->db->sanitize($field)." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2804 } elseif ($format == 'dategmt') {
2805 $sql .= $this->db->sanitize($field)." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
2806 }
2807
2808 if ($fk_user_field) {
2809 if (!empty($fuser) && is_object($fuser)) {
2810 $sql .= ", ".$this->db->sanitize($fk_user_field)." = ".((int) $fuser->id);
2811 } elseif (empty($fuser) || $fuser != 'none') {
2812 $sql .= ", ".$this->db->sanitize($fk_user_field)." = ".((int) $user->id);
2813 }
2814 }
2815
2816 $sql .= " WHERE ".$this->db->sanitize($id_field)." = ".((int) $id);
2817
2818 $resql = $this->db->query($sql);
2819 if ($resql) {
2820 if ($trigkey) {
2821 // call trigger with updated object values
2822 if (method_exists($this, 'fetch')) {
2823 $result = $this->fetch($id);
2824 } else {
2825 $result = $this->fetchCommon($id);
2826 }
2827
2828 $this->oldcopy = clone $this;
2829 if (property_exists($this->oldcopy, $field)) {
2830 $this->oldcopy->$field = $oldvalue;
2831 }
2832 if ($propfield != $field && property_exists($this->oldcopy, $propfield)) {
2833 $this->oldcopy->$propfield = $oldvalue;
2834 }
2835
2836 if (empty($this->context['actionmsgmore'])) {
2837 $this->context['actionmsgmore'] = 'Trigger called by setValueFrom';
2838 }
2839
2840 if ($result >= 0) {
2841 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2842 }
2843 if ($result < 0) {
2844 $error++;
2845 }
2846 } else {
2847 if (property_exists($this, $field)) {
2848 $this->$field = $value;
2849 }
2850 if ($propfield != $field && property_exists($this, $propfield)) {
2851 $this->$propfield = $value;
2852 }
2853 }
2854
2855 if (!$error) {
2856 $this->db->commit();
2857 return 1;
2858 } else {
2859 if (property_exists($this, $field)) {
2860 $this->$field = $oldvalue;
2861 }
2862 if ($propfield != $field && property_exists($this, $propfield)) {
2863 $this->$propfield = $oldvalue;
2864 }
2865 $this->db->rollback();
2866 return -2;
2867 }
2868 } else {
2869 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2870 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2871 } else {
2872 $this->error = $this->db->lasterror();
2873 }
2874 $this->db->rollback();
2875 return -1;
2876 }
2877 }
2878
2879 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2890 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2891 {
2892 // phpcs:enable
2893 global $conf, $user;
2894
2895 if (!$this->table_element) {
2896 dol_print_error(null, get_class($this)."::load_previous_next_ref was called on object with property table_element not defined");
2897 return -1;
2898 }
2899 if ($fieldid == 'none') {
2900 return 1;
2901 }
2902
2903 // For backward compatibility
2904 if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2905 $fieldid = 'titre';
2906 }
2907
2908 // Security on socid
2909 $socid = 0;
2910 if ($user->socid > 0) {
2911 $socid = $user->socid;
2912 }
2913
2914 // this->ismultientitymanaged contains
2915 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2916 $aliastablesociete = 's';
2917 if ($this->element == 'societe') {
2918 $aliastablesociete = 'te'; // te as table_element
2919 }
2920 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2921 // ORDER BY ... LIMIT 1 and not MAX()/MIN(): with the other conditions (entity...), MAX()/MIN() read the whole range
2922 // of the index, while ORDER BY ... LIMIT 1 stops at the first row found.
2923 $sql = "SELECT te.".$this->db->sanitize($fieldid);
2924 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2925 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2926 $tmparray = explode('@', $this->ismultientitymanaged);
2927 $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
2928 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2929 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2930 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2931 $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
2932 }
2933 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2934 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2935 }
2936 if ($fieldid == 'rowid') {
2937 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." < ".((int) $this->id);
2938 } elseif ($fieldid == 'label') {
2939 // Suppose caller is not in error @phan-suppress-next-line PhanUndeclaredProperty
2940 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." < '".$this->db->escape((string) $this->label)."'";
2941 } else { // Should be 'ref' or any other string field
2942 $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)
2943 }
2944 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2945 $sql .= " AND sc.fk_user = ".((int) $user->id);
2946 }
2947 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2948 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2949 }
2950
2951 $filtermax = $filter;
2952
2953 // Manage filter
2954 $errormessage = '';
2955 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermax, $errormessage);
2956 if ($errormessage) {
2957 if (!preg_match('/^\s*AND/i', $filtermax)) {
2958 $sql .= " AND ";
2959 }
2960 $sql .= $filtermax; // @phan-suppress-current-line SqlInjection
2961 } else {
2962 $sql .= $tmpsql;
2963 }
2964
2965 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2966 $tmparray = explode('@', $this->ismultientitymanaged);
2967 $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
2968 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2969 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2970 }
2971 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2972 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2973 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2974 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2975 } else {
2976 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2977 }
2978 } else {
2979 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2980 }
2981 }
2982 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2983 $tmparray = explode('@', $this->ismultientitymanaged);
2984 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2985 }
2986 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2987 $sql .= ' AND te.fk_soc = '.((int) $socid);
2988 }
2989 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2990 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2991 }
2992 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2993 $sql .= ' AND te.rowid = '.((int) $socid);
2994 }
2995 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2996
2997 $sql .= " ORDER BY te.".$this->db->sanitize($fieldid)." DESC";
2998 $sql .= $this->db->plimit(1);
2999
3000 $result = $this->db->query($sql);
3001 if (!$result) {
3002 $this->error = $this->db->lasterror();
3003 return -1;
3004 }
3005 $row = $this->db->fetch_row($result);
3006 $this->ref_previous = ($row ? $row[0] : null);
3007
3008 $sql = "SELECT te.".$this->db->sanitize($fieldid);
3009 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
3010 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
3011 $tmparray = explode('@', $this->ismultientitymanaged);
3012 $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
3013 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
3014 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
3015 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
3016 $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
3017 }
3018 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
3019 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
3020 }
3021 if ($fieldid == 'rowid') {
3022 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." > ".((int) $this->id);
3023 } elseif ($fieldid == 'label') {
3024 // Suppose caller is not in error @phan-suppress-next-line PhanUndeclaredProperty
3025 $sql .= " WHERE te.".$this->db->sanitize($fieldid)." > '".$this->db->escape((string) $this->label)."'";
3026 } else { // Should be 'ref' or any other string field
3027 $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)
3028 }
3029 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
3030 $sql .= " AND (sc.fk_user = ".((int) $user->id);
3031 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
3032 $userschilds = $user->getAllChildIds();
3033 $sql .= " OR sc.fk_user IN (".$this->db->sanitize(implode(',', $userschilds)).")";
3034 }
3035 $sql .= ')';
3036 }
3037 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
3038 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
3039 }
3040
3041 $filtermin = $filter;
3042
3043 // Manage filter
3044 $errormessage = '';
3045 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermin, $errormessage);
3046 if ($errormessage) {
3047 if (!preg_match('/^\s*AND/i', $filtermin)) {
3048 $sql .= " AND ";
3049 }
3050 $sql .= $filtermin; // @phan-suppress-current-line SqlInjection
3051
3052 $filtermin = '';
3053 } else {
3054 $sql .= $tmpsql;
3055 }
3056
3057 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
3058 $tmparray = explode('@', $this->ismultientitymanaged);
3059 $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
3060 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
3061 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
3062 }
3063 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
3064 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
3065 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
3066 $sql .= " AND te.entity IS NOT NULL"; // Show all users
3067 } else {
3068 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
3069 }
3070 } else {
3071 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
3072 }
3073 }
3074 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
3075 $tmparray = explode('@', $this->ismultientitymanaged);
3076 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
3077 }
3078 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
3079 $sql .= ' AND te.fk_soc = '.((int) $socid);
3080 }
3081 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
3082 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
3083 }
3084 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
3085 $sql .= ' AND te.rowid = '.((int) $socid);
3086 }
3087 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
3088 // 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
3089
3090 $sql .= " ORDER BY te.".$this->db->sanitize($fieldid)." ASC";
3091 $sql .= $this->db->plimit(1);
3092
3093 $result = $this->db->query($sql);
3094 if (!$result) {
3095 $this->error = $this->db->lasterror();
3096 return -2;
3097 }
3098 $row = $this->db->fetch_row($result);
3099 $this->ref_next = ($row ? $row[0] : null);
3100
3101 return 1;
3102 }
3103
3104
3112 public function getListContactId($source = 'external')
3113 {
3114 $contactAlreadySelected = array();
3115 $tab = $this->liste_contact(-1, $source);
3116 $num = count($tab);
3117 $i = 0;
3118 while ($i < $num) {
3119 if ($source == 'thirdparty') {
3120 $contactAlreadySelected[$i] = $tab[$i]['socid'];
3121 } else {
3122 $contactAlreadySelected[$i] = $tab[$i]['id'];
3123 }
3124 $i++;
3125 }
3126 return $contactAlreadySelected;
3127 }
3128
3129
3137 public function setProject($projectid, $notrigger = 0)
3138 {
3139 global $user;
3140 $error = 0;
3141
3142 if (!$this->table_element) {
3143 dol_syslog(get_class($this)."::setProject was called on object with property table_element not defined", LOG_ERR);
3144 return -1;
3145 }
3146
3147 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3148 if ($this->table_element == 'actioncomm') { // Special case for actioncomm
3149 if ($projectid) {
3150 $sql .= " SET fk_project = ".((int) $projectid);
3151 } else {
3152 $sql .= " SET fk_project = NULL";
3153 }
3154 $sql .= ' WHERE id = '.((int) $this->id);
3155 // @phan-suppress-next-line PhanTypeMismatchProperty
3156 } elseif (!empty($this->fields['fk_project'])) { // Common case
3157 if ($projectid) {
3158 $sql .= " SET fk_project = ".((int) $projectid);
3159 } else {
3160 $sql .= " SET fk_project = NULL";
3161 }
3162 $sql .= ' WHERE rowid = '.((int) $this->id);
3163 } else { // Special case for old architecture objects
3164 if ($projectid) {
3165 $sql .= ' SET fk_projet = '.((int) $projectid);
3166 } else {
3167 $sql .= ' SET fk_projet = NULL';
3168 }
3169 $sql .= " WHERE rowid = ".((int) $this->id);
3170 }
3171
3172 $this->db->begin();
3173
3174 dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
3175 if ($this->db->query($sql)) {
3176 $this->fk_project = ((int) $projectid);
3177 } else {
3178 dol_print_error($this->db);
3179 $error++;
3180 }
3181
3182 // Triggers
3183 if (!$error && !$notrigger) {
3184 // Call triggers
3185 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
3186 if ($result < 0) {
3187 $error++;
3188 } //Do also here what you must do to rollback action if trigger fail
3189 // End call triggers
3190 }
3191
3192 // Commit or rollback
3193 if ($error) {
3194 $this->db->rollback();
3195 return -1;
3196 } else {
3197 $this->db->commit();
3198 return 1;
3199 }
3200 }
3201
3209 public function setPaymentMethods($id)
3210 {
3211 global $user;
3212
3213 $error = 0;
3214 $notrigger = 0;
3215
3216 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
3217
3218 if ($this->status >= 0 || $this->element == 'societe') {
3219 $this->oldcopy = dol_clone($this, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
3220
3221 // TODO uniformize field name
3222 $fieldname = 'fk_mode_reglement';
3223 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3224 if ($this->element == 'societe') {
3225 $fieldname = 'mode_reglement';
3226 $triggerName = 'COMPANY';
3227 }
3228 if (get_class($this) == 'Facture') {
3229 $triggerName = 'BILL';
3230 }
3231 if (get_class($this) == 'Fournisseur') {
3232 $fieldname = 'mode_reglement_supplier';
3233 $triggerName = 'BILL_SUPPLIER';
3234 }
3235 if (get_class($this) == 'Tva') {
3236 $fieldname = 'fk_typepayment';
3237 $triggerName = 'VAT';
3238 }
3239 if (get_class($this) == 'Salary') {
3240 $fieldname = 'fk_typepayment';
3241 }
3242
3243 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3244 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3245 $sql .= ' WHERE rowid = '.((int) $this->id);
3246
3247 if ($this->db->query($sql)) {
3248 $this->mode_reglement_id = $id;
3249 // for supplier
3250 if (get_class($this) == 'Fournisseur') {
3251 $this->mode_reglement_supplier_id = $id;
3252 }
3253
3254 // Triggers
3255 if (!$error && !$notrigger) {
3256 // Call triggers
3257 $result = $this->call_trigger($triggerName.'_MODIFY', $user);
3258 if ($result < 0) {
3259 $error++;
3260 }
3261 // End call triggers
3262 }
3263 return 1;
3264 } else {
3265 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
3266 $this->error = $this->db->error();
3267 return -1;
3268 }
3269 } else {
3270 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
3271 $this->error = 'Status of the object is incompatible '.$this->status;
3272 return -2;
3273 }
3274 }
3275
3282 public function setMulticurrencyCode($code)
3283 {
3284 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
3285 if ($this->status >= 0 || $this->element == 'societe') {
3286 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3287 $sql .= " SET multicurrency_code = '".$this->db->escape($code)."'";
3288 $sql .= ' WHERE rowid='.((int) $this->id);
3289
3290 if ($this->db->query($sql)) {
3291 $this->multicurrency_code = $code;
3292
3293 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
3294 if ($rate) {
3295 $this->setMulticurrencyRate($rate, 2);
3296 }
3297
3298 return 1;
3299 } else {
3300 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
3301 $this->error = $this->db->error();
3302 return -1;
3303 }
3304 } else {
3305 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
3306 $this->error = 'Status of the object is incompatible '.$this->status;
3307 return -2;
3308 }
3309 }
3310
3318 public function setMulticurrencyRate($rate, $mode = 1)
3319 {
3320 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.', '.$mode.')');
3321 if ($this->status >= 0 || $this->element == 'societe') {
3322 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3323 $sql .= " SET multicurrency_tx = ".((float) $rate);
3324 $sql .= ' WHERE rowid='.((int) $this->id);
3325
3326 if ($this->db->query($sql)) {
3327 $this->multicurrency_tx = $rate;
3328
3329 // Update line price
3330 if (!empty($this->lines)) {
3331 foreach ($this->lines as &$line) {
3332 // A credit line (deposit, credit note, discount applied to the invoice) is not priced at the invoice rate:
3333 // both its amounts are the historical ones of the credit, so a rate change must leave it untouched.
3334 if (!empty($line->fk_remise_except)) {
3335 continue;
3336 }
3337
3338 // Amounts in company currency will be recalculated
3339 if ($mode == 1) {
3340 $line->subprice = 0;
3341 }
3342
3343 // Amounts in foreign currency will be recalculated
3344 if ($mode == 2) {
3345 $line->multicurrency_subprice = 0;
3346 }
3347
3348 switch ($this->element) {
3349 case 'propal':
3350 if ($this instanceof Propal) {
3352 '@phan-var-force PropaleLigne $line';
3353 $this->updateline(
3354 $line->id,
3355 $line->subprice,
3356 $line->qty,
3357 $line->remise_percent,
3358 $line->tva_tx,
3359 $line->localtax1_tx,
3360 $line->localtax2_tx,
3361 ($line->description ? $line->description : $line->desc),
3362 'HT',
3363 $line->info_bits,
3364 $line->special_code,
3365 $line->fk_parent_line,
3366 $line->skip_update_total,
3367 $line->fk_fournprice,
3368 $line->pa_ht,
3369 $line->label,
3370 $line->product_type,
3371 $line->date_start,
3372 $line->date_end,
3373 $line->array_options,
3374 $line->fk_unit,
3375 $line->multicurrency_subprice
3376 );
3377 }
3378 break;
3379 case 'commande':
3380 if ($this instanceof Commande) {
3382 '@phan-var-force OrderLine $line';
3383 $this->updateline(
3384 $line->id,
3385 ($line->description ? $line->description : $line->desc),
3386 $line->subprice,
3387 $line->qty,
3388 $line->remise_percent,
3389 $line->tva_tx,
3390 $line->localtax1_tx,
3391 $line->localtax2_tx,
3392 'HT',
3393 $line->info_bits,
3394 $line->date_start,
3395 $line->date_end,
3396 $line->product_type,
3397 $line->fk_parent_line,
3398 $line->skip_update_total,
3399 $line->fk_fournprice,
3400 $line->pa_ht,
3401 $line->label,
3402 $line->special_code,
3403 $line->array_options,
3404 $line->fk_unit,
3405 $line->multicurrency_subprice
3406 );
3407 }
3408 break;
3409 case 'facture':
3410 if ($this instanceof Facture) {
3412 '@phan-var-force FactureLigne $line';
3413 $this->updateline(
3414 $line->id,
3415 ($line->description ? $line->description : $line->desc),
3416 $line->subprice,
3417 $line->qty,
3418 $line->remise_percent,
3419 $line->date_start,
3420 $line->date_end,
3421 $line->tva_tx,
3422 $line->localtax1_tx,
3423 $line->localtax2_tx,
3424 'HT',
3425 $line->info_bits,
3426 $line->product_type,
3427 $line->fk_parent_line,
3428 $line->skip_update_total,
3429 $line->fk_fournprice,
3430 $line->pa_ht,
3431 $line->label,
3432 $line->special_code,
3433 $line->array_options,
3434 $line->situation_percent,
3435 $line->fk_unit,
3436 $line->multicurrency_subprice
3437 );
3438 }
3439 break;
3440 case 'facturerec':
3441 if ($this instanceof FactureRec) {
3443 '@phan-var-force FactureLigneRec $line';
3444 $this->updateline(
3445 $line->id,
3446 ($line->description ? $line->description : $line->desc),
3447 $line->subprice,
3448 $line->qty,
3449 $line->tva_tx,
3450 $line->localtax1_tx,
3451 $line->localtax2_tx,
3452 $line->fk_product,
3453 $line->remise_percent,
3454 'HT',
3455 $line->info_bits,
3456 0,
3457 0,
3458 $line->product_type,
3459 $line->rang,
3460 $line->special_code,
3461 $line->label,
3462 $line->fk_unit,
3463 $line->multicurrency_subprice,
3464 0,
3465 $line->date_start, // Ignore real issue with FactureLigneRec @phan-suppress-current-line PhanUndeclaredProperty
3466 $line->date_end, // Ignore real issue with FactureLigneRec @phan-suppress-current-line PhanUndeclaredProperty
3467 $line->fk_fournprice,
3468 $line->pa_ht,
3469 $line->fk_parent_line
3470 );
3471 }
3472 break;
3473 case 'supplier_proposal':
3474 if ($this instanceof SupplierProposal) {
3476 '@phan-var-force SupplierProposalLine $line';
3477 $this->updateline(
3478 $line->id,
3479 $line->subprice,
3480 $line->qty,
3481 $line->remise_percent,
3482 $line->tva_tx,
3483 $line->localtax1_tx,
3484 $line->localtax2_tx,
3485 ($line->description ? $line->description : $line->desc),
3486 'HT',
3487 $line->info_bits,
3488 $line->special_code,
3489 $line->fk_parent_line,
3490 $line->skip_update_total,
3491 $line->fk_fournprice,
3492 $line->pa_ht,
3493 $line->label,
3494 $line->product_type,
3495 $line->array_options,
3496 $line->ref_fourn,
3497 (int) $line->fk_unit,
3498 $line->multicurrency_subprice
3499 );
3500 }
3501 break;
3502 case 'order_supplier':
3504 '@phan-var-force CommandeFournisseur $this';
3505 '@phan-var-force CommandeFournisseurLigne $line';
3506 $this->updateline(
3507 $line->id,
3508 ($line->description ? $line->description : $line->desc),
3509 $line->subprice,
3510 $line->qty,
3511 $line->remise_percent,
3512 $line->tva_tx,
3513 $line->localtax1_tx,
3514 $line->localtax2_tx,
3515 'HT',
3516 $line->info_bits,
3517 $line->product_type,
3518 0,
3519 $line->date_start,
3520 $line->date_end,
3521 $line->array_options,
3522 $line->fk_unit,
3523 $line->multicurrency_subprice,
3524 $line->ref_supplier
3525 );
3526 break;
3527 case 'invoice_supplier':
3529 '@phan-var-force FactureFournisseur $this';
3530 '@phan-var-force SupplierInvoiceLIne $line';
3531 $this->updateline(
3532 $line->id,
3533 ($line->description ? $line->description : $line->desc),
3534 $line->subprice,
3535 $line->tva_tx,
3536 $line->localtax1_tx,
3537 $line->localtax2_tx,
3538 $line->qty,
3539 0,
3540 'HT',
3541 $line->info_bits,
3542 $line->product_type,
3543 $line->remise_percent,
3544 0,
3545 $line->date_start,
3546 $line->date_end,
3547 $line->array_options,
3548 $line->fk_unit,
3549 $line->multicurrency_subprice,
3550 $line->ref_supplier
3551 );
3552 break;
3553 default:
3554 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
3555 break;
3556 }
3557 }
3558 }
3559
3560 return 1;
3561 } else {
3562 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
3563 $this->error = $this->db->error();
3564 return -1;
3565 }
3566 } else {
3567 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
3568 $this->error = 'Status of the object is incompatible '.$this->status;
3569 return -2;
3570 }
3571 }
3572
3580 public function setPaymentTerms($id, $deposit_percent = null)
3581 {
3582 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.formatLogObject($deposit_percent).')');
3583 if ($this->status >= 0 || $this->element == 'societe') {
3584 // TODO uniformize field name
3585 $fieldname = 'fk_cond_reglement';
3586 if ($this->element == 'societe') {
3587 $fieldname = 'cond_reglement';
3588 }
3589 if (get_class($this) == 'Fournisseur') {
3590 $fieldname = 'cond_reglement_supplier';
3591 }
3592
3593 if (empty($deposit_percent) || $deposit_percent < 0) {
3594 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
3595 }
3596
3597 if ($deposit_percent > 100) {
3598 $deposit_percent = 100;
3599 }
3600
3601 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3602 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3603 if (in_array($this->table_element, array('propal', 'commande', 'supplier_proposal', 'commande_fournisseur', 'societe'))) {
3604 $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape((string) $deposit_percent)."'");
3605 }
3606 $sql .= ' WHERE rowid = '.((int) $this->id);
3607
3608 if ($this->db->query($sql)) {
3609 $this->cond_reglement_id = $id;
3610 // for supplier
3611 if (get_class($this) == 'Fournisseur') {
3612 $this->cond_reglement_supplier_id = $id;
3613 }
3614 $this->deposit_percent = $deposit_percent;
3615 return 1;
3616 } else {
3617 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
3618 $this->error = $this->db->error();
3619 return -1;
3620 }
3621 } else {
3622 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
3623 $this->error = 'Status of the object is incompatible '.$this->status;
3624 return -2;
3625 }
3626 }
3627
3634 public function setTransportMode($id)
3635 {
3636 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
3637 if ($this->status >= 0 || $this->element == 'societe') {
3638 $fieldname = 'fk_transport_mode';
3639 if ($this->element == 'societe') {
3640 $fieldname = 'transport_mode';
3641 }
3642 if (get_class($this) == 'Fournisseur') {
3643 $fieldname = 'transport_mode_supplier';
3644 }
3645
3646 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3647 $sql .= " SET ".$this->db->sanitize($fieldname)." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3648 $sql .= ' WHERE rowid='.((int) $this->id);
3649
3650 if ($this->db->query($sql)) {
3651 $this->transport_mode_id = $id;
3652 // for supplier
3653 if (get_class($this) == 'Fournisseur') {
3654 $this->transport_mode_supplier_id = $id;
3655 }
3656 return 1;
3657 } else {
3658 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
3659 $this->error = $this->db->error();
3660 return -1;
3661 }
3662 } else {
3663 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
3664 $this->error = 'Status of the object is incompatible '.$this->status;
3665 return -2;
3666 }
3667 }
3668
3676 public function setDeliveryAddress($id)
3677 {
3678 $fieldname = 'fk_delivery_address';
3679 if ($this->element == 'delivery' || $this->element == 'shipping') {
3680 $fieldname = 'fk_address';
3681 }
3682
3683 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$this->db->sanitize($fieldname)." = ".((int) $id);
3684 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
3685
3686 if ($this->db->query($sql)) {
3687 $this->fk_delivery_address = $id;
3688 return 1;
3689 } else {
3690 $this->error = $this->db->error();
3691 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
3692 return -1;
3693 }
3694 }
3695
3696
3705 public function setShippingMethod($shipping_method_id, $notrigger = 0, $userused = null)
3706 {
3707 global $user;
3708
3709 if (empty($userused)) {
3710 $userused = $user;
3711 }
3712
3713 $error = 0;
3714
3715 if (!$this->table_element) {
3716 dol_syslog(get_class($this)."::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3717 return -1;
3718 }
3719
3720 $this->db->begin();
3721
3722 if ($shipping_method_id < 0) {
3723 $shipping_method_id = 'NULL';
3724 }
3725 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
3726
3727 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3728 $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
3729 $sql .= " WHERE rowid=".((int) $this->id);
3730 $resql = $this->db->query($sql);
3731 if (!$resql) {
3732 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
3733 $this->error = $this->db->lasterror();
3734 $error++;
3735 } else {
3736 if (!$notrigger) {
3737 // Call trigger
3738 $this->context = array('shippingmethodupdate' => 1);
3739 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3740 $result = $this->call_trigger($triggerPrefix.'_MODIFY', $userused);
3741 if ($result < 0) {
3742 $error++;
3743 }
3744 // End call trigger
3745 }
3746 }
3747 if ($error) {
3748 $this->db->rollback();
3749 return -1;
3750 } else {
3751 $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id;
3752 $this->db->commit();
3753 return 1;
3754 }
3755 }
3756
3757
3764 public function setWarehouse($warehouse_id)
3765 {
3766 if (!$this->table_element) {
3767 dol_syslog(get_class($this)."::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3768 return -1;
3769 }
3770 if ($warehouse_id < 0) {
3771 $warehouse_id = 'NULL';
3772 }
3773 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
3774
3775 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3776 $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
3777 $sql .= " WHERE rowid=".((int) $this->id);
3778
3779 if ($this->db->query($sql)) {
3780 $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id;
3781 return 1;
3782 } else {
3783 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
3784 $this->error = $this->db->error();
3785 return 0;
3786 }
3787 }
3788
3789
3797 public function setDocModel($user, $modelpdf)
3798 {
3799 if (!$this->table_element) {
3800 dol_syslog(get_class($this)."::setDocModel was called on object with property table_element not defined", LOG_ERR);
3801 return -1;
3802 }
3803
3804 $newmodelpdf = dol_trunc($modelpdf, 255);
3805
3806 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3807 $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
3808 $sql .= " WHERE rowid = ".((int) $this->id);
3809
3810 dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
3811 $resql = $this->db->query($sql);
3812 if ($resql) {
3813 $this->model_pdf = $modelpdf;
3814 return 1;
3815 } else {
3816 dol_print_error($this->db);
3817 return 0;
3818 }
3819 }
3820
3821
3830 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
3831 {
3832 global $user;
3833
3834 if (empty($userused)) {
3835 $userused = $user;
3836 }
3837
3838 $error = 0;
3839
3840 if (!$this->table_element) {
3841 dol_syslog(get_class($this)."::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3842 return -1;
3843 }
3844 $this->db->begin();
3845
3846 if ($fk_account < 0) {
3847 $fk_account = 'NULL';
3848 }
3849 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3850
3851 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3852 $sql .= " SET fk_account = ".((int) $fk_account);
3853 $sql .= " WHERE rowid=".((int) $this->id);
3854
3855 $resql = $this->db->query($sql);
3856 if (!$resql) {
3857 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3858 $this->error = $this->db->lasterror();
3859 $error++;
3860 } else {
3861 if (!$notrigger) {
3862 // Call trigger
3863 $this->context['bankaccountupdate'] = 1;
3864
3865 $triggerName = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
3866 $result = $this->call_trigger($triggerName . '_MODIFY', $userused);
3867 if ($result < 0) {
3868 $error++;
3869 }
3870 // End call trigger
3871 }
3872 }
3873 if ($error) {
3874 $this->db->rollback();
3875 return -1;
3876 } else {
3877 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
3878 $this->db->commit();
3879 return 1;
3880 }
3881 }
3882
3883
3884 // TODO: Move line related operations to CommonObjectLine?
3885
3886 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3896 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3897 {
3898 // phpcs:enable
3899 if (!$this->table_element_line) {
3900 dol_syslog(get_class($this)."::line_order was called on object with property table_element_line not defined", LOG_ERR);
3901 return -1;
3902 }
3903 if (!$this->fk_element) {
3904 dol_syslog(get_class($this)."::line_order was called on object with property fk_element not defined", LOG_ERR);
3905 return -1;
3906 }
3907
3908 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3909 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3910 $fieldposition = 'position';
3911 }
3912
3913 // Count number of lines to reorder (according to choice $renum)
3914 $nl = 0;
3915 $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3916 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3917 if (!$renum) {
3918 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = 0";
3919 }
3920 if ($renum) {
3921 $sql .= " AND " . $this->db->sanitize($fieldposition) . " <> 0";
3922 }
3923
3924 dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3925 $resql = $this->db->query($sql);
3926 if ($resql) {
3927 $row = $this->db->fetch_row($resql);
3928 $nl = $row[0];
3929 } else {
3930 dol_print_error($this->db);
3931 }
3932 if ($nl > 0) {
3933 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3934 $rows = array();
3935
3936 // We first search all lines that are parent lines (for multilevel details lines)
3937 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3938 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3939 if ($fk_parent_line) {
3940 $sql .= ' AND fk_parent_line IS NULL';
3941 }
3942 $sql .= " ORDER BY " . $this->db->sanitize($fieldposition) . " ASC, rowid " . $this->db->sanitize($rowidorder);
3943
3944 dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3945 $resql = $this->db->query($sql);
3946 if ($resql) {
3947 $i = 0;
3948 $num = $this->db->num_rows($resql);
3949 $grandchild = getDolGlobalInt('MAIN_CARE_GRANDCHILD');
3950 while ($i < $num) {
3951 $row = $this->db->fetch_row($resql);
3952 $rows[] = $row[0]; // Add parent line into array rows
3953 if ($fk_parent_line) {
3954 $children = $this->getChildrenOfLine($row[0], $grandchild);
3955 }
3956 if (!empty($children)) {
3957 foreach ($children as $child) {
3958 array_push($rows, $child);
3959 }
3960 }
3961 $i++;
3962 }
3963
3964 // Now we set a new number for each lines (parent and children with children included into parent tree)
3965 if (!empty($rows)) {
3966 foreach ($rows as $key => $row) {
3967 $this->updateRangOfLine($row, ($key + 1));
3968 }
3969 }
3970 } else {
3971 dol_print_error($this->db);
3972 }
3973 }
3974 return 1;
3975 }
3976
3984 public function getChildrenOfLine($id, $includealltree = 0)
3985 {
3986 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3987 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3988 $fieldposition = 'position';
3989 }
3990
3991 $rows = array();
3992
3993 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
3994 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
3995 $sql .= ' AND fk_parent_line = '.((int) $id);
3996 $sql .= " ORDER BY " . $this->db->sanitize($fieldposition) . " ASC";
3997
3998 dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3999
4000 $resql = $this->db->query($sql);
4001 if (!$resql || $this->db->num_rows($resql) <= 0) {
4002 return array();
4003 }
4004
4005 while ($row = $this->db->fetch_row($resql)) {
4006 $rows[] = $row[0];
4007 if (!empty($includealltree) && $includealltree <= 1000) { // Test <= 1000 is a protection in depth of recursive call to avoid infinite loop
4008 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree + 1));
4009 }
4010 }
4011 return $rows;
4012 }
4013
4014 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4022 public function line_up($rowid, $fk_parent_line = true)
4023 {
4024 // phpcs:enable
4025 $this->line_order(false, 'ASC', $fk_parent_line);
4026
4027 // Get rang of line
4028 $rang = $this->getRangOfLine($rowid);
4029
4030 // Update position of line
4031 $this->updateLineUp($rowid, $rang);
4032 }
4033
4034 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4042 public function line_down($rowid, $fk_parent_line = true)
4043 {
4044 // phpcs:enable
4045 $this->line_order(false, 'ASC', $fk_parent_line);
4046
4047 // Get rang of line
4048 $rang = $this->getRangOfLine($rowid);
4049
4050 // Get max value for rang
4051 $max = $this->line_max();
4052
4053 // Update position of line
4054 $this->updateLineDown($rowid, $rang, $max);
4055 }
4056
4064 public function updateRangOfLine($rowid, $rang)
4065 {
4066 global $hookmanager;
4067 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
4068 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
4069 $fieldposition = 'position';
4070 }
4071
4072 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldposition)." = ".((int) $rang);
4073 $sql .= ' WHERE rowid = '.((int) $rowid);
4074 if ($this->id > 0 && !empty($this->fk_element)) {
4075 // The line must belong to the object we reorder lines of
4076 $sql .= " AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4077 }
4078
4079 dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
4080 if (!$this->db->query($sql)) {
4081 dol_print_error($this->db);
4082 return -1;
4083 }
4084
4085 $parameters = array('rowid' => $rowid, 'rang' => $rang, 'fieldposition' => $fieldposition);
4086 $action = '';
4087 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
4088 return 1;
4089 }
4090
4091 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4098 public function line_ajaxorder($rows)
4099 {
4100 // phpcs:enable
4101 $num = count($rows);
4102 for ($i = 0; $i < $num; $i++) {
4103 $this->updateRangOfLine($rows[$i], ($i + 1));
4104 }
4105 }
4106
4114 public function updateLineUp($rowid, $rang)
4115 {
4116 if ($rang <= 1) {
4117 return -1;
4118 }
4119
4120 $fieldposition = 'rang';
4121 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
4122 $fieldposition = 'position';
4123 }
4124
4125 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line)." SET ".$this->db->sanitize($fieldposition)." = ".((int) $rang);
4126 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4127 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = " . ((int) ($rang - 1));
4128 if (!$this->db->query($sql)) {
4129 $this->error = $this->db->lasterror();
4130 return -1;
4131 }
4132
4133 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldposition)." = ".((int) ($rang - 1));
4134 $sql .= ' WHERE rowid = '.((int) $rowid);
4135 if (!$this->db->query($sql)) {
4136 $this->error = $this->db->lasterror();
4137 return -1;
4138 }
4139
4140 return 1;
4141 }
4142
4151 public function updateLineDown($rowid, $rang, $max)
4152 {
4153 if ($rang >= $max) {
4154 return -1;
4155 }
4156
4157 $fieldposition = 'rang';
4158 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
4159 $fieldposition = 'position';
4160 }
4161
4162 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element_line)." SET ".$this->db->sanitize($fieldposition)." = ".((int) $rang);
4163 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4164 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = " . ((int) ($rang + 1));
4165 if (!$this->db->query($sql)) {
4166 $this->error = $this->db->lasterror();
4167 return -1;
4168 }
4169
4170 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$this->db->sanitize($fieldposition)." = ".((int) ($rang + 1));
4171 $sql .= ' WHERE rowid = '.((int) $rowid);
4172 if (!$this->db->query($sql)) {
4173 $this->error = $this->db->lasterror();
4174 return -1;
4175 }
4176
4177 return 1;
4178 }
4179
4186 public function getRangOfLine($rowid)
4187 {
4188 $fieldposition = 'rang';
4189 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
4190 $fieldposition = 'position';
4191 }
4192
4193 $sql = "SELECT " . $this->db->sanitize($fieldposition) . " FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4194 $sql .= " WHERE rowid = ".((int) $rowid);
4195
4196 dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
4197 $resql = $this->db->query($sql);
4198 if (!$resql) {
4199 return 0;
4200 }
4201
4202 $row = $this->db->fetch_row($resql);
4203 return $row[0];
4204 }
4205
4212 public function getIdOfLine($rang)
4213 {
4214 $fieldposition = 'rang';
4215 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
4216 $fieldposition = 'position';
4217 }
4218
4219 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4220 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4221 $sql .= " AND " . $this->db->sanitize($fieldposition) . " = ".((int) $rang);
4222 $resql = $this->db->query($sql);
4223 if (!$resql) {
4224 return 0;
4225 }
4226
4227 $row = $this->db->fetch_row($resql);
4228 return $row[0];
4229 }
4230
4240 public function roundQtyToPackaging($qty, $packaging)
4241 {
4242 if (empty($packaging) || !is_numeric($packaging) || (float) $packaging <= 0) {
4243 return $qty;
4244 }
4245 $sign = ((float) $qty < 0 ? -1 : 1);
4246 $absqty = abs((float) $qty);
4247 if ($absqty < (float) $packaging) {
4248 return $sign * (float) $packaging;
4249 }
4250 if ((float) price2num(fmod($absqty, (float) $packaging), 'MS')) {
4251 $coeff = intval($absqty / (float) $packaging) + 1;
4252 return $sign * (float) price2num((float) $packaging * $coeff, 'MS');
4253 }
4254 return $qty;
4255 }
4256
4257 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4264 public function line_max($fk_parent_line = 0)
4265 {
4266 // phpcs:enable
4267 $positionfield = 'rang';
4268 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
4269 $positionfield = 'position';
4270 }
4271
4272 $sql = "SELECT max(".$this->db->sanitize($positionfield).") FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4273 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4274
4275 // Search the last rang with fk_parent_line
4276 if ($fk_parent_line) {
4277 $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
4278 }
4279
4280 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
4281 $resql = $this->db->query($sql);
4282 if ($resql) {
4283 $row = $this->db->fetch_row($resql);
4284
4285 if ($fk_parent_line) {
4286 if (!empty($row[0])) {
4287 return $row[0];
4288 } else {
4289 return $this->getRangOfLine($fk_parent_line);
4290 }
4291 } else {
4292 return $row[0];
4293 }
4294 }
4295
4296 return 0;
4297 }
4298
4299 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4306 public function update_ref_ext($ref_ext)
4307 {
4308 // phpcs:enable
4309 if (!$this->table_element) {
4310 dol_syslog(get_class($this)."::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
4311 return -1;
4312 }
4313
4314 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4315 $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
4316 // @phan-suppress-next-line PhanUndeclaredProperty
4317 $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
4318
4319 dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
4320 if ($this->db->query($sql)) {
4321 $this->ref_ext = $ref_ext;
4322 return 1;
4323 } else {
4324 $this->error = $this->db->error();
4325 return -1;
4326 }
4327 }
4328
4329 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4338 public function update_note($note, $suffix = '', $notrigger = 0)
4339 {
4340 // phpcs:enable
4341 global $user;
4342
4343 if (!$this->table_element) {
4344 $this->error = 'update_note was called on object with property table_element not defined';
4345 dol_syslog(get_class($this)."::update_note was called on object with property table_element not defined", LOG_ERR);
4346 return -1;
4347 }
4348 if (!in_array($suffix, array('', '_public', '_private'))) {
4349 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
4350 dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
4351 return -2;
4352 }
4353
4354 $newsuffix = $suffix;
4355
4356 // Special case
4357 if ($this->table_element == 'product' && $newsuffix == '_private') {
4358 $newsuffix = '';
4359 }
4360 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
4361 $fieldusermod = "fk_user_mod";
4362 } elseif ($this->table_element == 'ecm_files') {
4363 $fieldusermod = "fk_user_m";
4364 } else {
4365 $fieldusermod = "fk_user_modif";
4366 }
4367 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
4368 $sql .= " SET note".$this->db->sanitize($newsuffix)." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
4369 $sql .= ", ".$this->db->sanitize($fieldusermod)." = ".((int) $user->id);
4370 $sql .= " WHERE rowid = ".((int) $this->id);
4371
4372 dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
4373 if ($this->db->query($sql)) {
4374 if ($suffix == '_public') {
4375 $this->note_public = $note;
4376 } elseif ($suffix == '_private') {
4377 $this->note_private = $note;
4378 } else {
4379 $this->note = $note; // deprecated
4380 $this->note_private = $note;
4381 }
4382 if (empty($notrigger)) {
4383 // TODO Use the $this->TRIGGER_PREFIX when implemented
4384 switch ($this->element) {
4385 case 'societe':
4386 $triggerName = 'COMPANY_MODIFY';
4387 break;
4388 case 'facture':
4389 $triggerName = 'BILL_MODIFY';
4390 break;
4391 case 'invoice_supplier':
4392 $triggerName = 'BILL_SUPPLIER_MODIFY';
4393 break;
4394 case 'facturerec':
4395 $triggerName = 'BILLREC_MODIFIY';
4396 break;
4397 case 'expensereport':
4398 $triggerName = 'EXPENSE_REPORT_MODIFY';
4399 break;
4400 default:
4401 $triggerName = (!empty($this->TRIGGER_PREFIX) ? $this->TRIGGER_PREFIX : strtoupper($this->element)) . '_MODIFY';
4402 }
4403 $ret = $this->call_trigger($triggerName, $user);
4404 if ($ret < 0) {
4405 return -1;
4406 }
4407 }
4408 return 1;
4409 } else {
4410 $this->error = $this->db->lasterror();
4411 return -1;
4412 }
4413 }
4414
4415 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4424 public function update_note_public($note)
4425 {
4426 // phpcs:enable
4427 return $this->update_note($note, '_public');
4428 }
4429
4430 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4441 public function update_price($exclspec = 0, $roundingadjust = 'auto', $nodatabaseupdate = 0, $seller = null)
4442 {
4443 // phpcs:enable
4444 global $conf, $hookmanager, $action;
4445
4446 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
4447 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4448 if ($reshook > 0) {
4449 return 1; // replacement code
4450 } elseif ($reshook < 0) {
4451 return -1; // failure
4452 } // reshook = 0 => execute normal code
4453
4454 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
4455 $isElementForSupplier = false;
4456 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND'; // const for customer by default
4457 $MODULE = "";
4458 if ($this->element == 'propal') {
4459 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
4460 } elseif ($this->element == 'commande' || $this->element == 'order') {
4461 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
4462 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
4463 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
4464 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
4465 $isElementForSupplier = true;
4466 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
4467 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
4468 $isElementForSupplier = true;
4469 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
4470 } elseif ($this->element == 'supplier_proposal') {
4471 $isElementForSupplier = true;
4472 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
4473 }
4474 if ($isElementForSupplier) {
4475 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER'; // const for supplier
4476 }
4477
4478 if (!empty($MODULE)) {
4479 if (getDolGlobalString($MODULE)) {
4480 $modsactivated = explode(',', getDolGlobalString($MODULE));
4481 foreach ($modsactivated as $mod) {
4482 if (isModEnabled($mod)) {
4483 return 1; // update was disabled by specific setup
4484 }
4485 }
4486 }
4487 }
4488
4489 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
4490
4491 $forcedroundingmode = $roundingadjust;
4492 if ($forcedroundingmode == 'auto' && isset($conf->global->{$roundTotalConstName})) {
4493 $forcedroundingmode = getDolGlobalString($roundTotalConstName);
4494 } elseif ($forcedroundingmode == 'auto') {
4495 $forcedroundingmode = '0';
4496 }
4497
4498 $error = 0;
4499
4500 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
4501
4502 // Define constants to find lines to sum (field name into the table_element_line not into table_element)
4503 $fieldtva = 'total_tva';
4504 $fieldlocaltax1 = 'total_localtax1';
4505 $fieldlocaltax2 = 'total_localtax2';
4506 $fieldup = 'subprice';
4507 $base_price_type = 'HT';
4508 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
4509 $fieldtva = 'tva';
4510 $fieldup = 'pu_ht';
4511 }
4512 if ($this->element == 'invoice_supplier_rec') {
4513 $fieldup = 'pu_ht';
4514 }
4515 if ($this->element == 'expensereport') {
4516 // Force rounding mode to '0', otherwise when you set MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND to 1, you may have lines with different totals.
4517 // 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
4518 // and 5,16 on HT total and 1,04 on VAT total to get 6,20 on TTT total on second line (see #30051).
4519 $forcedroundingmode = '0';
4520 $fieldup = 'value_unit';
4521 $base_price_type = 'TTC';
4522 }
4523
4524 $sql = "SELECT rowid, qty, ".$this->db->sanitize($fieldup)." as up, remise_percent,";
4525 $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,";
4526 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
4527 $sql .= ' info_bits, product_type,';
4528 if ($this->element == 'expensereport') {
4529 $sql .= ' comments as description';
4530 } else {
4531 $sql .= ' description';
4532 }
4533 if ($this->table_element_line == 'facturedet') {
4534 $sql .= ', situation_percent';
4535 }
4536 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
4537 $sql .= " FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
4538 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
4539 if ($exclspec) {
4540 $product_field = 'product_type';
4541 if ($this->table_element_line == 'contratdet') {
4542 $product_field = ''; // contratdet table has no product_type field
4543 }
4544 if ($product_field) {
4545 $sql .= " AND ".$this->db->sanitize($product_field)." <> 9";
4546 }
4547 }
4548 $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
4549
4550 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4551
4552 $resql = $this->db->query($sql);
4553 if ($resql) {
4554 $this->total_ht = 0;
4555 $this->total_tva = 0;
4556 $this->total_localtax1 = 0;
4557 $this->total_localtax2 = 0;
4558 $this->total_ttc = 0;
4559 $total_ht_by_vats = array();
4560 $total_tva_by_vats = array();
4561 $total_ttc_by_vats = array();
4562 $this->multicurrency_total_ht = 0;
4563 $this->multicurrency_total_tva = 0;
4564 $this->multicurrency_total_ttc = 0;
4565
4566 $this->db->begin();
4567
4568 $num = $this->db->num_rows($resql);
4569 $i = 0;
4570 while ($i < $num) {
4571 $obj = $this->db->fetch_object($resql);
4572
4573 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = '0'
4574 $parameters = array('fk_element' => $obj->rowid);
4575 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4576
4577 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'
4578 // This part of code is to fix data. We should not call it too often.
4579 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
4580 $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, (isset($obj->multicurrency_subprice) ? $obj->multicurrency_subprice : 0), (isset($this->multicurrency_code) ? $this->multicurrency_code : ''));
4581
4582 $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.
4583 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
4584 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
4585 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
4586
4587 if ($diff_on_current_total) {
4588 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
4589 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line;
4590 $sqlfix .= " SET ".$this->db->sanitize($fieldtva)." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2]);
4591 $sqlfix .= ", multicurrency_total_tva = ".price2num((float) $tmpcal[17]).", multicurrency_total_ttc = ".price2num((float) $tmpcal[18]);
4592 $sqlfix .= " WHERE rowid = ".((int) $obj->rowid);
4593 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);
4594 $resqlfix = $this->db->query($sqlfix);
4595 if (!$resqlfix) {
4596 dol_print_error($this->db, 'Failed to update line');
4597 }
4598 $obj->total_tva = $tmpcal[1];
4599 $obj->total_ttc = $tmpcal[2];
4600 $obj->multicurrency_total_tva = $tmpcal[17];
4601 $obj->multicurrency_total_ttc = $tmpcal[18];
4602 } elseif ($diff_when_using_price_ht) {
4603 // 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
4604 // 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),
4605 // so we continue only if price HT are same.
4606 if ((float) $tmpcal[0] == (float) $obj->total_ht) {
4607 // 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
4608 // will give different results than the one stored in database (the good one are the one in database and we must not fix anything).
4609 if ($obj->description != '(DEPOSIT)' && !getDolGlobalInt('MAIN_DISABLE_AUTOFIX_CORRUPTED_LINES_WHEN_TOTAL_DOES_NOT_MATCH_RECALCULATION_FROM_UP')) {
4610 // 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,
4611 // 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.
4612 // 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.
4613 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line;
4614 $sqlfix .= " SET ".$this->db->sanitize($fieldtva)." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2]);
4615 $sqlfix .= ", multicurrency_total_tva = ".price2num((float) $tmpcal[17]).", multicurrency_total_ttc = ".price2num((float) $tmpcal[18]);
4616 $sqlfix .= " WHERE rowid = ".((int) $obj->rowid);
4617
4618 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);
4619
4620 $resqlfix = $this->db->query($sqlfix);
4621 if (!$resqlfix) {
4622 dol_print_error($this->db, 'Failed to update line');
4623 }
4624 $obj->total_tva = $tmpcal[1];
4625 $obj->total_ttc = $tmpcal[2];
4626 $obj->multicurrency_total_tva = $tmpcal[17];
4627 $obj->multicurrency_total_ttc = $tmpcal[18];
4628 }
4629 }
4630 }
4631 }
4632
4633 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
4634 $this->total_tva += $obj->total_tva;
4635 $this->total_localtax1 += $obj->total_localtax1;
4636 $this->total_localtax2 += $obj->total_localtax2;
4637 $this->total_ttc += $obj->total_ttc;
4638 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
4639 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
4640 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
4641
4642 if (!isset($total_ht_by_vats[$obj->vatrate])) {
4643 $total_ht_by_vats[$obj->vatrate] = 0;
4644 }
4645 if (!isset($total_tva_by_vats[$obj->vatrate])) {
4646 $total_tva_by_vats[$obj->vatrate] = 0;
4647 }
4648 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4649 $total_ttc_by_vats[$obj->vatrate] = 0;
4650 }
4651 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4652 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4653 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4654
4655 if ($forcedroundingmode == '1') { // Check if we need adjustment onto line for vat. TODO This works on the company currency but not on foreign currency
4656 if ($base_price_type == 'TTC') {
4657 $tmpvat = price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate), 'MT', 1);
4658 } else {
4659 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
4660 }
4661 $diff = price2num($total_tva_by_vats[$obj->vatrate] - (float) $tmpvat, 'MT', 1);
4662 //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";
4663 if ($diff) {
4664 $maxdiff = (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)));
4665 if (abs((float) $diff) > $maxdiff) {
4666 // If error is more than 10 times the accuracy of rounding. This should not happen.
4667 $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.';
4668 dol_syslog($errmsg, LOG_WARNING);
4669 $this->error = $errmsg;
4670 $error++;
4671 break;
4672 }
4673
4674 if ($base_price_type == 'TTC') {
4675 $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);
4676 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);
4677 } else {
4678 $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);
4679 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);
4680 }
4681
4682 $resqlfix = $this->db->query($sqlfix);
4683
4684 if (!$resqlfix) {
4685 dol_print_error($this->db, 'Failed to update line');
4686 }
4687
4688 $this->total_tva = (float) price2num($this->total_tva - (float) $diff, '', 1);
4689 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4690 if ($base_price_type == 'TTC') {
4691 $this->total_ht = (float) price2num($this->total_ht + (float) $diff, '', 1);
4692 $total_ht_by_vats[$obj->vatrate] = (float) price2num($total_ht_by_vats[$obj->vatrate] + (float) $diff, '', 1);
4693 } else {
4694 $this->total_ttc = (float) price2num($this->total_ttc - (float) $diff, '', 1);
4695 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4696 }
4697 }
4698 }
4699
4700 $i++;
4701 }
4702
4703 // Add revenue stamp to total
4704 // @phan-suppress-next-line PhanUndeclaredProperty
4705 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4706 // @phan-suppress-next-line PhanUndeclaredProperty
4707 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4708
4709 // Situations totals
4710 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
4711 '@phan-var-force Facture $this';
4712 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
4713 if ($this->type != Facture::TYPE_CREDIT_NOTE) { // @phpstan-ignore-line
4714 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
4715 $prev_sits = $this->get_prev_sits();
4716
4717 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
4718 $this->total_ht -= $sit->total_ht;
4719 $this->total_tva -= $sit->total_tva;
4720 $this->total_localtax1 -= $sit->total_localtax1;
4721 $this->total_localtax2 -= $sit->total_localtax2;
4722 $this->total_ttc -= $sit->total_ttc;
4723 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4724 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4725 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4726 }
4727 }
4728 }
4729 }
4730
4731 // Clean total
4732 $this->total_ht = (float) price2num($this->total_ht);
4733 $this->total_tva = (float) price2num($this->total_tva);
4734 $this->total_localtax1 = (float) price2num($this->total_localtax1);
4735 $this->total_localtax2 = (float) price2num($this->total_localtax2);
4736 $this->total_ttc = (float) price2num($this->total_ttc);
4737 $this->multicurrency_total_ht = (float) price2num($this->multicurrency_total_ht, 'CT', 0, (isset($this->multicurrency_code) ? $this->multicurrency_code : ''));
4738 $this->multicurrency_total_tva = (float) price2num($this->multicurrency_total_tva, 'CT', 0, (isset($this->multicurrency_code) ? $this->multicurrency_code : ''));
4739 $this->multicurrency_total_ttc = (float) price2num($this->multicurrency_total_ttc, 'CT', 0, (isset($this->multicurrency_code) ? $this->multicurrency_code : ''));
4740
4741 $this->db->free($resql);
4742
4743 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
4744 $fieldht = 'total_ht';
4745 $fieldtva = 'tva';
4746 $fieldlocaltax1 = 'localtax1';
4747 $fieldlocaltax2 = 'localtax2';
4748 $fieldttc = 'total_ttc';
4749 // Specific code for backward compatibility with old field names
4750 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
4751 $fieldtva = 'total_tva';
4752 }
4753
4754 if (!$error && empty($nodatabaseupdate)) {
4755 $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
4756 $sql .= " ".$this->db->sanitize($fieldht)." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
4757 $sql .= " ".$this->db->sanitize($fieldtva)." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
4758 $sql .= " ".$this->db->sanitize($fieldlocaltax1)." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
4759 $sql .= " ".$this->db->sanitize($fieldlocaltax2)." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
4760 $sql .= " ".$this->db->sanitize($fieldttc)." = ".((float) price2num($this->total_ttc, 'MT', 1));
4761 $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'CT', 1, (isset($this->multicurrency_code) ? $this->multicurrency_code : '')));
4762 $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'CT', 1, (isset($this->multicurrency_code) ? $this->multicurrency_code : '')));
4763 $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'CT', 1, (isset($this->multicurrency_code) ? $this->multicurrency_code : '')));
4764 $sql .= " WHERE rowid = ".((int) $this->id);
4765
4766 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4767 $resql = $this->db->query($sql);
4768
4769 if (!$resql) {
4770 $error++;
4771 $this->error = $this->db->lasterror();
4772 $this->errors[] = $this->db->lasterror();
4773 }
4774 }
4775
4776 if (!$error) {
4777 $this->db->commit();
4778 return 1;
4779 } else {
4780 $this->db->rollback();
4781 return -1;
4782 }
4783 } else {
4784 dol_print_error($this->db, 'Bad request in update_price');
4785 return -1;
4786 }
4787 }
4788
4789 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4800 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
4801 {
4802 // phpcs:enable
4803 global $user, $hookmanager, $action;
4804 dol_syslog(__METHOD__, LOG_DEBUG);
4805
4806 if (empty($this->origin_type) && !empty($this->origin)) {
4807 $this->origin_type = $this->origin;
4808 }
4809 $origin = (!empty($origin) ? $origin : $this->origin_type);
4810 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4811 $f_user = isset($f_user) ? $f_user : $user;
4812
4813 // Special case
4814 if ($origin == 'order') {
4815 $origin = 'commande';
4816 }
4817 if ($origin == 'invoice') {
4818 $origin = 'facture';
4819 }
4820 if ($origin == 'invoice_template') {
4821 $origin = 'facturerec';
4822 }
4823 if ($origin == 'supplierorder') {
4824 $origin = 'order_supplier';
4825 }
4826
4827 // Add module part to target type
4828 $targettype = $this->getElementType();
4829
4830 $parameters = array('targettype' => $targettype);
4831 // Hook for explicitly set the targettype if it must be different than $this->element
4832 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4833 if ($reshook > 0) {
4834 if (!empty($hookmanager->resArray['targettype'])) {
4835 $targettype = $hookmanager->resArray['targettype'];
4836 }
4837 }
4838
4839 $this->db->begin();
4840 $error = 0;
4841
4842 $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
4843 $sql .= "fk_source";
4844 $sql .= ", sourcetype";
4845 $sql .= ", fk_target";
4846 $sql .= ", targettype";
4847 $sql .= ") VALUES (";
4848 $sql .= ((int) $origin_id);
4849 $sql .= ", '" . $this->db->escape($origin) . "'";
4850 $sql .= ", " . ((int) $this->id);
4851 $sql .= ", '" . $this->db->escape($targettype) . "'";
4852 $sql .= ")";
4853
4854 dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
4855 if ($this->db->query($sql)) {
4856 // If we link a supplier order to a supplier invoice that already uses discounts coming from other supplier invoices
4857 // (deposit invoice / credit note used as payment), also link those source invoices to the same supplier order.
4858 // This helps keep "linked elements" consistent when totals are impacted by such discounts.
4859 if ($origin === 'order_supplier' && $targettype === 'invoice_supplier' && $this->element === 'invoice_supplier' && (int) $origin_id > 0 && (int) $this->id > 0) {
4860 $sourceinvoices = array();
4861
4862 $sqlsources = "SELECT DISTINCT rc.fk_invoice_supplier_source as rowid";
4863 $sqlsources .= " FROM ".$this->db->prefix()."societe_remise_except as rc";
4864 $sqlsources .= " WHERE rc.fk_invoice_supplier = ".((int) $this->id);
4865 $sqlsources .= " AND rc.fk_invoice_supplier_source IS NOT NULL";
4866
4867 $resqlsources = $this->db->query($sqlsources);
4868 if ($resqlsources) {
4869 while ($objsrc = $this->db->fetch_object($resqlsources)) {
4870 $srcid = (int) $objsrc->rowid;
4871 if ($srcid > 0 && $srcid !== (int) $this->id) {
4872 $sourceinvoices[$srcid] = $srcid;
4873 }
4874 }
4875 } else {
4876 dol_syslog(get_class($this)."::add_object_linked Failed to read supplier invoice discounts sources", LOG_WARNING);
4877 }
4878
4879 if (!empty($sourceinvoices)) {
4880 $existing = array();
4881 $sourcelist = implode(',', $sourceinvoices);
4882
4883 $sqlexists = "SELECT fk_target";
4884 $sqlexists .= " FROM ".$this->db->prefix()."element_element";
4885 $sqlexists .= " WHERE fk_source = ".((int) $origin_id);
4886 $sqlexists .= " AND sourcetype = '".$this->db->escape($origin)."'";
4887 $sqlexists .= " AND targettype = '".$this->db->escape($targettype)."'";
4888 $sqlexists .= " AND fk_target IN (".$this->db->sanitize($sourcelist).")";
4889
4890 $resqlexists = $this->db->query($sqlexists);
4891 if ($resqlexists) {
4892 while ($objexist = $this->db->fetch_object($resqlexists)) {
4893 $existing[(int) $objexist->fk_target] = 1;
4894 }
4895 } else {
4896 dol_syslog(get_class($this)."::add_object_linked Failed to read existing linked supplier invoices", LOG_WARNING);
4897 }
4898
4899 foreach ($sourceinvoices as $srcid) {
4900 if (!empty($existing[(int) $srcid])) {
4901 continue;
4902 }
4903
4904 $sqladd = "INSERT INTO " . $this->db->prefix() . "element_element (fk_source, sourcetype, fk_target, targettype)";
4905 $sqladd .= " VALUES (".((int) $origin_id).", '".$this->db->escape($origin)."', ".((int) $srcid).", '".$this->db->escape($targettype)."')";
4906 $this->db->query($sqladd); // Best-effort: do not fail original link action
4907 }
4908 }
4909 }
4910
4911 if (!$notrigger) {
4912 // Call trigger
4913 $this->context['link_origin'] = $origin;
4914 $this->context['link_origin_id'] = $origin_id;
4915
4916 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user); // Note: We should have used here a hook. Not a business event
4917 if ($result < 0) {
4918 $error++;
4919 }
4920 // End call triggers
4921 }
4922 } else {
4923 $this->error = $this->db->lasterror();
4924 $error++;
4925 }
4926
4927 if (!$error) {
4928 $this->db->commit();
4929 return 1;
4930 } else {
4931 $this->db->rollback();
4932 return 0;
4933 }
4934 }
4935
4941 public function getElementType()
4942 {
4943 // 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.
4944 // 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).
4945 $coreModule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
4946 // Add module part to target type if object has $module property and isn't in core modules.
4947 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.'_' : '').$this->element;
4948 }
4949
4950
4973 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
4974 {
4975 global $hookmanager, $action;
4976
4977 // Important for pdf generation time reduction
4978 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
4979 // If you need to force the reload, you can call clearObjectLinkedCache() before calling fetchObjectLinked()
4980 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4981 return 1;
4982 }
4983
4984 $this->linkedObjectsIds = array();
4985 $this->linkedObjects = array();
4986
4987 // Hook for allowing modules to completely alter the behavior of the method
4988 $parameters = array(
4989 'sourceid' => $sourceid,
4990 'sourcetype' => $sourcetype,
4991 'targetid' => $targetid,
4992 'targettype' => $targettype,
4993 'clause' => $clause,
4994 'alsosametype' => $alsosametype,
4995 'orderby' => $orderby,
4996 'loadalsoobjects' => $loadalsoobjects
4997 );
4998 $reshook = $hookmanager->executeHooks('fetchObjectLinked', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4999 if ($reshook > 0) {
5000 return $reshook;
5001 }
5002
5003 $justsource = false;
5004 $justtarget = false;
5005 $withtargettype = false;
5006 $withsourcetype = false;
5007
5008 // Hook for explicitly set the targettype if it must be differtent than $this->element
5009 if (is_object($hookmanager)) {
5010 $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
5011 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5012 if ($reshook > 0) {
5013 if (!empty($hookmanager->resArray['sourcetype'])) {
5014 $sourcetype = $hookmanager->resArray['sourcetype'];
5015 }
5016 if (!empty($hookmanager->resArray['sourceid'])) {
5017 $sourceid = $hookmanager->resArray['sourceid'];
5018 }
5019 if (!empty($hookmanager->resArray['targettype'])) {
5020 $targettype = $hookmanager->resArray['targettype'];
5021 }
5022 if (!empty($hookmanager->resArray['targetid'])) {
5023 $targetid = $hookmanager->resArray['targetid'];
5024 }
5025 }
5026 }
5027
5028 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
5029 $justsource = true; // the source (id and type) is a search criteria
5030 if (!empty($targettype)) {
5031 $withtargettype = true;
5032 }
5033 }
5034 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
5035 $justtarget = true; // the target (id and type) is a search criteria
5036 if (!empty($sourcetype)) {
5037 $withsourcetype = true;
5038 }
5039 }
5040
5041 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
5042 $targetid = (!empty($targetid) ? $targetid : $this->id);
5043 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->getElementType());
5044 $targettype = (!empty($targettype) ? $targettype : $this->getElementType());
5045
5046 /*if (empty($sourceid) && empty($targetid))
5047 {
5048 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
5049 return -1;
5050 }*/
5051
5052 // Links between objects are stored in table element_element
5053 $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
5054 $sql .= " FROM ".$this->db->prefix()."element_element";
5055 $sql .= " WHERE ";
5056 if ($justsource || $justtarget) {
5057 if ($justsource) {
5058 $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
5059 if ($withtargettype) {
5060 $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
5061 }
5062 } elseif ($justtarget) {
5063 $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
5064 if ($withsourcetype) {
5065 $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
5066 }
5067 }
5068 } else {
5069 $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
5070 $sql .= " ".$this->db->sanitize($clause)." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
5071 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
5072 $this->linkedObjectsFullLoaded[$this->id] = true;
5073 }
5074 }
5075 $sql .= $this->db->order($orderby);
5076
5077 dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
5078
5079 $resql = $this->db->query($sql);
5080 if ($resql) {
5081 $num = $this->db->num_rows($resql);
5082 $i = 0;
5083 while ($i < $num) {
5084 $obj = $this->db->fetch_object($resql);
5085 if ($justsource || $justtarget) {
5086 if ($justsource) {
5087 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
5088 } elseif ($justtarget) {
5089 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
5090 }
5091 } else {
5092 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
5093 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
5094 }
5095 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
5096 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
5097 }
5098 }
5099 $i++;
5100 }
5101
5102 if (!empty($this->linkedObjectsIds)) {
5103 $tmparray = $this->linkedObjectsIds;
5104 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
5105 $element_properties = getElementProperties($objecttype);
5106 $element = $element_properties['element'];
5107 $classPath = $element_properties['classpath'];
5108 $classFile = $element_properties['classfile'];
5109 $className = $element_properties['classname'];
5110 $module = $element_properties['module'];
5111
5112 // Here $module, $classFile and $className are set, we can use them.
5113 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
5114 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
5115 dol_include_once('/'.$classPath.'/'.$classFile.'.class.php');
5116 if (class_exists($className)) {
5117 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
5118 $object = new $className($this->db);
5119 '@phan-var-force CommonObject $object';
5120 $ret = $object->fetch($objectid);
5121 if ($ret > 0) {
5122 $this->linkedObjects[$objecttype][$i] = $object;
5123 }
5124 }
5125 }
5126 }
5127 } else {
5128 unset($this->linkedObjectsIds[$objecttype]);
5129 }
5130 }
5131 }
5132 return 1;
5133 } else {
5134 dol_print_error($this->db);
5135 return -1;
5136 }
5137 }
5138
5145 public function clearObjectLinkedCache()
5146 {
5147 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
5148 unset($this->linkedObjectsFullLoaded[$this->id]);
5149 }
5150
5151 return 1;
5152 }
5153
5166 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
5167 {
5168 global $user;
5169 $updatesource = false;
5170 $updatetarget = false;
5171 $f_user = isset($f_user) ? $f_user : $user;
5172 dol_syslog(__METHOD__, LOG_DEBUG);
5173
5174 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
5175 $updatesource = true;
5176 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
5177 $updatetarget = true;
5178 }
5179
5180 $this->db->begin();
5181 $error = 0;
5182
5183 $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
5184 if ($updatesource) {
5185 $sql .= "fk_source = " . ((int) $sourceid);
5186 $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
5187 $sql .= " WHERE fk_target = " . ((int) $this->id);
5188 $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
5189 } elseif ($updatetarget) {
5190 $sql .= "fk_target = " . ((int) $targetid);
5191 $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
5192 $sql .= " WHERE fk_source = " . ((int) $this->id);
5193 $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
5194 }
5195
5196 dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
5197 if ($this->db->query($sql)) {
5198 if (!$notrigger) {
5199 // Call trigger
5200 $this->context['link_source_id'] = $sourceid;
5201 $this->context['link_source_type'] = $sourcetype;
5202 $this->context['link_target_id'] = $targetid;
5203 $this->context['link_target_type'] = $targettype;
5204
5205 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user); // Note: We should have used here a hook. Not a business event
5206 if ($result < 0) {
5207 $error++;
5208 }
5209 // End call triggers
5210 }
5211 } else {
5212 $this->error = $this->db->lasterror();
5213 $error++;
5214 }
5215
5216 if (!$error) {
5217 $this->db->commit();
5218 return 1;
5219 } else {
5220 $this->db->rollback();
5221 return -1;
5222 }
5223 }
5224
5238 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0)
5239 {
5240 global $user;
5241 $deletesource = false;
5242 $deletetarget = false;
5243 $f_user = isset($f_user) ? $f_user : $user;
5244
5245 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
5246 $deletesource = true;
5247 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
5248 $deletetarget = true;
5249 }
5250
5251 $element = $this->getElementType();
5252 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
5253 $sourcetype = (!empty($sourcetype) ? $sourcetype : $element);
5254 $targetid = (!empty($targetid) ? $targetid : $this->id);
5255 $targettype = (!empty($targettype) ? $targettype : $element);
5256 $this->db->begin();
5257 $error = 0;
5258
5259 if (!$notrigger) {
5260 // Call trigger
5261 $this->context['link_id'] = $rowid;
5262 $this->context['link_source_id'] = $sourceid;
5263 $this->context['link_source_type'] = $sourcetype;
5264 $this->context['link_target_id'] = $targetid;
5265 $this->context['link_target_type'] = $targettype;
5266
5267 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user); // Note: We should have used here a hook. Not a business event
5268 if ($result < 0) {
5269 $error++;
5270 }
5271 // End call triggers
5272 }
5273
5274 if (!$error) {
5275 $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
5276 $sql .= " WHERE";
5277 if ($rowid > 0) {
5278 $sql .= " rowid = " . ((int) $rowid);
5279 } else {
5280 if ($deletesource) {
5281 $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
5282 $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($element) . "'";
5283 } elseif ($deletetarget) {
5284 $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
5285 $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($element) . "'";
5286 } else {
5287 $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($element) . "')";
5288 $sql .= " OR";
5289 $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($element) . "')";
5290 }
5291 }
5292
5293 dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
5294 if (!$this->db->query($sql)) {
5295 $this->error = $this->db->lasterror();
5296 $this->errors[] = $this->error;
5297 $error++;
5298 }
5299 }
5300
5301 if (!$error) {
5302 $this->db->commit();
5303 return 1;
5304 } else {
5305 $this->db->rollback();
5306 return 0;
5307 }
5308 }
5309
5319 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
5320 {
5321 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5322 return -1;
5323 }
5324 if (!preg_match('/^[_a-zA-Z0-9]+$/', $field_select)) {
5325 dol_syslog('Invalid value $field_select for parameter '.$field_select.' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
5326 }
5327
5328 global $db;
5329
5330 $sql = "SELECT ".$db->sanitize($field_select)." FROM ".$db->prefix().$db->sanitize($table_element)." WHERE ".$db->sanitize($field_where)." = ".((int) $fk_object_where);
5331 $resql = $db->query($sql);
5332
5333 $TRes = array();
5334 if (!empty($resql)) {
5335 while ($res = $db->fetch_object($resql)) {
5336 $TRes[] = $res->{$field_select};
5337 }
5338 }
5339
5340 return $TRes;
5341 }
5342
5351 public static function getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
5352 {
5353 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5354 return -1;
5355 }
5356
5357 global $db;
5358
5359 $sql = "SELECT COUNT(*) as nb FROM ".$db->prefix().$db->sanitize($table_element)." WHERE ".$db->sanitize($field_where)." = ".((int) $fk_object_where);
5360 $resql = $db->query($sql);
5361 $n = 0;
5362 if ($resql) {
5363 $res = $db->fetch_object($resql);
5364 if ($res) {
5365 $n = $res->nb;
5366 }
5367 }
5368
5369 return $n;
5370 }
5371
5380 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
5381 {
5382 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
5383 return -1;
5384 }
5385
5386 global $db;
5387
5388 $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$db->sanitize($field_where)." = ".((int) $fk_object_where);
5389 $resql = $db->query($sql);
5390
5391 if (empty($resql)) {
5392 return 0;
5393 }
5394
5395 return 1;
5396 }
5397
5409 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = '')
5410 {
5411 global $user;
5412
5413 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
5414
5415 $elementId = (!empty($elementId) ? $elementId : $this->id);
5416 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
5417
5418 $this->db->begin();
5419
5420 if (empty($fieldstatus)) {
5421 if ($elementTable == 'facture_rec') {
5422 $fieldstatus = "suspended";
5423 }
5424 if ($elementTable == 'mailing') {
5425 $fieldstatus = "statut";
5426 }
5427 if ($elementTable == 'cronjob') {
5428 $fieldstatus = "status";
5429 }
5430 if ($elementTable == 'user') {
5431 $fieldstatus = "statut";
5432 }
5433 if ($elementTable == 'expensereport') {
5434 $fieldstatus = "fk_statut";
5435 }
5436 if ($elementTable == 'receptiondet_batch') {
5437 $fieldstatus = "status";
5438 }
5439 if ($elementTable == 'prelevement_bons') {
5440 $fieldstatus = "statut";
5441 }
5442 if ($elementTable == 'bank_account') {
5443 $fieldstatus = "clos";
5444 }
5445 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
5446 $fieldstatus = 'status';
5447 }
5448 // If still empty
5449 if (empty($fieldstatus)) {
5450 $fieldstatus = 'fk_statut';
5451 }
5452 }
5453
5454 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
5455 $sql .= " SET ".$this->db->sanitize($fieldstatus)." = ".((int) $status);
5456 // If status = 1 = validated and we update the main status field, we can update also fk_user_valid
5457 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields and on $fieldstatus
5458 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
5459 $sql .= ", fk_user_valid = ".((int) $user->id);
5460 }
5461 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
5462 $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
5463 }
5464 if ($status == 1 && in_array($elementTable, array('inventory'))) {
5465 $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
5466 }
5467 $sql .= " WHERE rowid = ".((int) $elementId);
5468 $sql .= " AND ".$this->db->sanitize($fieldstatus)." <> ".((int) $status); // We avoid update if status already correct
5469
5470 dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
5471 $resql = $this->db->query($sql);
5472 if ($resql) {
5473 $error = 0;
5474
5475 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
5476
5477 if ($nb_rows_affected > 0) {
5478 if (empty($trigkey)) {
5479 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
5480 if ($this->element == 'supplier_proposal' && $status == 2) {
5481 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
5482 }
5483 if ($this->element == 'supplier_proposal' && $status == 3) {
5484 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
5485 }
5486 if ($this->element == 'supplier_proposal' && $status == 4) {
5487 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
5488 }
5489 if ($this->element == 'fichinter' && $status == 3) {
5490 $trigkey = 'FICHINTER_CLASSIFY_DONE';
5491 }
5492 if ($this->element == 'fichinter' && $status == 2) {
5493 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
5494 }
5495 if ($this->element == 'fichinter' && $status == 1) {
5496 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
5497 }
5498 }
5499
5500 $this->context = array_merge($this->context, array('newstatus' => $status));
5501
5502 if ($trigkey && $trigkey != 'none') {
5503 $this->oldcopy = dol_clone($this);
5504
5505 // Call trigger
5506 $result = $this->call_trigger($trigkey, $user);
5507 if ($result < 0) {
5508 $error++;
5509 }
5510 // End call triggers
5511 }
5512 } else {
5513 // The status was probably already good. We do nothing more, no triggers.
5514 }
5515
5516 if (!$error) {
5517 $this->db->commit();
5518
5519 if (empty($savElementId)) {
5520 // If the element we update is $this (so $elementId was provided as null)
5521 if ($fieldstatus == 'dispute_status') {
5522 $this->dispute_status = $status;
5523 } elseif ($fieldstatus == 'tosell') {
5524 $this->status = $status;
5525 } elseif ($fieldstatus == 'tobuy') {
5526 $this->status_buy = $status; // @phpstan-ignore-line
5527 } elseif ($fieldstatus == 'tobatch') {
5528 $this->status_batch = $status; // @phpstan-ignore-line
5529 } elseif ($fieldstatus == 'stockable_product') {
5530 $this->stockable_product = $status; // @phpstan-ignore-line
5531 } else {
5532 $this->status = $status;
5533 }
5534 }
5535
5536 return 1;
5537 } else {
5538 $this->db->rollback();
5539 dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
5540 return -1;
5541 }
5542 } else {
5543 $this->error = $this->db->lasterror();
5544 $this->db->rollback();
5545 return -1;
5546 }
5547 }
5548
5549
5557 public function getCanvas($id = 0, $ref = '')
5558 {
5559 if (empty($id) && empty($ref)) {
5560 return 0;
5561 }
5562 if (getDolGlobalString('MAIN_DISABLE_CANVAS')) {
5563 return 0; // To increase speed. Not enabled by default.
5564 }
5565
5566 // Clean parameters
5567 $ref = trim($ref);
5568
5569 $sql = "SELECT rowid, canvas";
5570 $sql .= " FROM ".$this->db->prefix().$this->table_element;
5571 $sql .= " WHERE entity IN (".getEntity($this->element).")";
5572 if (!empty($id)) {
5573 $sql .= " AND rowid = ".((int) $id);
5574 }
5575 if (!empty($ref)) {
5576 $sql .= " AND ref = '".$this->db->escape($ref)."'";
5577 }
5578
5579 $resql = $this->db->query($sql);
5580 if ($resql) {
5581 $obj = $this->db->fetch_object($resql);
5582 if ($obj) {
5583 $this->canvas = $obj->canvas;
5584 return 1;
5585 } else {
5586 return 0;
5587 }
5588 } else {
5589 dol_print_error($this->db);
5590 return -1;
5591 }
5592 }
5593
5594
5601 public function getSpecialCode($lineid)
5602 {
5603 $sql = "SELECT special_code FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
5604 $sql .= " WHERE rowid = ".((int) $lineid);
5605 $resql = $this->db->query($sql);
5606 if ($resql) {
5607 $row = $this->db->fetch_row($resql);
5608 return (!empty($row[0]) ? $row[0] : 0);
5609 }
5610
5611 return 0;
5612 }
5613
5622 public function isObjectUsed($id = 0, $entity = 0)
5623 {
5624 global $langs;
5625
5626 if (empty($id)) {
5627 $id = $this->id;
5628 }
5629
5630 // Check parameters
5631 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
5632 dol_print_error(null, 'Called isObjectUsed on a class with property this->childtables not defined');
5633 return -1;
5634 }
5635
5636 $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
5637 // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
5638 $tmparray = array_keys($this->childtables);
5639 if (is_numeric($tmparray[0])) {
5640 $arraytoscan = array_flip($this->childtables);
5641 }
5642
5643 // Test on all child tables to scan if child exists
5644 $haschild = 0;
5645 foreach ($arraytoscan as $table => $element) {
5646 //print $id.'-'.$table.'-'.$elementname.'<br>';
5647
5648 // Check if module is enabled (to avoid error if tables of module not created)
5649 if (isset($element['enabled']) && !empty($element['enabled'])) {
5650 $enabled = (int) dol_eval((string) $element['enabled'], 1);
5651 if (empty($enabled)) {
5652 continue;
5653 }
5654 }
5655
5656 // Check if element can be deleted
5657 $sql = "SELECT COUNT(*) as nb";
5658 $sql .= " FROM ".$this->db->prefix().$this->db->sanitize($table)." as c";
5659 if (!empty($element['parent']) && !empty($element['parentkey'])) {
5660 $sql .= ", ".$this->db->prefix().$this->db->sanitize($element['parent'])." as p";
5661 }
5662 if (!empty($element['fk_element'])) {
5663 $sql .= " WHERE c.".$this->db->sanitize($element['fk_element'])." = ".((int) $id);
5664 } else {
5665 $sql .= " WHERE c.".$this->db->sanitize($this->fk_element)." = ".((int) $id);
5666 }
5667 if (!empty($element['parent']) && !empty($element['parentkey'])) {
5668 $sql .= " AND c.".$this->db->sanitize($element['parentkey'])." = p.rowid";
5669 }
5670 if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
5671 $sql .= " AND c.".$this->db->sanitize($element['parenttypefield'])." = '".$this->db->escape($element['parenttypevalue'])."'";
5672 }
5673 if (!empty($entity)) {
5674 if (!empty($element['parent']) && !empty($element['parentkey'])) {
5675 $sql .= " AND p.entity = ".((int) $entity);
5676 } else {
5677 $sql .= " AND c.entity = ".((int) $entity);
5678 }
5679 }
5680 //var_dump($table, $element, $sql);
5681
5682 $resql = $this->db->query($sql);
5683 if ($resql) {
5684 $obj = $this->db->fetch_object($resql);
5685 if ($obj->nb > 0) {
5686 $langs->load("errors");
5687 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
5688 $haschild += (int) $obj->nb;
5689 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
5690 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
5691 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
5692 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
5693 } else { // new usage: $element['name']=Translation key
5694 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
5695 }
5696 break; // We found at least one, we stop here
5697 }
5698 } else {
5699 $this->errors[] = $this->db->lasterror();
5700 return -1;
5701 }
5702 }
5703
5704 if ($haschild > 0) {
5705 $this->errors[] = "ErrorRecordHasChildren";
5706 return $haschild;
5707 } else {
5708 return 0;
5709 }
5710 }
5711
5718 public function hasProductsOrServices($predefined = -1)
5719 {
5720 $nb = 0;
5721
5722 foreach ($this->lines as $key => $val) {
5723 $qualified = 0;
5724 if ($predefined == -1) {
5725 $qualified = 1;
5726 }
5727 if ($predefined == 1 && $val->fk_product > 0) {
5728 $qualified = 1;
5729 }
5730 if ($predefined == 0 && $val->fk_product <= 0) {
5731 $qualified = 1;
5732 }
5733 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
5734 $qualified = 1;
5735 }
5736 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
5737 $qualified = 1;
5738 }
5739 if ($qualified) {
5740 $nb++;
5741 }
5742 }
5743 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
5744 return $nb;
5745 }
5746
5752 public function getTotalDiscount()
5753 {
5754 if (!empty($this->table_element_line) && ($this->table_element_line != 'expeditiondet')) {
5755 $total_discount = 0.00;
5756
5757 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
5758 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
5759 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
5760
5761 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
5762 $resql = $this->db->query($sql);
5763 if ($resql) {
5764 $num = $this->db->num_rows($resql);
5765 $i = 0;
5766 while ($i < $num) {
5767 $obj = $this->db->fetch_object($resql);
5768
5769 $pu_ht = $obj->pu_ht;
5770 $qty = $obj->qty;
5771 $total_ht = $obj->total_ht;
5772
5773 $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT');
5774 $total_discount += $total_discount_line;
5775
5776 $i++;
5777 }
5778 }
5779
5780 //print $total_discount; exit;
5781 return (float) price2num($total_discount);
5782 }
5783
5784 return null;
5785 }
5786
5787
5794 public function getTotalWeightVolume()
5795 {
5796 $totalWeight = 0;
5797 $totalVolume = 0;
5798 // defined for shipment only
5799 $totalOrdered = 0;
5800 // defined for shipment only
5801 $totalToShip = 0;
5802
5803 if (empty($this->lines)) {
5804 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5805 }
5806
5807 foreach ($this->lines as $line) {
5808 if (isset($line->qty_asked)) {
5809 $totalOrdered += $line->qty_asked; // defined for shipment only
5810 }
5811 if (isset($line->qty_shipped)) {
5812 $totalToShip += $line->qty_shipped; // defined for shipment only
5813 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
5814 if (empty($totalToShip)) {
5815 $totalToShip = 0;
5816 }
5817 $totalToShip += $line->qty; // defined for reception only
5818 }
5819
5820 // Define qty, weight, volume, weight_units, volume_units
5821 if ($this->element == 'shipping') {
5822 // for shipments
5823 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5824 } else {
5825 $qty = $line->qty ? $line->qty : 0;
5826 }
5827
5828 $weight = !empty($line->weight) ? $line->weight : 0;
5829 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5830 $volume = !empty($line->volume) ? $line->volume : 0;
5831 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5832
5833 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5834 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5835 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5836 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5837
5838 $weightUnit = 0;
5839 $volumeUnit = 0;
5840 if (!empty($weight_units)) {
5841 $weightUnit = $weight_units;
5842 }
5843 if (!empty($volume_units)) {
5844 $volumeUnit = $volume_units;
5845 }
5846
5847 if (empty($totalWeight)) {
5848 $totalWeight = 0; // Avoid warning because $totalWeight is ''
5849 }
5850 if (empty($totalVolume)) {
5851 $totalVolume = 0; // Avoid warning because $totalVolume is ''
5852 }
5853
5854 //var_dump($line->volume_units);
5855 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5856 $trueWeightUnit = pow(10, $weightUnit);
5857 $totalWeight += $weight * $qty * $trueWeightUnit;
5858 } else {
5859 if ($weight_units == 99) {
5860 // conversion 1 Pound = 0.45359237 KG
5861 $trueWeightUnit = 0.45359237;
5862 $totalWeight += $weight * $qty * $trueWeightUnit;
5863 } elseif ($weight_units == 98) {
5864 // conversion 1 Ounce = 0.0283495 KG
5865 $trueWeightUnit = 0.0283495;
5866 $totalWeight += $weight * $qty * $trueWeightUnit;
5867 } else {
5868 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
5869 }
5870 }
5871 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5872 //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
5873 $trueVolumeUnit = pow(10, $volumeUnit);
5874 //print $line->volume;
5875 $totalVolume += $volume * $qty * $trueVolumeUnit;
5876 } else {
5877 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
5878 }
5879 }
5880
5881 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5882 }
5883
5884
5890 public function setExtraParameters()
5891 {
5892 $this->db->begin();
5893
5894 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
5895 $extraparams = dol_trunc($extraparams, 250);
5896
5897 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
5898 $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
5899 $sql .= " WHERE rowid = ".((int) $this->id);
5900
5901 dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
5902 $resql = $this->db->query($sql);
5903 if (!$resql) {
5904 $this->error = $this->db->lasterror();
5905 $this->db->rollback();
5906 return -1;
5907 } else {
5908 $this->db->commit();
5909 return 1;
5910 }
5911 }
5912
5913
5914 // --------------------
5915 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
5916 // --------------------
5917
5918 /* This is to show add lines */
5919
5929 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
5930 {
5931 global $conf, $user, $langs, $object, $hookmanager, $extrafields, $form;
5932
5933 // Line extrafield
5934 if (!is_object($extrafields)) {
5935 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5936 $extrafields = new ExtraFields($this->db);
5937 }
5938 $extrafields->fetch_name_optionals_label($this->table_element_line);
5939
5940 // Output template part (modules that overwrite templates must declare this into descriptor)
5941 // Use global variables + $dateSelector + $seller and $buyer
5942 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
5943 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5944 foreach ($dirtpls as $module => $reldir) {
5945 if (!empty($module)) {
5946 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
5947 } else {
5948 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
5949 }
5950
5951 if (empty($conf->file->strict_mode)) {
5952 $res = @include $tpl;
5953 } else {
5954 $res = include $tpl; // for debug
5955 }
5956 if ($res) {
5957 break;
5958 }
5959 }
5960 }
5961
5962
5963
5964 /* This is to show array of line of details */
5965
5966
5981 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
5982 {
5983 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
5984 // TODO We should not use global var for this
5985 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5986
5987 $this->prepareObjectLinesDisplay();
5988
5989 $num = count($this->lines);
5990
5991 $parameters = array();
5992 $reshook = $hookmanager->executeHooks('printObjectLinesBlock', $parameters, $this, $action);
5993 if (empty($reshook)) {
5994 $parameters = array('num' => $num, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
5995 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5996 if (empty($reshook)) {
5997 // Output template part (modules that overwrite templates must declare this into descriptor)
5998 // Use global variables + $dateSelector + $seller and $buyer
5999 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
6000 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
6001 foreach ($dirtpls as $module => $reldir) {
6002 $res = 0;
6003 if (!empty($module)) {
6004 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
6005 } else {
6006 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
6007 }
6008 if (file_exists($tpl)) {
6009 if (empty($conf->file->strict_mode)) {
6010 $res = @include $tpl;
6011 } else {
6012 $res = include $tpl; // for debug
6013 }
6014 }
6015 if ($res) {
6016 break;
6017 }
6018 }
6019 }
6020
6021 $i = 0;
6022
6023 print "<!-- begin printObjectLines() -->\n";
6024 foreach ($this->lines as $line) {
6025 // Line extrafield. TODO Remove this. extrafields should be already loaded.
6026 //$line->fetch_optionals();
6027
6028 $this->printObjectLineWithHooks($action, $line, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
6029
6030 $i++;
6031 }
6032 print "<!-- end printObjectLines() -->\n";
6033 }
6034 }
6035
6042 protected function prepareObjectLinesDisplay()
6043 {
6044 global $extrafields, $usemargins;
6045
6046 // Define $usemargins (used by objectline_xxx.tpl.php files)
6047 $usemargins = 0;
6048 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
6049 $usemargins = 1;
6050 }
6051
6052 // Line extrafield
6053 if (!is_object($extrafields)) {
6054 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6055 $extrafields = new ExtraFields($this->db);
6056 }
6057 $extrafields->fetch_name_optionals_label($this->table_element_line);
6058
6059 if (method_exists($this, 'loadExpeditions')) {
6060 // 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.
6061 $this->loadExpeditions();
6062 }
6063 }
6064
6081 protected function printObjectLineWithHooks($action, $line, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir)
6082 {
6083 global $hookmanager;
6084
6085 // Only lines of documents having sub lines declare fk_parent_line
6086 // @phan-suppress-next-line PhanUndeclaredProperty
6087 $fk_parent_line = (empty($line->fk_parent_line) ? 0 : $line->fk_parent_line);
6088
6089 $reshook = 0;
6090 if (is_object($hookmanager)) {
6091 if (empty($fk_parent_line)) {
6092 $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element, 'defaulttpldir' => $defaulttpldir);
6093 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6094 } else {
6095 $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' => $fk_parent_line, 'defaulttpldir' => $defaulttpldir);
6096 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6097 }
6098 }
6099 if (empty($reshook)) {
6100 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
6101 }
6102 }
6103
6111 {
6112 global $mysoc;
6113
6114 return array(
6115 'seller' => $mysoc,
6116 'buyer' => (is_object($this->thirdparty) ? $this->thirdparty : null),
6117 'dateSelector' => 1,
6118 'forceall' => 0,
6119 'senderissupplier' => 0,
6120 'inputalsopricewithtax' => 0,
6121 );
6122 }
6123
6130 public function initObjectLinesDisplay()
6131 {
6132 // TODO We should not use global var for this
6133 global $forceall, $senderissupplier, $inputalsopricewithtax;
6134
6135 $context = $this->getObjectLinesDisplayContext();
6136
6137 $forceall = $context['forceall'];
6138 $senderissupplier = $context['senderissupplier'];
6139 $inputalsopricewithtax = $context['inputalsopricewithtax'];
6140
6141 return $context;
6142 }
6143
6155 public function getObjectLineHtml($lineid, $action = '')
6156 {
6157 global $object, $form, $extrafields;
6158 global $forceall, $senderissupplier, $inputalsopricewithtax, $usemargins;
6159
6160 $lines = (is_array($this->lines) ? $this->lines : array());
6161 $num = count($lines);
6162 $i = 0;
6163 $line = null;
6164 foreach ($lines as $tmpline) {
6165 if ($tmpline->id == $lineid) {
6166 $line = $tmpline;
6167 break;
6168 }
6169 $i++;
6170 }
6171 if ($line === null) {
6172 $this->error = 'ErrorRecordNotFound';
6173 return '';
6174 }
6175
6176 // Third party is needed for seller or buyer and by printObjectLine()
6177 // @phan-suppress-next-line PhanUndeclaredProperty
6178 if (!is_object($this->thirdparty) && property_exists($this, 'socid') && !empty($this->socid)) {
6179 $this->fetch_thirdparty();
6180 }
6181
6182 // Keep the global variables of the caller, they are restored at the end
6183 $savedGlobals = array($object, $form, $extrafields, $forceall, $senderissupplier, $inputalsopricewithtax, $usemargins);
6184
6185 $object = $this; // Used by the line templates
6186 if (!is_object($form)) {
6187 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
6188 $form = new Form($this->db);
6189 }
6190 $context = $this->initObjectLinesDisplay();
6191 $this->prepareObjectLinesDisplay();
6192
6193 ob_start();
6194 $this->printObjectLineWithHooks($action, $line, $num, $i, $context['dateSelector'], $context['seller'], $context['buyer'], 0, $extrafields, '/core/tpl');
6195 $out = ob_get_clean();
6196
6197 list($object, $form, $extrafields, $forceall, $senderissupplier, $inputalsopricewithtax, $usemargins) = $savedGlobals;
6198
6199 return (string) $out;
6200 }
6201
6219 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
6220 {
6221 global $conf, $langs, $user, $object, $hookmanager; // used into tpl
6222 global $form;
6223 global $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
6224
6225 // var used into tpl
6226 $text = '';
6227 $description = '';
6228
6229 // Line in view mode
6230 if ($action != 'editline' || $selected != $line->id) {
6231 // Product
6232 if (!empty($line->fk_product) && $line->fk_product > 0) {
6233 $product_static = new Product($this->db);
6234 $product_static->fetch($line->fk_product);
6235
6236 $product_static->ref = (string) $line->ref; //can change ref in hook
6237 // label is checked with empty @phan-suppress-next-line PhanUndeclaredProperty
6238 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
6239
6240 $text = $product_static->getNomUrl(1);
6241
6242 // Define output language and label
6243 if (getDolGlobalInt('MAIN_MULTILANGS')) {
6244 // @phan-suppress-next-line PhanUndeclaredProperty
6245 if (property_exists($this, 'socid') && !empty($this->socid) && !is_object($this->thirdparty)) {
6246 dol_print_error(null, 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
6247 return;
6248 }
6249
6250 $prod = new Product($this->db);
6251 $prod->fetch($line->fk_product);
6252
6253 $outputlangs = $langs;
6254 $newlang = '';
6255 if (GETPOST('lang_id', 'aZ09')) {
6256 $newlang = GETPOST('lang_id', 'aZ09');
6257 }
6258 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
6259 $newlang = $this->thirdparty->default_lang; // To use language of customer
6260 }
6261 if (!empty($newlang)) {
6262 $outputlangs = new Translate("", $conf);
6263 $outputlangs->setDefaultLang($newlang);
6264 }
6265
6266 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
6267 } else {
6268 $label = $line->product_label;
6269 }
6270
6271 // label is checked with empty @phan-suppress-next-line PhanUndeclaredProperty
6272 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
6273 $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.
6274 }
6275
6276 // Recalculate unit price with tax if not defined
6277 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)
6278 // So we calculate an estimated value just to show something on screen.
6279 // Not: the unit price is always for 100% of line, it is not a prorata of situation invoice (when total is)
6280 if (empty((float) $line->localtax1_tx) && empty((float) $line->localtax2_tx) && !empty((float) $line->subprice)) {
6281 // With only VAT, the unit price excl. tax gives an exact value, not rounded to the precision of totals like an estimate from total_ttc
6282 $line->subprice_ttc = (float) price2num($line->subprice * (1 + ((((int) $line->info_bits & 1) ? 0 : (float) $line->tva_tx) / 100)), 'MU');
6283 } elseif ($line->remise_percent != 100) {
6284 // Suppose situation_percent is defined @phan-suppress-next-line PhanUndeclaredProperty
6285 $line->subprice_ttc = (float) price2num($line->total_ttc * ($line->situation_percent ? 100 / $line->situation_percent : 1) / $line->qty / (1 - $line->remise_percent / 100), 'MU');
6286 } else {
6287 // Other method is less accurate
6288 $line->subprice_ttc = (float) price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
6289 }
6290 }
6291 $line->pu_ttc = $line->subprice_ttc; // deprecated
6292
6293 // Output template part (modules that overwrite templates must declare this into descriptor)
6294 // Use global variables + $dateSelector + $seller and $buyer
6295 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
6296
6297 $qty_shipped = 0;
6298 if (isset($this->expeditions[$line->id])) { // @phan-suppress-current-line PhanUndeclaredProperty
6299 // Suppose existence of expeditions is tested @phan-suppress-next-line PhanUndeclaredProperty
6300 $qty_shipped = $this->expeditions[$line->id];
6301 }
6302 $disableedit = ($qty_shipped > 0) && ($qty_shipped >= $line->qty);
6303
6304 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
6305 foreach ($dirtpls as $module => $reldir) {
6306 $res = 0;
6307 if (!empty($module)) {
6308 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
6309 } else {
6310 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
6311 }
6312 //var_dump($tpl);
6313 if (file_exists($tpl)) {
6314 if (empty($conf->file->strict_mode)) {
6315 $res = @include $tpl;
6316 } else {
6317 $res = include $tpl; // for debug
6318 }
6319 }
6320 if ($res) {
6321 break;
6322 }
6323 }
6324 }
6325
6326 // Line in update mode
6327 if ($this->status == 0 && $action == 'editline' && $selected == $line->id) {
6328 // label is tested @phan-suppress-next-line PhanUndeclaredProperty
6329 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
6330
6331 $line->subprice_ttc = (float) price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
6332 $line->pu_ttc = $line->subprice_ttc; // deprecated
6333
6334 // Output template part (modules that overwrite templates must declare this into descriptor)
6335 // Use global variables + $dateSelector + $seller and $buyer
6336 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
6337 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
6338 foreach ($dirtpls as $module => $reldir) {
6339 if (!empty($module)) {
6340 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
6341 } else {
6342 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
6343 }
6344
6345 if (empty($conf->file->strict_mode)) {
6346 $res = @include $tpl;
6347 } else {
6348 $res = include $tpl; // for debug
6349 }
6350 if ($res) {
6351 break;
6352 }
6353 }
6354 }
6355 }
6356
6357
6358 /* This is to show array of line of details of source object */
6359
6360
6371 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
6372 {
6373 global $langs, $hookmanager, $form, $action;
6374
6375 print '<!-- printOriginLinesList '.get_class($this).' -->'."\n";
6376 print '<tr class="liste_titre">';
6377 print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
6378 print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
6379 print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
6380 print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
6381 if (isModEnabled("multicurrency")) {
6382 print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
6383 }
6384 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
6385 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
6386 print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
6387 }
6388 print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
6389 print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
6390 print '<td class="center">';
6391 print $form->showCheckAddButtons('checkforselect', 1);
6392 print '</td>';
6393 print '</tr>';
6394 $i = 0;
6395
6396 if (!empty($this->lines)) {
6397 foreach ($this->lines as $line) {
6398 $reshook = 0;
6399 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
6400 if (is_object($hookmanager)) { // Old code is commented on preceding line.
6401 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
6402 if (!empty($line->fk_parent_line)) {
6403 $parameters['fk_parent_line'] = $line->fk_parent_line;
6404 }
6405 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6406 }
6407 if (empty($reshook)) {
6408 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
6409 }
6410
6411 $i++;
6412 }
6413 }
6414 }
6415
6429 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
6430 {
6431 global $langs, $conf;
6432
6433 //var_dump($line);
6434 if (!empty($line->date_start)) {
6435 // @phan-suppress-next-line PhanUndeclaredProperty
6436 $date_start = $line->date_start;
6437 } else {
6438 $date_start = $line->date_debut_prevue;
6439 if ($line->date_debut_reel) {
6440 $date_start = $line->date_debut_reel;
6441 }
6442 }
6443 if (!empty($line->date_end)) {
6444 // @phan-suppress-next-line PhanUndeclaredProperty
6445 $date_end = $line->date_end;
6446 } else {
6447 $date_end = $line->date_fin_prevue;
6448 if ($line->date_fin_reel) {
6449 $date_end = $line->date_fin_reel;
6450 }
6451 }
6452
6453 // Set thevalue into ->tpl[] array.
6454 $this->tpl['id'] = $line->id;
6455
6456 $this->tpl['label'] = '';
6457 if (!empty($line->fk_parent_line)) {
6458 $this->tpl['label'] .= img_picto('', 'rightarrow.png');
6459 }
6460
6461 if (((int) $line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
6462 $discount = new DiscountAbsolute($this->db);
6463 if (property_exists($this, 'socid')) {
6464 // Tested if socid exists @phan-suppress-next-line PhanUndeclaredProperty
6465 $discount->fk_soc = $this->socid;
6466 // Tested if socid exists @phan-suppress-next-line PhanUndeclaredProperty
6467 $discount->socid = $this->socid;
6468 }
6469 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
6470 } elseif (!empty($line->fk_product)) {
6471 $productstatic = new Product($this->db);
6472 $productstatic->id = $line->fk_product;
6473 $productstatic->ref = (string) $line->ref;
6474 $productstatic->type = $line->fk_product_type;
6475 if (empty($productstatic->ref)) {
6476 $line->fetch_product();
6477 $productstatic = $line->product;
6478 }
6479
6480 $this->tpl['label'] .= $productstatic->getNomUrl(1);
6481 // Existence of $line->label is tested @phan-suppress-next-line PhanUndeclaredProperty
6482 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
6483 // Dates
6484 if ($line->product_type == 1 && ($date_start || $date_end)) {
6485 $this->tpl['label'] .= get_date_range($date_start, $date_end);
6486 }
6487 } else {
6488 $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"')));
6489 if (!empty($line->desc)) {
6490 $this->tpl['label'] .= $line->desc;
6491 } else {
6492 // Supposes existence of $line->label @phan-suppress-next-line PhanUndeclaredProperty
6493 $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
6494 }
6495
6496 // Dates
6497 if ($line->product_type == 1 && ($date_start || $date_end)) {
6498 $this->tpl['label'] .= get_date_range($date_start, $date_end);
6499 }
6500 }
6501
6502 if (!empty($line->desc)) {
6503 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
6504 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
6505 $discount = new DiscountAbsolute($this->db);
6506 $discount->fetch($line->fk_remise_except);
6507 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
6508 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
6509 $discount = new DiscountAbsolute($this->db);
6510 $discount->fetch($line->fk_remise_except);
6511 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
6512 } elseif ($line->desc == '(EXCESS RECEIVED)') {
6513 $discount = new DiscountAbsolute($this->db);
6514 $discount->fetch($line->fk_remise_except);
6515 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
6516 } elseif ($line->desc == '(EXCESS PAID)') {
6517 $discount = new DiscountAbsolute($this->db);
6518 $discount->fetch($line->fk_remise_except);
6519 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
6520 } else {
6521 $this->tpl['description'] = dol_trunc($line->desc, 60);
6522 }
6523 } else {
6524 $this->tpl['description'] = '&nbsp;';
6525 }
6526
6527 // VAT Rate
6528 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
6529 $this->tpl['vat_rate'] .= (((int) $line->info_bits & 1) == 1) ? '*' : '';
6530 if (!empty($line->vat_src_code) && !preg_match('/\‍(/', $this->tpl['vat_rate'])) {
6531 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
6532 }
6533
6534 $this->tpl['price'] = price($line->subprice);
6535 $this->tpl['total_ht'] = price($line->total_ht);
6536 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
6537 $this->tpl['qty'] = (((int) $line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
6538 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
6539 $this->tpl['unit'] = $line->getLabelOfUnit('long', $langs);
6540 $this->tpl['unit_short'] = $line->getLabelOfUnit('short', $langs);
6541 //$this->tpl['unit_code'] = $line->getLabelOfUnit('code');
6542 }
6543 $this->tpl['remise_percent'] = (((int) $line->info_bits & 2) != 2) ? vatrate((string) $line->remise_percent, true) : '&nbsp;';
6544
6545 // Is the line strike or not
6546 $this->tpl['strike'] = 0;
6547 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
6548 $this->tpl['strike'] = 1;
6549 } elseif (defined('SUBTOTALS_SPECIAL_CODE') && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
6550 // SUBTOTALS_SPECIAL_CODE is only defined when the subtotals module
6551 // is loaded (htdocs/subtotals/class/commonsubtotal.class.php:24).
6552 // Without the guard, printing origin lines from a PO into a vendor
6553 // invoice fatals (#37663). Other tpl files already follow this pattern.
6554 $this->tpl['strike'] = 1;
6555 }
6556
6557 // Output template part (modules that overwrite templates must declare this into descriptor)
6558 // Use global variables + $dateSelector + $seller and $buyer
6559 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
6560 foreach ($dirtpls as $module => $reldir) {
6561 if (!empty($module)) {
6562 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
6563 } else {
6564 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
6565 }
6566
6567 if (empty($conf->file->strict_mode)) {
6568 $res = @include $tpl;
6569 } else {
6570 $res = include $tpl; // for debug
6571 }
6572 if ($res) {
6573 break;
6574 }
6575 }
6576 }
6577
6578
6579 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6591 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0, $notrigger = 0)
6592 {
6593 // phpcs:enable
6594 global $user;
6595 $this->db->begin();
6596
6597 $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
6598 $sql .= "resource_id";
6599 $sql .= ", resource_type";
6600 $sql .= ", element_id";
6601 $sql .= ", element_type";
6602 $sql .= ", busy";
6603 $sql .= ", mandatory";
6604 $sql .= ") VALUES (";
6605 $sql .= ((int) $resource_id);
6606 $sql .= ", '".$this->db->escape($resource_type)."'";
6607 $sql .= ", '".$this->db->escape((string) $this->id)."'";
6608 $sql .= ", '".$this->db->escape($this->element)."'";
6609 $sql .= ", '".$this->db->escape((string) $busy)."'";
6610 $sql .= ", '".$this->db->escape((string) $mandatory)."'";
6611 $sql .= ")";
6612
6613 dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
6614 if ($this->db->query($sql)) {
6615 if (!$notrigger) {
6616 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).'_ADD_RESOURCE', $user);
6617 if ($result < 0) {
6618 $this->db->rollback();
6619 return -1;
6620 }
6621 }
6622 $this->db->commit();
6623 return 1;
6624 } else {
6625 $this->error = $this->db->lasterror();
6626 $this->db->rollback();
6627 return 0;
6628 }
6629 }
6630
6631 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6640 public function delete_resource($rowid, $element = '', $notrigger = 0)
6641 {
6642 // phpcs:enable
6643 global $user;
6644
6645 $this->db->begin();
6646
6647 $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
6648 $sql .= " WHERE rowid = ".((int) $rowid);
6649
6650 dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
6651
6652 $resql = $this->db->query($sql);
6653 if (!$resql) {
6654 $this->error = $this->db->lasterror();
6655 $this->db->rollback();
6656 return -1;
6657 } else {
6658 if (!$notrigger) {
6659 $result = $this->call_trigger(strtoupper($this->TRIGGER_PREFIX).'_DELETE_RESOURCE', $user);
6660 if ($result < 0) {
6661 $this->db->rollback();
6662 return -1;
6663 }
6664 }
6665 $this->db->commit();
6666 return 1;
6667 }
6668 }
6669
6670
6676 public function __clone()
6677 {
6678 // Force a copy of this->lines, otherwise it will point to same object.
6679 if (isset($this->lines) && is_array($this->lines)) {
6680 $nboflines = count($this->lines);
6681 for ($i = 0; $i < $nboflines; $i++) {
6682 if (is_object($this->lines[$i])) {
6683 $this->lines[$i] = clone $this->lines[$i];
6684 }
6685 }
6686 }
6687 }
6688
6702 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
6703 {
6704 global $conf, $langs, $hookmanager, $action;
6705
6706 $srctemplatepath = '';
6707
6708 $parameters = array('modelspath' => $modelspath, 'modele' => $modele, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'hidedesc' => $hidedesc, 'hideref' => $hideref, 'moreparams' => $moreparams);
6709 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
6710
6711 if (!empty($reshook)) {
6712 return $reshook;
6713 }
6714
6715 dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
6716
6717 if (empty($modele)) {
6718 $this->error = 'BadValueForParameterModele';
6719 return -1;
6720 }
6721
6722 // Increase limit for PDF build
6723 $err = error_reporting();
6724 error_reporting(0);
6725 @set_time_limit(120);
6726 error_reporting($err);
6727
6728 // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
6729 $tmp = explode(':', $modele, 2);
6730 $saved_model = $modele;
6731 if (!empty($tmp[1])) {
6732 $modele = $tmp[0];
6733 $srctemplatepath = $tmp[1];
6734
6735 if (!preg_match('/^'.preg_quote(DOL_DATA_ROOT, '/').'\/(ecm|doctemplates)/', $srctemplatepath)) {
6736 $this->error = 'BadDirForTemplateFile';
6737 return -1;
6738 }
6739 }
6740
6741 // Search template files
6742 $file = '';
6743 $classname = '';
6744 $filefound = '';
6745 $dirmodels = array('/');
6746 if (is_array($conf->modules_parts['models'])) {
6747 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
6748 }
6749 foreach ($dirmodels as $reldir) {
6750 foreach (array('doc', 'pdf') as $prefix) {
6751 if (in_array(get_class($this), array('Adherent'))) {
6752 // Member module use prefix_modele.class.php
6753 $file = $prefix."_".$modele.".class.php";
6754 } else {
6755 // Other module use prefix_modele.modules.php
6756 $file = $prefix."_".$modele.".modules.php";
6757 }
6758
6759 $file = dol_sanitizeFileName($file);
6760
6761 // We check if the file exists
6762 $file = dol_buildpath($reldir.$modelspath.$file, 0);
6763 if (file_exists($file)) {
6764 $filefound = $file;
6765 $classname = $prefix.'_'.$modele;
6766 break;
6767 }
6768 }
6769 if ($filefound) {
6770 break;
6771 }
6772 }
6773
6774 if ($filefound === '' || $classname === '') {
6775 $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
6776 $this->errors[] = $this->error;
6777 dol_syslog($this->error, LOG_ERR);
6778 return -1;
6779 }
6780
6781 // Sanitize $filefound
6782 $filefound = dol_sanitizePathName($filefound);
6783
6784 // If generator was found
6785 global $db; // Required to solve a conception error making an include of some code that uses $db instead of $this->db just after.
6786
6787 require_once $filefound;
6788
6789 $obj = new $classname($this->db);
6790
6791 // TODO: Check the following classes that seem possible for $obj, but removed for compatibility:
6792 // ModeleBankAccountDoc|ModeleExpenseReport|ModelePDFBom|ModelePDFCommandes|ModelePDFContract|
6793 // ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|
6794 // ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|
6795 // ModelePDFRecruitmentJobPosition|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|
6796 // ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePdfExpedition|ModelePdfReception|
6797 // ModelePDFStock|ModelePDFStockTransfer|
6798 // ModeleDon|ModelePDFTask|
6799 // ModelePDFAsset|ModelePDFTicket|ModelePDFUserGroup|ModeleThirdPartyDoc|ModelePDFUser
6800 // Has no write_file: ModeleBarCode|ModeleImports|ModeleExports|
6801 '@phan-var-force ModelePDFMember $obj';
6802 // '@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';
6803
6804 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
6805 if ($obj->type == 'odt' && empty($srctemplatepath)) {
6806 $varfortemplatedir = $obj->scandir;
6807 if ($varfortemplatedir && getDolGlobalString($varfortemplatedir)) {
6808 $dirtoscan = getDolGlobalString($varfortemplatedir);
6809
6810 $listoffiles = array();
6811
6812 // Now we add first model found in directories scanned
6813 $listofdir = explode(',', $dirtoscan);
6814 foreach ($listofdir as $key => $tmpdir) {
6815 $tmpdir = trim($tmpdir);
6816 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
6817 if (!$tmpdir) {
6818 unset($listofdir[$key]);
6819 continue;
6820 }
6821 if (is_dir($tmpdir)) {
6822 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
6823 if (count($tmpfiles)) {
6824 $listoffiles = array_merge($listoffiles, $tmpfiles);
6825 }
6826 }
6827 }
6828
6829 if (count($listoffiles)) {
6830 foreach ($listoffiles as $record) {
6831 $srctemplatepath = $record['fullname'];
6832 break;
6833 }
6834 }
6835 }
6836
6837 if (empty($srctemplatepath)) {
6838 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
6839 return -1;
6840 }
6841 }
6842
6843 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
6844 if (!dol_is_file($srctemplatepath)) {
6845 dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
6846 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
6847 return -1;
6848 }
6849 }
6850
6851 // We save charset_output to restore it because write_file can change it if needed for
6852 // output format that does not support UTF8.
6853 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
6854
6855 // update model_pdf in object
6856 $this->model_pdf = $saved_model;
6857
6858 try {
6859 if ($obj instanceof ModelePDFMember) {
6860 if ($this instanceof Adherent) {
6861 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards');
6862 } else {
6863 $resultwritefile = -1;
6864 dol_syslog("Error generating document - Provided ".get_class($this)." to ".get_class($obj)."::write_file()", LOG_ERR);
6865 }
6866 } elseif ($obj instanceof ModeleDon) {
6867 // Only 3 arguments
6868 if ($this instanceof Don) {
6869 $resultwritefile = $obj->write_file($this, $outputlangs /*, $currency */);
6870 } else {
6871 $resultwritefile = -1;
6872 dol_syslog("Error generating document - Provided ".get_class($this)." to Don::write_file()", LOG_ERR);
6873 }
6874 } else {
6875 // TODO: Try to set type above again
6876 '@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';
6877 $this->context['moreparams'] = $moreparams;
6878 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref); // @phan-suppress-current-line PhanTypeMismatchArgument
6879 }
6880 } catch (\Throwable $e) {
6881 $resultwritefile = -1;
6882 $this->error = $e->getMessage();
6883 dol_syslog("Exception in write_file() for ".get_class($this).": ".$e->getMessage(), LOG_ERR);
6884 }
6885 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
6886
6887
6888 if ($resultwritefile > 0) {
6889 $outputlangs->charset_output = $sav_charset_output;
6890
6891 // We delete old preview
6892 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6893 dol_delete_preview($this);
6894
6895 // Index file in database
6896 if (!empty($obj->result['fullpath'])) {
6897 $destfull = $obj->result['fullpath'];
6898
6899 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
6900 $update_main_doc_field = 0;
6901 if (!empty($obj->update_main_doc_field)) {
6902 $update_main_doc_field = 1;
6903 }
6904
6905 // Check that the file exists, before indexing it.
6906 // Hint: It does not exist, if we create a PDF and auto delete the ODT File
6907 if (dol_is_file($destfull)) {
6908 $this->indexFile($destfull, $update_main_doc_field);
6909 }
6910 } else {
6911 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);
6912 }
6913
6914 // Success in building document. We build meta file.
6915 dol_meta_create($this);
6916
6917 $this->warnings = $obj->warnings;
6918
6919 return 1;
6920 } else {
6921 $outputlangs->charset_output = $sav_charset_output;
6922 if (empty($this->error)) {
6923 $this->error = $obj->error;
6924 }
6925 if (empty($this->errors)) {
6926 $this->errors = $obj->errors;
6927 }
6928 $this->warnings = $obj->warnings;
6929 dol_syslog("Error generating document for ".__CLASS__.". Error: ".$this->error, LOG_ERR);
6930 return -1;
6931 }
6932 }
6933
6943 public function indexFile($destfull, $update_main_doc_field)
6944 {
6945 global $conf, $user;
6946
6947 $upload_dir = dirname($destfull);
6948 $destfile = basename($destfull);
6949 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
6950
6951 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
6952 $filename = basename($destfile);
6953 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
6954 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
6955
6956 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
6957 $ecmfile = new EcmFiles($this->db);
6958 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
6959
6960 // Set the public "share" key
6961 $setsharekey = false;
6962 if (
6963 !empty($this->TRIGGER_PREFIX)
6964 && (getDolGlobalInt($this->TRIGGER_PREFIX . "_ALLOW_EXTERNAL_DOWNLOAD") || getDolGlobalInt($this->TRIGGER_PREFIX . "_ALLOW_ONLINESIGN"))
6965 ) {
6966 $setsharekey = true;
6967 }
6968 // TODO Remove case covered by trigger prefix
6969 if ($this->element == 'propal' || $this->element == 'proposal') {
6970 if (getDolGlobalInt("PROPOSAL_ALLOW_ONLINESIGN")) {
6971 $setsharekey = true; // feature to make online signature is not set or set to on (default)
6972 }
6973 if (getDolGlobalInt("PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6974 $setsharekey = true;
6975 }
6976 }
6977 if ($this->element == 'facture' && getDolGlobalInt("INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6978 $setsharekey = true;
6979 }
6980 if ($this->element == 'bank_account' && getDolGlobalInt("BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
6981 $setsharekey = true;
6982 }
6983 if ($this->element == 'contrat' && getDolGlobalInt("CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
6984 $setsharekey = true;
6985 }
6986 if ($this->element == 'supplier_proposal' && getDolGlobalInt("SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6987 $setsharekey = true;
6988 }
6989 if ($this->element == 'order_supplier' && getDolGlobalInt("SUPPLIER_ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
6990 $setsharekey = true;
6991 }
6992 if ($this->element == 'invoice_supplier' && getDolGlobalInt("SUPPLIER_INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
6993 $setsharekey = true;
6994 }
6995 if ($this->element == 'societe_rib' && getDolGlobalInt("SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6996 $setsharekey = true;
6997 }
6998
6999 if ($setsharekey) {
7000 if (empty($ecmfile->share)) { // Because object not found or share not set yet
7001 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
7002 $ecmfile->share = getRandomPassword(true);
7003 }
7004 }
7005
7006 if ($result > 0) {
7007 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
7008 $ecmfile->fullpath_orig = '';
7009 $ecmfile->gen_or_uploaded = 'generated';
7010 $ecmfile->description = ''; // indexed content
7011 $ecmfile->keywords = ''; // keyword content
7012 $ecmfile->src_object_type = $this->table_element;
7013 $ecmfile->src_object_id = $this->id;
7014 $result = $ecmfile->update($user);
7015 if ($result < 0) {
7016 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
7017 return -1;
7018 }
7019 } else {
7020 $ecmfile->entity = $conf->entity;
7021 $ecmfile->filepath = $rel_dir;
7022 $ecmfile->filename = $filename;
7023 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
7024 $ecmfile->fullpath_orig = '';
7025 $ecmfile->gen_or_uploaded = 'generated';
7026 $ecmfile->description = ''; // indexed content
7027 $ecmfile->keywords = ''; // keyword content
7028 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
7029 $ecmfile->src_object_id = $this->id;
7030
7031 $result = $ecmfile->create($user);
7032 if ($result < 0) {
7033 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
7034 return -1;
7035 }
7036 }
7037
7038 /*$this->result['fullname']=$destfull;
7039 $this->result['filepath']=$ecmfile->filepath;
7040 $this->result['filename']=$ecmfile->filename;*/
7041 //var_dump($obj->update_main_doc_field);exit;
7042
7043 if ($update_main_doc_field && !empty($this->table_element)) {
7044 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
7045 $sql .= " WHERE rowid = ".((int) $this->id);
7046
7047 $resql = $this->db->query($sql);
7048 if (!$resql) {
7049 dol_print_error($this->db);
7050 return -1;
7051 } else {
7052 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
7053 }
7054 }
7055 }
7056
7057 return 1;
7058 }
7059
7068 public function addThumbs($file, $quality = 50)
7069 {
7070 $file_osencoded = dol_osencode($file);
7071
7072 if (file_exists($file_osencoded)) {
7073 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
7074
7075 $tmparraysize = getDefaultImageSizes();
7076 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
7077 $maxheightsmall = $tmparraysize['maxheightsmall'];
7078 $maxwidthmini = $tmparraysize['maxwidthmini'];
7079 $maxheightmini = $tmparraysize['maxheightmini'];
7080 //$quality = $tmparraysize['quality'];
7081
7082 // Create small thumbs for company (Ratio is near 16/9)
7083 // Used on logon for example
7084 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
7085
7086 // Create mini thumbs for company (Ratio is near 16/9)
7087 // Used on menu or for setup page for example
7088 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
7089 }
7090 }
7091
7099 public function delThumbs($file)
7100 {
7101 $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
7102 dol_delete_file($imgThumbName);
7103 $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
7104 dol_delete_file($imgThumbName);
7105 }
7106
7107
7108 /* Functions common to commonobject and commonobjectline */
7109
7110 /* For default values */
7111
7125 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
7126 {
7127 /* TODO Remove this. Must use now something like:
7128 $note_private = GETPOST('note_private', 'restricthtml');
7129 if (!GETPOSTISSET('note_private') && empty($note_private) && !empty($objectsrc) [&& othercondtion]) {
7130 $note_private = $objectsrc->note_private;
7131 }
7132 */
7133
7134 // If param here has been posted, we use this value first.
7135 if (GETPOSTISSET($fieldname)) {
7136 return GETPOST($fieldname, $type, 3);
7137 }
7138
7139 if (isset($alternatevalue)) {
7140 return $alternatevalue;
7141 }
7142
7143 $newelement = $this->element;
7144 if ($newelement == 'facture') {
7145 $newelement = 'invoice';
7146 }
7147 if ($newelement == 'commande') {
7148 $newelement = 'order';
7149 }
7150 if (empty($newelement)) {
7151 dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
7152 return '';
7153 }
7154
7155 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
7156 //var_dump($keyforfieldname);
7157 if (getDolGlobalString($keyforfieldname)) {
7158 return getDolGlobalString($keyforfieldname);
7159 }
7160
7161 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
7162 // store content into $conf->cache['overwrite_default']
7163
7164 return '';
7165 }
7166
7167
7168 /* Functions for data in other language */
7169
7170
7180 {
7181 // To avoid SQL errors. Probably not the better solution though
7182 if (!$this->element) {
7183 return 0;
7184 }
7185 if (!($this->id > 0)) {
7186 return 0;
7187 }
7188 if (is_array($this->array_languages)) {
7189 return 1;
7190 }
7191
7192 $this->array_languages = array();
7193
7194 $element = $this->element;
7195 if ($element == 'categorie') {
7196 $element = 'categories'; // For compatibility
7197 }
7198
7199 // Request to get translation values for object
7200 $sql = "SELECT rowid, property, lang , value";
7201 $sql .= " FROM ".$this->db->prefix()."object_lang";
7202 $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
7203 $sql .= " AND fk_object = ".((int) $this->id);
7204
7205 $resql = $this->db->query($sql);
7206 if ($resql) {
7207 $numrows = $this->db->num_rows($resql);
7208 if ($numrows) {
7209 $i = 0;
7210 while ($i < $numrows) {
7211 $obj = $this->db->fetch_object($resql);
7212 $key = $obj->property;
7213 $value = $obj->value;
7214 $codelang = $obj->lang;
7215 $type = $this->fields[$key]['type'];
7216
7217 // we can add this attribute to object
7218 if (preg_match('/date/', $type)) {
7219 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
7220 } else {
7221 $this->array_languages[$key][$codelang] = $value;
7222 }
7223
7224 $i++;
7225 }
7226 }
7227
7228 $this->db->free($resql);
7229
7230 if ($numrows) {
7231 return $numrows;
7232 } else {
7233 return 0;
7234 }
7235 } else {
7236 dol_print_error($this->db);
7237 return -1;
7238 }
7239 }
7240
7248 public function setValuesForExtraLanguages($onlykey = '')
7249 {
7250 // Get extra fields
7251 foreach ($_POST as $postfieldkey => $postfieldvalue) {
7252 $tmparray = explode('-', $postfieldkey);
7253 if ($tmparray[0] != 'field') {
7254 continue;
7255 }
7256
7257 $element = $tmparray[1];
7258 $key = $tmparray[2];
7259 $codelang = $tmparray[3];
7260 //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
7261
7262 if (!empty($onlykey) && $key != $onlykey) {
7263 continue;
7264 }
7265 if ($element != $this->element) {
7266 continue;
7267 }
7268
7269 $key_type = $this->fields[$key]['type'];
7270
7271 $enabled = 1;
7272 if (isset($this->fields[$key]['enabled'])) {
7273 $enabled = (int) dol_eval((string) $this->fields[$key]['enabled'], 1, 1, '1');
7274 }
7275 /*$perms = 1;
7276 if (isset($this->fields[$key]['perms']))
7277 {
7278 $perms = (int) dol_eval((string) $this->fields[$key]['perms'], 1, 1, '1');
7279 }*/
7280 if (empty($enabled)) {
7281 continue;
7282 }
7283 //if (empty($perms)) continue;
7284
7285 if (in_array($key_type, array('date'))) {
7286 // Clean parameters
7287 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
7288 $value_key = dol_mktime(0, 0, 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
7289 } elseif (in_array($key_type, array('datetime'))) {
7290 // Clean parameters
7291 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
7292 $value_key = dol_mktime(GETPOSTINT($postfieldkey."hour"), GETPOSTINT($postfieldkey."min"), 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
7293 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
7294 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
7295 if (!empty($value_arr)) {
7296 $value_key = implode(',', $value_arr);
7297 } else {
7298 $value_key = '';
7299 }
7300 } elseif (in_array($key_type, array('price', 'double'))) {
7301 $value_arr = GETPOST($postfieldkey, 'alpha');
7302 $value_key = price2num($value_arr);
7303 } else {
7304 $value_key = GETPOST($postfieldkey);
7305 if (in_array($key_type, array('link')) && $value_key == '-1') {
7306 $value_key = '';
7307 }
7308 }
7309
7310 $this->array_languages[$key][$codelang] = $value_key;
7311
7312 /*if ($nofillrequired) {
7313 $langs->load('errors');
7314 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
7315 return -1;
7316 }*/
7317 }
7318
7319 return 1;
7320 }
7321
7322
7323 /* Functions for extrafields */
7324
7331 public function fetchNoCompute($id)
7332 {
7333 global $conf;
7334
7335 $savDisableCompute = $conf->disable_compute;
7336 $conf->disable_compute = 1;
7337
7338 $ret = $this->fetch($id); /* @phpstan-ignore-line */
7339
7340 $conf->disable_compute = $savDisableCompute;
7341
7342 return $ret;
7343 }
7344
7345 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7355 public function fetch_optionals($rowid = null, $optionsArray = null)
7356 {
7357 // phpcs:enable
7358 global $conf, $extrafields;
7359
7360 if (empty($rowid)) {
7361 $rowid = $this->id;
7362 }
7363 if (empty($rowid) && isset($this->rowid)) { // @phan-suppress-current-line PhanUndeclaredProperty
7364 $rowid = $this->rowid; // deprecated @phan-suppress-current-line PhanUndeclaredProperty
7365 }
7366
7367 // To avoid SQL errors. Probably not the better solution though
7368 if (!$this->table_element) {
7369 return 0;
7370 }
7371 $this->array_options = array();
7372
7373 if (!is_array($optionsArray)) {
7374 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
7375 if (!isset($extrafields) || !is_object($extrafields)) {
7376 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
7377 $extrafields = new ExtraFields($this->db);
7378 }
7379
7380 // Load array of extrafields for elementype = $this->table_element
7381 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
7382 $extrafields->fetch_name_optionals_label($this->table_element);
7383 }
7384 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
7385 } else {
7386 global $extrafields;
7387 dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
7388 }
7389
7390 $table_element = $this->table_element;
7391 if ($table_element == 'categorie') {
7392 $table_element = 'categories'; // For compatibility
7393 }
7394
7395 // Request to get complementary values
7396 if (is_array($optionsArray) && count($optionsArray) > 0) {
7397 $sql = "SELECT rowid";
7398 foreach ($optionsArray as $name => $label) {
7399 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || (!in_array($extrafields->attributes[$this->table_element]['type'][$name], ['separate', 'point', 'multipts', 'linestrg','polygon']))) {
7400 $sql .= ", ".$this->db->sanitize($name);
7401 }
7402 // use geo sql function to read as text
7403 if (!empty($extrafields->attributes[$this->table_element]['type'][$name]) && in_array($extrafields->attributes[$this->table_element]['type'][$name], array('point', 'multipts', 'linestrg', 'polygon'))) {
7404 // TODO Add an abstraction method in the database driver
7405 $sql .= ", ST_AsWKT(".$this->db->sanitize($name).") as ".$this->db->sanitize($name);
7406 }
7407 }
7408 $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
7409 $sql .= " WHERE fk_object = ".((int) $rowid);
7410
7411 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
7412 $resql = $this->db->query($sql);
7413 if ($resql) {
7414 $numrows = $this->db->num_rows($resql);
7415 if ($numrows) {
7416 $tab = $this->db->fetch_array($resql);
7417 foreach ($tab as $key => $value) {
7418 // 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)
7419 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
7420 // we can add this attribute to object
7421 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
7422 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
7423 $this->array_options["options_".$key] = $this->db->jdate($value);
7424 } else {
7425 $this->array_options["options_".$key] = $value;
7426 }
7427
7428 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
7429 }
7430 if (!empty($extrafields->attributes[$this->table_element]['type'][$key]) && $extrafields->attributes[$this->table_element]['type'][$key] == 'password') {
7431 if (!empty($value) && preg_match('/^dolcrypt:/', $value)) {
7432 $this->array_options["options_".$key] = dolDecrypt($value);
7433 }
7434 }
7435 }
7436 } else {
7441 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
7442 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
7443 $this->array_options['options_' . $key] = null;
7444 }
7445 }
7446 }
7447
7448 // If field is a computed field, value must become result of compute (regardless of whether a row exists
7449 // in the element's extrafields table)
7450 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
7451 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
7452 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
7453 //var_dump($conf->disable_compute);
7454 if (empty($conf->disable_compute)) {
7455 // We set a global variable to $objectoffield so we can use it inside computed formula (must be before the assignment)
7456 global $objectoffield;
7457 $objectoffield = dol_clone($this, 2);
7458 $this->array_options['options_' . $key] = dol_eval((string) $extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
7459 }
7460 }
7461 }
7462 }
7463
7464 $this->db->free($resql);
7465
7466 if ($numrows) {
7467 return $numrows;
7468 } else {
7469 return 0;
7470 }
7471 } else {
7472 $this->errors[] = $this->db->lasterror();
7473 return -1;
7474 }
7475 }
7476 return 0;
7477 }
7478
7485 public function deleteExtraFields()
7486 {
7487 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
7488 return 0;
7489 }
7490
7491 $this->db->begin();
7492
7493 $table_element = $this->table_element;
7494 if ($table_element == 'categorie') {
7495 $table_element = 'categories'; // For compatibility
7496 }
7497
7498 dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
7499
7500 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7501
7502 $resql = $this->db->query($sql_del);
7503 if (!$resql) {
7504 $this->error = $this->db->lasterror();
7505 $this->db->rollback();
7506 return -1;
7507 } else {
7508 $this->db->commit();
7509 return 1;
7510 }
7511 }
7512
7523 public function insertExtraFields($trigger = '', $userused = null)
7524 {
7525 global $langs, $extrafields, $user;
7526
7527 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED') || empty($this->array_options)) {
7528 return 0;
7529 }
7530
7531 if (empty($userused)) {
7532 $userused = $user;
7533 }
7534
7535 $error = 0;
7536
7537 // Check parameters
7538 $langs->load('admin');
7539 if (!isset($extrafields) || !is_object($extrafields)) {
7540 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
7541 $extrafields = new ExtraFields($this->db);
7542 }
7543 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
7544
7545 // Eliminate copied source object extra fields that do not exist in target object
7546 $new_array_options = array();
7547 foreach ($this->array_options as $key => $value) {
7548 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
7549 $new_array_options[$key] = $value;
7550 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
7551 $new_array_options['options_'.$key] = $value;
7552 }
7553 }
7554
7555 foreach ($new_array_options as $key => $value) {
7556 $attributeKey = substr($key, 8); // Remove 'options_' prefix
7557 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
7558 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element]['label'][$attributeKey]);
7559 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
7560 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
7561 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
7562 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
7563 $attributeEmptyOnClone = $extrafields->attributes[$this->table_element]['emptyonclone'][$attributeKey];
7564 /*
7565 $attributeEnabled = $extrafields->attributes[$this->table_element]['enabled'][$attributeKey];
7566 $enabled = 0;
7567 if (!empty($extrafields->attributes[$this->table_element]['enabled'][$key])) {
7568 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
7569 }
7570 */
7571
7572 // If we clone, we have to clean unique extrafields to prevent duplicates.
7573 // If we clone, we have to clean extrafields having "empty on clone" option on.
7574 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
7575 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && (!empty($attributeUnique) || !empty($attributeEmptyOnClone))) {
7576 $new_array_options[$key] = null;
7577 continue;
7578 }
7579
7580 // If we create product combination, we have to clean unique extrafields to prevent duplicates.
7581 // This behaviour can be prevented by external code by changing $this->context['createproductcombination'] value in hook
7582 if (!empty($this->context['createproductcombination']) && $this->context['createproductcombination'] == 'createproductcombination' && !empty($attributeUnique)) {
7583 $new_array_options[$key] = null;
7584 continue;
7585 }
7586
7587 // Similar code than into insertExtraFields
7588 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'.
7589 $v = $this->array_options[$key];
7590 if (ExtraFields::isEmptyValue($v, $attributeType)) {
7591 $langs->load("errors");
7592 dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
7593 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
7594 return -1;
7595 }
7596 }
7597
7598 if (!empty($attrfieldcomputed)) {
7599 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
7600 global $objectoffield; // We set a global variable to $objectoffield so
7601 $objectoffield = $this; // we can use it inside the computed formula
7602 $value = dol_eval((string) $attrfieldcomputed, 1, 0, '2');
7603 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
7604 $new_array_options[$key] = $value;
7605 } else {
7606 $new_array_options[$key] = null;
7607 }
7608 continue;
7609 }
7610
7611 switch ($attributeType) {
7612 case 'int':
7613 case 'duration':
7614 case 'stars':
7615 if (!is_numeric($value) && $value != '') {
7616 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7617 return -1;
7618 } elseif ($value === '') {
7619 $new_array_options[$key] = null;
7620 }
7621 break;
7622 case 'boolean':
7623 if ($value === '' || $value === false || $value === null) {
7624 $new_array_options[$key] = null;
7625 }
7626 break;
7627 case 'price':
7628 case 'double':
7629 $value = price2num($value);
7630 if (!is_numeric($value) && $value != '') {
7631 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7632 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7633 return -1;
7634 } elseif ($value == '') {
7635 $value = null;
7636 }
7637 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
7638 $new_array_options[$key] = $value;
7639 break;
7640 /*case 'select': // Not required, we chose value='0' for undefined values
7641 if ($value=='-1')
7642 {
7643 $this->array_options[$key] = null;
7644 }
7645 break;*/
7646 case 'password':
7647 $algo = '';
7648 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
7649 // If there is an encryption choice, we use it to encrypt data before insert
7650 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
7651 $algo = reset($tmparrays);
7652 if ($algo != '') {
7653 //global $action; // $action may be 'create', 'update', 'update_extras'...
7654 //var_dump($action);
7655 //var_dump($this->oldcopy);exit;
7656 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
7657 //var_dump('algo='.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
7658 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
7659 // If old value encrypted in database is same than submitted new value, it means we don't change it, so we don't update.
7660 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7661 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
7662 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
7663 } else {
7664 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7665 }
7666 } else {
7667 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7668 }
7669 } else {
7670 // If value has changed
7671 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7672 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
7673 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
7674 } else {
7675 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7676 }
7677 } else {
7678 $new_array_options[$key] = dol_hash($this->array_options[$key], $algo);
7679 }
7680 }
7681 } else {
7682 //var_dump('jjj'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
7683 // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
7684 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options[$key])) { // dolibarr reversible encryption
7685 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
7686 } else {
7687 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7688 }
7689 }
7690 } else {
7691 // No encryption
7692 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7693 }
7694 } else { // Common usage
7695 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
7696 }
7697 break;
7698 case 'date':
7699 case 'datetime':
7700 // If data is a string instead of a timestamp, we convert it
7701 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7702 $this->array_options[$key] = strtotime($this->array_options[$key]);
7703 }
7704 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
7705 break;
7706 case 'datetimegmt':
7707 // If data is a string instead of a timestamp, we convert it
7708 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
7709 $this->array_options[$key] = strtotime($this->array_options[$key]);
7710 }
7711 $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
7712 break;
7713 case 'link':
7714 $param_list = array_keys($attributeParam['options']);
7715 // 0 : ObjectName
7716 // 1 : classPath
7717 $InfoFieldList = explode(":", $param_list[0]);
7718 dol_include_once($InfoFieldList[1]);
7719 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
7720 if ($value == '-1') { // -1 is key for no defined in combo list of objects
7721 $new_array_options[$key] = '';
7722 } elseif ($value) {
7723 $object = new $InfoFieldList[0]($this->db);
7724 '@phan-var-force CommonObject $object';
7725
7726 $objectId = 0;
7727
7728 $sqlFetchObject = "SELECT rowid FROM ".$this->db->prefix().$object->table_element;
7729 if (is_numeric($value)) {
7730 $sqlFetchObject .= " WHERE rowid = " . (int) $value;
7731 } else {
7732 $sqlFetchObject .= " WHERE ref = '" . $this->db->escape($value) . "'";
7733 }
7734
7735 $obj = $this->db->getRow($sqlFetchObject);
7736
7737 // getRow() returns an object on success, int 0 when the query succeeded but
7738 // returned no row, and false on SQL failure. Testing "!== false" let the 0
7739 // through as a success: $obj->rowid on an int is null, $res was set to 1 and
7740 // null was stored in the column while a success was reported.
7741 if (is_object($obj)) {
7742 $objectId = $obj->rowid;
7743 $res = 1;
7744 } else {
7745 $res = -1;
7746 }
7747
7748 if ($res > 0) {
7749 $new_array_options[$key] = $objectId;
7750 } else {
7751 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
7752 return -1;
7753 }
7754 }
7755 } else {
7756 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7757 }
7758 break;
7759 case 'checkbox':
7760 case 'chkbxlst':
7761 if (is_array($this->array_options[$key])) {
7762 $new_array_options[$key] = implode(',', $this->array_options[$key]);
7763 } else {
7764 $new_array_options[$key] = $this->array_options[$key];
7765 }
7766 break;
7767 }
7768 }
7769
7770 // Set array $sqlColumnValues (SQL field name in extrafield table => value)
7771 $sqlColumnValues = ['fk_object' => (int) $this->id]; // key-value pairs for the SQL INSERT or UPDATE query
7772
7773 foreach ($new_array_options as $key => $newValue) {
7774 $attributeKey = substr($key, 8); // Remove 'options_' prefix
7775 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
7776 if ($attributeType === 'separate') {
7777 // separator extrafields don't have data per object so they don't have a comlumn in the database
7778 continue;
7779 }
7780 $geoDataType = ExtraFields::$geoDataTypes[$attributeType] ?? null;
7781 // Add field of attribute
7782 if (! $geoDataType) {
7783 // not a geodata type
7784 if ($newValue != '') {
7785 $sqlColumnValues[$attributeKey] = "'".$this->db->escape($newValue)."'";
7786 } else {
7787 $sqlColumnValues[$attributeKey] = 'null';
7788 }
7789 continue;
7790 }
7791 if (empty($newValue)) {
7792 $sqlColumnValues[$attributeKey] = 'null';
7793 continue;
7794 }
7795 if (preg_match('/error/i', $newValue)) {
7796 dol_syslog('Bad syntax string for '.$geoDataType['shortname'].' '.$newValue.' to generate SQL request', LOG_WARNING);
7797 $sqlColumnValues[$attributeKey] = 'null';
7798 continue;
7799 }
7800
7801 // Geodata type: Text must be a WKT string. Examples:
7802 // - point => "POINT(15 20)"
7803 // - multipts => "MULTIPOINT(0 0, 20 20, 60 60)"
7804 // - linestrg => "LINESTRING(0 0, 10 10, 20 25, 50 60)"
7805 // - polygon => "POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))"
7806 $sqlColumnValues[$attributeKey] = $geoDataType['ST_Function']."('".$this->db->escape($newValue)."')"; // @phan-suppress-current-line SqlInjection
7807 }
7808
7809 $this->db->begin();
7810
7811 $table_element = $this->table_element;
7812 if ($table_element == 'categorie') {
7813 $table_element = 'categories'; // For compatibility
7814 }
7815 $extrafieldsTable = $this->db->prefix() . $table_element . '_extrafields';
7816
7817 dol_syslog(get_class($this)."::insertExtraFields update or insert record line", LOG_DEBUG);
7818
7819 $linealreadyfound = 0;
7820 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7821 $resql = $this->db->query($sql);
7822 if ($resql) {
7823 $tmpobj = $this->db->fetch_object($resql);
7824 if ($tmpobj) {
7825 $linealreadyfound = $tmpobj->nb;
7826 }
7827 }
7828
7829 // if the extrafields row already exists for the object, we update it
7830 if ($linealreadyfound) {
7831 array_shift($sqlColumnValues); // drop the 'fk_object' column because its value won't change
7832 if (empty($sqlColumnValues)) {
7833 // No column of the target element to update. This happens when the object was created from
7834 // another element whose extrafields do not exist on this element (e.g. invoice created from a
7835 // shipment: the source line extrafields are copied into array_options but none match facturedet).
7836 // The existing row is already correct, so there is nothing to update: avoid an empty "SET" clause
7837 // that would produce an invalid SQL statement.
7838 $this->db->commit();
7839 return 1;
7840 }
7841 $sqlColumnValueString = implode(
7842 ',',
7847 array_map(function ($key) use ($sqlColumnValues) {
7848 return "{$key} = {$sqlColumnValues[$key]}";
7849 }, array_keys($sqlColumnValues))
7850 );
7851 $sql = "UPDATE {$extrafieldsTable} SET {$sqlColumnValueString} WHERE fk_object = ".((int) $this->id);
7852 } else {
7853 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
7854 $extrafieldsRequiredOnOtherEntities = $extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] ?? array();
7855 foreach ($extrafieldsRequiredOnOtherEntities as $key => $extrafieldType) {
7856 if (isset($sqlColumnValues[$key])) {
7857 // extrafield value already provided: no need to add it
7858 continue;
7859 }
7860 // default value: empty string, except for 'int', 'double' and 'price'
7861 $sqlColumnValues[$key] = "''";
7862 if (in_array($extrafieldType, array('int', 'double', 'price'))) {
7863 $sqlColumnValues[$key] = 0;
7864 }
7865 }
7866 $sqlColumns = implode(',', array_keys($sqlColumnValues));
7867 $sqlValues = implode(',', array_values($sqlColumnValues));
7868 $sql = "INSERT INTO {$extrafieldsTable} ({$sqlColumns}) VALUES ({$sqlValues})";
7869 }
7870
7871 $resql = $this->db->query($sql);
7872 if (!$resql) {
7873 $this->error = $this->db->lasterror();
7874 $error++;
7875 }
7876
7877 // Update also the user of last modification in parent table
7878 if (!$error && !empty($this->fields['fk_user_modif'])) { // @phan-suppress-current-line PhanTypeMismatchProperty
7879 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
7880 $sql .= " SET fk_user_modif = ".(int) $userused->id;
7881 $sql .= " WHERE ".(empty($this->table_rowid) ? 'rowid' : $this->db->sanitize($this->table_rowid))." = ".((int) $this->id);
7882 $this->db->query($sql);
7883 }
7884
7885 if (!$error && $trigger) {
7886 // Call trigger
7887 $this->context = array('extrafieldaddupdate' => 1);
7888 $result = $this->call_trigger($trigger, $userused);
7889 if ($result < 0) {
7890 $error++;
7891 }
7892 // End call trigger
7893 }
7894
7895 if ($error) {
7896 $this->db->rollback();
7897 return -1;
7898 } else {
7899 $this->db->commit();
7900 return 1;
7901 }
7902 }
7903
7915 public function insertExtraLanguages($trigger = '', $userused = null)
7916 {
7917 global $langs, $user;
7918
7919 if (empty($userused)) {
7920 $userused = $user;
7921 }
7922
7923 $error = 0;
7924
7925 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
7926 return 0; // For avoid conflicts if trigger used
7927 }
7928
7929 if (is_array($this->array_languages)) {
7930 $new_array_languages = $this->array_languages;
7931
7932 foreach ($new_array_languages as $key => $value) {
7933 $attributeKey = $key;
7934 $attributeType = $this->fields[$attributeKey]['type'];
7935 $attributeLabel = $this->fields[$attributeKey]['label'];
7936
7937 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
7938 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
7939
7940 switch ($attributeType) {
7941 case 'int':
7942 if (is_array($value) || (!is_numeric($value) && $value != '')) {
7943 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
7944 return -1;
7945 } elseif ($value == '') { // @phan-suppress-current-line PhanTypeComparisonFromArray
7946 $new_array_languages[$key] = null;
7947 }
7948 break;
7949 case 'double':
7950 $value = price2num((string) $value);
7951 if (!is_numeric($value) && $value != '') {
7952 dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7953 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
7954 return -1;
7955 } elseif ($value == '') {
7956 $new_array_languages[$key] = null;
7957 } else {
7958 $new_array_languages[$key] = $value;
7959 }
7960 break;
7961 /*case 'select': // Not required, we chose value='0' for undefined values
7962 if ($value=='-1')
7963 {
7964 $this->array_options[$key] = null;
7965 }
7966 break;*/
7967 }
7968 }
7969
7970 $this->db->begin();
7971
7972 $table_element = $this->table_element;
7973 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
7974 $table_element = 'categories'; // For compatibility
7975 }
7976
7977 dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
7978
7979 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
7980 foreach ($langcodearray as $langcode => $value) {
7981 $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
7982 $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
7983 $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
7984 $this->db->query($sql_del);
7985
7986 if ($value !== '') {
7987 $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
7988 $sql .= ") VALUES (".((int) $this->id).", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
7989 $sql .= ")";
7990
7991 $resql = $this->db->query($sql);
7992 if (!$resql) {
7993 $this->error = $this->db->lasterror();
7994 $error++;
7995 break;
7996 }
7997 }
7998 }
7999 }
8000
8001 if (!$error && $trigger) {
8002 // Call trigger
8003 $this->context = array('extralanguagesaddupdate' => 1);
8004 $result = $this->call_trigger($trigger, $userused);
8005 if ($result < 0) {
8006 $error++;
8007 }
8008 // End call trigger
8009 }
8010
8011 if ($error) {
8012 $this->db->rollback();
8013 return -1;
8014 } else {
8015 $this->db->commit();
8016 return 1;
8017 }
8018 } else {
8019 return 0;
8020 }
8021 }
8022
8033 public function updateExtraField($key, $trigger = null, $userused = null)
8034 {
8035 global $langs, $user, $extrafields, $hookmanager;
8036
8037 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
8038 return 0;
8039 }
8040
8041 if (empty($userused)) {
8042 $userused = $user;
8043 }
8044
8045 $error = 0;
8046
8047 if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
8048 // Check parameters
8049 $langs->load('admin');
8050 if (!isset($extrafields) || !is_object($extrafields)) {
8051 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
8052 $extrafields = new ExtraFields($this->db);
8053 }
8054 $extrafields->fetch_name_optionals_label($this->table_element);
8055 if (!isset($extrafields->attributes[$this->table_element]['type'][$key])) {
8056 // Extrafield not defined for this object type: nothing to update
8057 return 0;
8058 }
8059 $value = $this->array_options["options_".$key];
8060
8061 $attributeKey = $key;
8062 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
8063 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
8064 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
8065 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
8066 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
8067 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
8068 //$attributeEnabled = $extrafields->attributes[$this->table_element]['enabled'][$attributeKey];
8069
8070 // Similar code than into insertExtraFields
8071 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'.
8072 $mandatorypb = false;
8073 if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
8074 $mandatorypb = true;
8075 }
8076 if ($this->array_options["options_".$key] === '') {
8077 $mandatorypb = true;
8078 }
8079 if ($mandatorypb) {
8080 $langs->load("errors");
8081 dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
8082 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
8083 return -1;
8084 }
8085 }
8086
8087 // $new_array_options will be used for direct update, so must contains formatted data for the UPDATE.
8088 $new_array_options = $this->array_options;
8089
8090 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
8091 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
8092 if (!empty($attrfieldcomputed)) {
8093 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
8094 global $objectoffield; // We set a global variable to $objectoffield so
8095 $objectoffield = $this; // we can use it inside the computed formula
8096 $value = dol_eval((string) $attrfieldcomputed, 1, 0, '2');
8097 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
8098
8099 $new_array_options["options_".$key] = $value;
8100
8101 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8102 } else {
8103 $new_array_options["options_".$key] = null;
8104
8105 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8106 }
8107 }
8108
8109 switch ($attributeType) {
8110 case 'int':
8111 if (!is_numeric($value) && $value != '') {
8112 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
8113 return -1;
8114 } elseif ($value === '') {
8115 $new_array_options["options_".$key] = null;
8116
8117 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8118 }
8119 break;
8120 case 'price':
8121 case 'double':
8122 $value = price2num($value);
8123 if (!is_numeric($value) && $value != '') {
8124 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
8125 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
8126 return -1;
8127 } elseif ($value === '') {
8128 $value = null;
8129 }
8130 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
8131 $new_array_options["options_".$key] = $value;
8132
8133 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8134 break;
8135 /*case 'select': // Not required, we chose value='0' for undefined values
8136 if ($value=='-1')
8137 {
8138 $new_array_options["options_".$key] = $value;
8139
8140 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8141 }
8142 break;*/
8143 case 'password':
8144 $algo = '';
8145 if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
8146 // If there is an encryption choice, we use it to encrypt data before insert
8147 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
8148 $algo = reset($tmparrays);
8149 if ($algo != '') {
8150 //global $action; // $action may be 'create', 'update', 'update_extras'...
8151 //var_dump($action);
8152 //var_dump($this->oldcopy);exit;
8153 //var_dump($key.' '.$this->array_options["options_".$key].' '.$algo);
8154 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
8155 //var_dump($this->oldcopy->array_options["options_".$key]); var_dump($this->array_options["options_".$key]);
8156 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.
8157 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
8158 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
8159 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
8160 } else {
8161 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
8162 }
8163 } else {
8164 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
8165 }
8166 } else {
8167 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
8168 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
8169 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]);
8170 } else {
8171 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
8172 }
8173 } else {
8174 $new_array_options["options_".$key] = dol_hash($this->array_options["options_".$key], $algo);
8175 }
8176 }
8177 } else {
8178 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { // dolibarr reversible encryption
8179 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
8180 } else {
8181 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
8182 }
8183 }
8184 } else {
8185 // No encryption
8186 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
8187 }
8188 } else { // Common usage
8189 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
8190 }
8191
8192 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8193 break;
8194 case 'date':
8195 case 'datetime':
8196 if (empty($this->array_options["options_".$key])) {
8197 $new_array_options["options_".$key] = null;
8198
8199 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8200 } else {
8201 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
8202 }
8203 break;
8204 case 'datetimegmt':
8205 if (empty($this->array_options["options_".$key])) {
8206 $new_array_options["options_".$key] = null;
8207
8208 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8209 } else {
8210 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
8211 }
8212 break;
8213 case 'boolean':
8214 if (empty($this->array_options["options_".$key])) {
8215 $new_array_options["options_".$key] = null;
8216
8217 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8218 }
8219 break;
8220 case 'link':
8221 if ($this->array_options["options_".$key] === '') {
8222 $new_array_options["options_".$key] = null;
8223
8224 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8225 }
8226 break;
8227 /*
8228 case 'link':
8229 $param_list = array_keys($attributeParam['options']);
8230 // 0 : ObjectName
8231 // 1 : classPath
8232 $InfoFieldList = explode(":", $param_list[0]);
8233 dol_include_once($InfoFieldList[1]);
8234 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
8235 {
8236 if ($value == '-1') // -1 is key for no defined in combo list of objects
8237 {
8238 $new_array_options[$key] = '';
8239 } elseif ($value) {
8240 $object = new $InfoFieldList[0]($this->db);
8241 if (is_numeric($value)) $res = $object->fetch($value); // Common case
8242 else $res = $object->fetch(0, $value); // For compatibility
8243
8244 if ($res > 0) $new_array_options[$key] = $object->id;
8245 else {
8246 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
8247 $this->db->rollback();
8248 return -1;
8249 }
8250 }
8251 } else {
8252 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
8253 }
8254 break;
8255 */
8256 case 'checkbox':
8257 case 'chkbxlst':
8258 $new_array_options = array();
8259 if (is_array($this->array_options["options_".$key])) {
8260 $new_array_options["options_".$key] = implode(',', $this->array_options["options_".$key]);
8261 } else {
8262 $new_array_options["options_".$key] = $this->array_options["options_".$key];
8263 }
8264
8265 $this->array_options["options_".$key] = $new_array_options["options_".$key];
8266 break;
8267 }
8268
8269 $this->db->begin();
8270
8271 $linealreadyfound = 0;
8272
8273 // 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)
8274 $table_element = $this->table_element;
8275 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
8276 $table_element = 'categories'; // For compatibility
8277 }
8278
8279 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
8280 $resql = $this->db->query($sql);
8281 if ($resql) {
8282 $tmpobj = $this->db->fetch_object($resql);
8283 if ($tmpobj) {
8284 $linealreadyfound = $tmpobj->nb;
8285 }
8286 }
8287
8288 //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit;
8289 if ($linealreadyfound) {
8290 $sanitizedGeoDataType = ExtraFields::$geoDataTypes[$attributeType] ?? null; // @phan-suppress-current-line SqlInjection
8291 if ($this->array_options["options_".$key] === null) {
8292 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($table_element)."_extrafields";
8293 $sql .= " SET ".$this->db->sanitize($key)." = null";
8294 } elseif (!empty($sanitizedGeoDataType['ST_Function'])) {
8295 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($table_element)."_extrafields";
8296 $sql .= " SET ".$this->db->sanitize($key)." = ".$this->db->sanitize($sanitizedGeoDataType['ST_Function'])."('".$this->db->escape($this->array_options["options_".$key])."')";
8297 } else {
8298 // TODO What about if field is type int or float ($attributeType = price, int, ...) ?
8299 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($table_element)."_extrafields";
8300 $sql .= " SET ".$this->db->sanitize($key)." = '".$this->db->escape($new_array_options["options_".$key])."'";
8301 }
8302 $sql .= " WHERE fk_object = ".((int) $this->id);
8303
8304 $resql = $this->db->query($sql);
8305 if (!$resql) {
8306 $error++;
8307 $this->error = $this->db->lasterror();
8308 }
8309 } else {
8310 $result = $this->insertExtraFields('', $user);
8311 if ($result < 0) {
8312 $error++;
8313 }
8314 }
8315
8316 // Update also the user of last modification in parent table
8317 if (!$error && !empty($this->fields['fk_user_modif'])) {
8318 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
8319 $sql .= " SET fk_user_modif = ".(int) $userused->id;
8320 $sql .= " WHERE ".(empty($this->table_rowid) ? 'rowid' : $this->db->sanitize($this->table_rowid))." = ".((int) $this->id);
8321 $this->db->query($sql);
8322 }
8323
8324 if (!$error) {
8325 $parameters = array('key' => $key);
8326 global $action;
8327 $reshook = $hookmanager->executeHooks('updateExtraFieldBeforeCommit', $parameters, $this, $action);
8328 if ($reshook < 0) {
8329 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
8330 }
8331 }
8332
8333 if (!$error && $trigger) {
8334 // Call trigger
8335 $this->context = array('extrafieldupdate' => 1);
8336 $result = $this->call_trigger($trigger, $userused);
8337 if ($result < 0) {
8338 $error++;
8339 }
8340 // End call trigger
8341 }
8342
8343 if ($error) {
8344 dol_syslog(__METHOD__.$this->error, LOG_ERR);
8345 $this->db->rollback();
8346 return -1;
8347 } else {
8348 $this->db->commit();
8349 return 1;
8350 }
8351 } else {
8352 return 0;
8353 }
8354 }
8355
8362 public function getExtraField($key)
8363 {
8364 return $this->array_options['options_'.$key] ?? null;
8365 }
8366
8374 public function setExtraField($key, $value)
8375 {
8376 $this->array_options['options_'.$key] = $value;
8377 }
8378
8389 public function updateExtraLanguages($key, $trigger = null, $userused = null)
8390 {
8391 global $user;
8392
8393 if (empty($userused)) {
8394 $userused = $user;
8395 }
8396
8397 //$error = 0;
8398
8399 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
8400 return 0; // For avoid conflicts if trigger used
8401 }
8402
8403 return 0;
8404 }
8405
8406
8421 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
8422 {
8423 global $conf, $langs, $form;
8424
8425
8426 // 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...)
8427
8428 if (!is_object($form)) {
8429 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
8430 $form = new Form($this->db);
8431 }
8432
8433 if (!empty($this->fields)) {
8434 $val = $this->fields[$key];
8435 }
8436
8437 // Validation tests and output
8438 $fieldValidationErrorMsg = '';
8439 $validationClass = '';
8440 $fieldValidationErrorMsg = $this->getFieldError($key);
8441 if (!empty($fieldValidationErrorMsg)) {
8442 $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
8443 } else {
8444 $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
8445 }
8446
8447 //$valuemultiselectinput = array();
8448 $out = '';
8449 $type = '';
8450 $isDependList = 0;
8451 $param = array();
8452 $param['options'] = array();
8453 $reg = array();
8454 // @phan-suppress-next-line PhanTypeMismatchProperty
8455 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
8456 // Because we work on extrafields
8457 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8458 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
8459 $type = 'link';
8460 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8461 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8462 $type = 'link';
8463 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
8464 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
8465 $type = 'link';
8466 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8467 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
8468 $type = 'sellist';
8469 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8470 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8471 $type = 'sellist';
8472 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
8473 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
8474 $type = 'sellist';
8475 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
8476 $param['options'] = array($reg[1] => 'N');
8477 $type = 'chkbxlst';
8478 } elseif (preg_match('/varchar\‍((\d+)\‍)/', $val['type'], $reg)) {
8479 $param['options'] = array();
8480 $type = 'varchar';
8481 $size = $reg[1];
8482 } elseif (preg_match('/varchar/', $val['type'])) {
8483 $param['options'] = array();
8484 $type = 'varchar';
8485 } elseif (preg_match('/stars\‍((\d+)\‍)/', $val['type'], $reg)) {
8486 $param['options'] = array();
8487 $type = 'stars';
8488 $size = $reg[1];
8489 } else {
8490 $param['options'] = array();
8491 $type = $this->fields[$key]['type'];
8492 }
8493 //var_dump($type); var_dump($param['options']);
8494
8495 // Special case that force options and type ($type can be integer, varchar, ...)
8496 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
8497 $param['options'] = $this->fields[$key]['arrayofkeyval'];
8498 // Special case that prevent to force $type to have multiple input @phan-suppress-next-line PhanTypeMismatchProperty
8499 if (empty($this->fields[$key]['multiinput'])) {
8500 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
8501 }
8502 }
8503
8504 $label = $this->fields[$key]['label'];
8505 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
8506 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
8507 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
8508 // @phan-suppress-next-line PhanTypeMismatchProperty
8509 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
8510 // @phan-suppress-next-line PhanTypeMismatchProperty
8511 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
8512 // @phan-suppress-next-line PhanTypeMismatchProperty
8513 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
8514 // @phan-suppress-next-line PhanTypeMismatchProperty
8515 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
8516 // @phan-suppress-next-line PhanTypeMismatchProperty
8517 $placeholder = (!empty($this->fields[$key]['placeholder']) ? $this->fields[$key]['placeholder'] : 0);
8518
8519 // @phan-suppress-next-line PhanTypeMismatchProperty
8520 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
8521 // @phan-suppress-next-line PhanTypeMismatchProperty
8522 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
8523 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
8524
8525 $objectid = $this->id;
8526
8527 if ($computed) {
8528 if (!preg_match('/^search_/', $keyprefix)) {
8529 return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
8530 } else {
8531 return '';
8532 }
8533 }
8534
8535 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
8536 if (empty($morecss) && !empty($val['css'])) {
8537 $morecss = $val['css'];
8538 } elseif (empty($morecss)) {
8539 if ($type == 'date') {
8540 $morecss = 'minwidth100imp';
8541 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
8542 $morecss = 'minwidth200imp';
8543 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
8544 $morecss = 'maxwidth75';
8545 } elseif ($type == 'url') {
8546 $morecss = 'minwidth400';
8547 } elseif ($type == 'boolean') {
8548 $morecss = '';
8549 } else {
8550 if (is_numeric($size) && round((float) $size) < 12) {
8551 $morecss = 'minwidth100';
8552 } elseif (is_numeric($size) && round((float) $size) <= 48) {
8553 $morecss = 'minwidth200';
8554 } else {
8555 $morecss = 'minwidth400';
8556 }
8557 }
8558 }
8559
8560 // Add validation state class
8561 if (!empty($validationClass)) {
8562 $morecss .= $validationClass;
8563 }
8564
8565 if (in_array($type, array('date'))) {
8566 $tmp = explode(',', $size);
8567 $newsize = $tmp[0];
8568 $showtime = 0;
8569
8570 // Do not show current date when field not required (see selectDate() method)
8571 if (!$required && $value == '') {
8572 $value = '-1';
8573 }
8574
8575 // TODO Must also support $moreparam
8576 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
8577 } elseif (in_array($type, array('datetime'))) {
8578 $tmp = explode(',', $size);
8579 $newsize = $tmp[0];
8580 $showtime = 1;
8581
8582 // Do not show current date when field not required (see selectDate() method)
8583 if (!$required && $value == '') {
8584 $value = '-1';
8585 }
8586
8587 // TODO Must also support $moreparam
8588 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
8589 } elseif (in_array($type, array('duration'))) {
8590 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
8591 } elseif (in_array($type, array('int', 'integer'))) {
8592 $tmp = explode(',', $size);
8593 $newsize = $tmp[0];
8594 $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' : '').'>';
8595 } elseif (in_array($type, array('real'))) {
8596 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
8597 } elseif (preg_match('/varchar/', (string) $type)) {
8598 $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' : '').'>';
8599 } elseif ($type == 'phone' && !preg_match('/search_/', $keyprefix)) {
8600 $out = $form->showPhoneInput($value, $keyprefix.$key.$keysuffix, !empty($this->country_id) ? $this->country_id : 0);
8601 } elseif (in_array($type, array('email', 'mail', 'url', 'ip'))) {
8602 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
8603 } elseif (preg_match('/^text/', (string) $type)) {
8604 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
8605 if (!empty($param['options'])) {
8606 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
8607 //var_dump($param['options']);
8608 $out .= $form->selectarray($keyprefix.$key.$keysuffix."_multiinput", $param['options'], '', 1, 0, 0, "flat maxwidthonphone".$morecss);
8609 $out .= '<input id="'.$keyprefix.$key.$keysuffix.'_multiinputadd" type="button" class="button" value="'.$langs->trans("Add").'">';
8610 $out .= "<script>";
8611 $out .= '
8612 function handlemultiinputdisabling(htmlname){
8613 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
8614 multiinput = $("#"+htmlname+"_multiinput");
8615 multiinput.find("option").each(function(){
8616 tmpval = $("#"+htmlname).val();
8617 tmpvalarray = tmpval.split("\n");
8618 valtotest = $(this).val();
8619 if(tmpvalarray.includes(valtotest)){
8620 $(this).prop("disabled",true);
8621 } else {
8622 if($(this).prop("disabled") == true){
8623 console.log(valtotest)
8624 $(this).prop("disabled", false);
8625 }
8626 }
8627 });
8628 }
8629
8630 $(document).ready(function () {
8631 $("#'.$keyprefix.$key.$keysuffix.'_multiinputadd").on("click",function() {
8632 tmpval = $("#'.$keyprefix.$key.$keysuffix.'").val();
8633 tmpvalarray = tmpval.split(",");
8634 valtotest = $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val();
8635 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
8636 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.'");
8637 if(tmpval == ""){
8638 tmpval = valtotest;
8639 } else {
8640 tmpval = tmpval + "\n" + valtotest;
8641 }
8642 $("#'.$keyprefix.$key.$keysuffix.'").val(tmpval);
8643 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
8644 $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val(-1);
8645 } else {
8646 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.'");
8647 }
8648 });
8649 $("#'.$keyprefix.$key.$keysuffix.'").on("change",function(){
8650 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
8651 });
8652 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
8653 })';
8654 $out .= "</script>";
8655 $value = str_replace(',', "\n", $value);
8656 }
8657 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
8658 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
8659 $out .= (string) $doleditor->Create(1, '', true, '', '', '', $morecss);
8660 } else {
8661 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
8662 }
8663 } elseif (preg_match('/^html/', (string) $type)) {
8664 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
8665 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
8666 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
8667 $out = (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
8668 } else {
8669 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
8670 }
8671 } elseif ($type == 'boolean') {
8672 $checked = '';
8673 if (!empty($value)) {
8674 $checked = ' checked value="1" ';
8675 } else {
8676 $checked = ' value="1" ';
8677 }
8678 $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
8679 } elseif ($type == 'price') {
8680 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
8681 $value = price($value);
8682 }
8683 $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>';
8684 } elseif ($type == 'stars') {
8685 $out = '<input type="hidden" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
8686 $out .= '<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.'_selection">';
8687 $i = 1;
8688 while ($i <= $size) {
8689 $out .= '<span class="star" data-value="'.$i.'">'.img_picto('', 'fontawesome_star_fas').'</span>';
8690 $i++;
8691 }
8692 $out .= '</div>';
8693 $out .= '<script>
8694 jQuery(function($) { /* commonobject.class.php 1 */
8695 let container = $("#'.$keyprefix.$key.$keysuffix.'_selection");
8696 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.'").val()) || 0;
8697 container.find(".star").each(function() {
8698 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8699 });
8700 container.find(".star").on("mouseover", function() {
8701 let selectedStar = $(this).data("value");
8702 container.find(".star").each(function() {
8703 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8704 });
8705 });
8706 container.on("mouseout", function() {
8707 container.find(".star").each(function() {
8708 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8709 });
8710 });
8711 container.find(".star").off("click").on("click", function() {
8712 selectedStars = $(this).data("value");
8713 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.'").val() == 1) {
8714 selectedStars = 0;
8715 }
8716 $("#'.$keyprefix.$key.$keysuffix.'").val(selectedStars);
8717 container.find(".star").each(function() {
8718 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8719 });
8720 });
8721 });
8722 </script>';
8723 } elseif (preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
8724 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
8725 $value = price($value);
8726 }
8727 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
8728 } elseif ($type == 'select') { // combo list
8729 $out = '';
8730 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8731 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
8732 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8733 }
8734
8735 $tmpselect = '';
8736 $nbchoice = 0;
8737
8738 foreach ($param['options'] as $keyb => $valb) {
8739 if ((string) $keyb == '') {
8740 continue;
8741 }
8742 if (strpos($valb, "|") !== false) {
8743 list($valb, $parent) = explode('|', $valb);
8744 }
8745 $nbchoice++;
8746 $tmpselect .= '<option value="'.$keyb.'"';
8747 $tmpselect .= (((string) $value == (string) $keyb) ? ' selected' : '');
8748 if (!empty($parent)) {
8749 $isDependList = 1;
8750 }
8751 $tmpselect .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
8752 $tmpselect .= '>'.$langs->trans($valb).'</option>';
8753 }
8754
8755 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
8756 if ((!isset($this->fields[$key]['default'])) || empty($this->fields[$key]['notnull']) || ($this->fields[$key]['notnull'] != 1) || $nbchoice >= 2) {
8757 $out .= '<option value="0">&nbsp;</option>';
8758 }
8759 $out .= $tmpselect;
8760 $out .= '</select>';
8761 } elseif ($type == 'sellist') {
8762 $out = '';
8763 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
8764 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
8765 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
8766 }
8767
8768 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
8769 if (is_array($param['options'])) {
8770 $tmpparamoptions = array_keys($param['options']);
8771 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
8772
8773 $InfoFieldList = explode(":", $paramoptions[0], 5);
8774 // 0 : tableName
8775 // 1 : label field name
8776 // 2 : key fields name (if different of rowid)
8777 // optional parameters...
8778 // 3 : key field parent (for dependent lists). How this is used ?
8779 // 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".
8780 // 5 : string category type. This replace the filter.
8781 // 6 : ids categories list separated by comma for category root. This replace the filter.
8782 // 7 : sort field
8783
8784 // If there is filter
8785 if (! empty($InfoFieldList[4])) {
8786 $pos = 0;
8787 $parenthesisopen = 0;
8788 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
8789 if (substr($InfoFieldList[4], $pos, 1) == '(') {
8790 $parenthesisopen++;
8791 }
8792 if (substr($InfoFieldList[4], $pos, 1) == ')') {
8793 $parenthesisopen--;
8794 }
8795 $pos++;
8796 }
8797 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
8798 $tmpafter = substr($InfoFieldList[4], $pos + 1);
8799 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
8800 $InfoFieldList[4] = $tmpbefore;
8801 if ($tmpafter !== '') {
8802 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
8803 }
8804 //var_dump($InfoFieldList);
8805
8806 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
8807 $reg = array();
8808 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
8809 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
8810 }
8811
8812 //var_dump($InfoFieldList);
8813 }
8814
8815 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
8816
8817 $parentName = '';
8818 $parentField = '';
8819
8820 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
8821
8822 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8823 if (strpos($InfoFieldList[4], 'extra.') !== false) {
8824 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
8825 } else {
8826 $keyList = $InfoFieldList[2].' as rowid';
8827 }
8828 }
8829 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8830 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
8831 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra.') !== false) {
8832 $keyList .= ', main.'.$parentField;
8833 } else {
8834 $keyList .= ', '.$parentField;
8835 }
8836 }
8837
8838 $filter_categorie = false;
8839 if (count($InfoFieldList) > 5) {
8840 if ($InfoFieldList[0] == 'categorie') {
8841 $filter_categorie = true;
8842 }
8843 }
8844
8845 if (!$filter_categorie) {
8846 $fields_label = isset($InfoFieldList[1]) ? explode('|', $InfoFieldList[1]) : array();
8847 if (!empty($fields_label)) {
8848 $keyList .= ', ';
8849 $keyList .= implode(', ', $fields_label);
8850 }
8851
8852 $sqlwhere = '';
8853 $sql = "SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
8854 $sql .= " FROM " . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
8855
8856 if (!empty($InfoFieldList[4])) {
8857 // can use SELECT request
8858 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
8859 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
8860 }
8861
8862 // current object id can be use into filter
8863 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
8864 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
8865 } else {
8866 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
8867 }
8868
8869 // We have to join on extrafield table
8870 $errstr = '';
8871 if (strpos($InfoFieldList[4], 'extra') !== false) {
8872 $sql .= " as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . "_extrafields as extra";
8873 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8874 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8875 } else {
8876 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
8877 }
8878 } else {
8879 $sqlwhere .= ' WHERE 1=1';
8880 }
8881
8882 // Add Usf filter on second line
8883 /*
8884 if ($Usf) {
8885 $errorstr = '';
8886 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
8887 if (!$errorstr) {
8888 $sqlwhere .= $sqlusf;
8889 } else {
8890 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
8891 }
8892 }
8893 */
8894
8895 // Some tables may have field, some other not. For the moment we disable it.
8896 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
8897 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
8898 }
8899 $sql .= $sqlwhere;
8900
8901 // Note: $InfoFieldList can be 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:Sortfield]]]]]]'
8902 if (isset($InfoFieldList[7]) && preg_match('/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
8903 $sql .= " ORDER BY ".$this->db->sanitize($InfoFieldList[7]);
8904 } else {
8905 $sql .= " ORDER BY ".$this->db->sanitize(implode(', ', $fields_label));
8906 }
8907 $sql .= ' LIMIT ' . getDolGlobalInt('MAIN_EXTRAFIELDS_LIMIT_SELLIST_SQL', 1000);
8908 // print $sql;
8909
8910 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
8911 $resql = $this->db->query($sql);
8912 if ($resql) {
8913 $out .= '<option value="0">&nbsp;</option>';
8914 $num = $this->db->num_rows($resql);
8915 $i = 0;
8916 while ($i < $num) {
8917 $labeltoshow = '';
8918 $obj = $this->db->fetch_object($resql);
8919
8920 // Several field into label (eq table:code|libelle:rowid)
8921 $notrans = false;
8922 $fields_label = explode('|', $InfoFieldList[1]);
8923 if (count($fields_label) > 1) {
8924 $notrans = true;
8925 foreach ($fields_label as $field_toshow) {
8926 $labeltoshow .= $obj->$field_toshow . ' ';
8927 }
8928 } else {
8929 $labeltoshow = $obj->{$InfoFieldList[1]};
8930 }
8931 $labeltoshow = dol_trunc($labeltoshow, 45);
8932
8933 if ($value == $obj->rowid) {
8934 foreach ($fields_label as $field_toshow) {
8935 $translabel = $langs->trans($obj->$field_toshow);
8936 if ($translabel != $obj->$field_toshow) {
8937 $labeltoshow = dol_trunc($translabel) . ' ';
8938 } else {
8939 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
8940 }
8941 }
8942 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
8943 } else {
8944 if (!$notrans) {
8945 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8946 if ($translabel != $obj->{$InfoFieldList[1]}) {
8947 $labeltoshow = dol_trunc($translabel, 18);
8948 } else {
8949 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
8950 }
8951 }
8952 if (empty($labeltoshow)) {
8953 $labeltoshow = '(not defined)';
8954 }
8955 if ($value == $obj->rowid) {
8956 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
8957 }
8958
8959 if (!empty($InfoFieldList[3]) && $parentField) {
8960 $parent = $parentName . ':' . $obj->{$parentField};
8961 $isDependList = 1;
8962 }
8963
8964 $out .= '<option value="' . $obj->rowid . '"';
8965 $out .= ($value == $obj->rowid ? ' selected' : '');
8966 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
8967 $out .= '>' . $labeltoshow . '</option>';
8968 }
8969
8970 $i++;
8971 }
8972 $this->db->free($resql);
8973 } else {
8974 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
8975 }
8976 } else {
8977 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
8978 $categcode = $InfoFieldList[5];
8979 if (is_numeric($categcode)) { // deprecated: must use the category code instead of id. For backward compatibility.
8980 $tmpcategory = new Categorie($this->db);
8981 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
8982 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
8983 }
8984
8985 $data = $form->select_all_categories($categcode, '', 'parent', 64, $InfoFieldList[6], 1, 1);
8986 $out .= '<option value="0">&nbsp;</option>';
8987 foreach ($data as $data_key => $data_value) {
8988 $out .= '<option value="' . $data_key . '"';
8989 $out .= ($value == $data_key ? ' selected' : '');
8990 $out .= '>' . $data_value . '</option>';
8991 }
8992 }
8993 }
8994 $out .= '</select>';
8995 } elseif ($type == 'checkbox') {
8996 $value_arr = explode(',', $value);
8997 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, 0, 0, $morecss, 0, '100%');
8998 } elseif ($type == 'radio') {
8999 $out = '';
9000 foreach ($param['options'] as $keyopt => $valopt) {
9001 $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
9002 $out .= ' value="'.$keyopt.'"';
9003 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
9004 $out .= ($value == $keyopt ? 'checked' : '');
9005 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
9006 }
9007 } elseif ($type == 'chkbxlst') {
9008 if (is_array($value)) {
9009 $value_arr = $value;
9010 } else {
9011 $value_arr = explode(',', $value);
9012 }
9013
9014 if (is_array($param['options'])) {
9015 $tmpparamoptions = array_keys($param['options']);
9016 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
9017
9018 $InfoFieldList = explode(":", $paramoptions[0], 5);
9019 // 0 : tableName
9020 // 1 : label field name
9021 // 2 : key fields name (if different of rowid)
9022 // optional parameters...
9023 // 3 : key field parent (for dependent lists). How this is used ?
9024 // 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".
9025 // 5 : string category type. This replace the filter.
9026 // 6 : ids categories list separated by comma for category root. This replace the filter.
9027 // 7 : sort field
9028
9029 // If there is a filter
9030 if (! empty($InfoFieldList[4])) {
9031 $pos = 0;
9032 $parenthesisopen = 0;
9033 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
9034 if (substr($InfoFieldList[4], $pos, 1) == '(') {
9035 $parenthesisopen++;
9036 }
9037 if (substr($InfoFieldList[4], $pos, 1) == ')') {
9038 $parenthesisopen--;
9039 }
9040 $pos++;
9041 }
9042 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
9043 $tmpafter = substr($InfoFieldList[4], $pos + 1);
9044 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
9045 $InfoFieldList[4] = $tmpbefore;
9046 if ($tmpafter !== '') {
9047 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
9048 }
9049
9050 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
9051 $reg = array();
9052 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
9053 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
9054 }
9055
9056 //var_dump($InfoFieldList);
9057 }
9058
9059 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
9060
9061 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
9062
9063 $parentName = '';
9064 $parentField = '';
9065
9066 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
9067
9068 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9069 if (strpos($InfoFieldList[4], 'extra.') !== false) {
9070 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
9071 } else {
9072 $keyList = $InfoFieldList[2].' as rowid';
9073 }
9074 }
9075 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
9076 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
9077 if (!empty($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra.') !== false) {
9078 $keyList .= ', main.'.$parentField;
9079 } else {
9080 $keyList .= ', '.$parentField;
9081 }
9082 }
9083
9084 $filter_categorie = false;
9085 if (count($InfoFieldList) > 5) {
9086 if ($InfoFieldList[0] == 'categorie') {
9087 $filter_categorie = true;
9088 }
9089 }
9090
9091 // Common filter
9092 if (!$filter_categorie) {
9093 $fields_label = explode('|', $InfoFieldList[1]);
9094 if (is_array($fields_label)) {
9095 $keyList .= ', ';
9096 $keyList .= implode(', ', $fields_label);
9097 }
9098
9099 $sqlwhere = '';
9100 $sql = "SELECT " . $this->db->sanitize($keyList, 0, 0, 1);
9101 $sql .= ' FROM ' . $this->db->prefix() . $this->db->sanitize($InfoFieldList[0]);
9102
9103 if (!empty($InfoFieldList[4])) {
9104 // can use SELECT request
9105 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
9106 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
9107 }
9108
9109 // current object id can be use into filter
9110 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
9111 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
9112 } else {
9113 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
9114 }
9115
9116 // We have to join on extrafield table
9117 $errstr = '';
9118 if (strpos($InfoFieldList[4], 'extra') !== false) {
9119 $sql .= ' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . '_extrafields as extra';
9120 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
9121 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
9122 } else {
9123 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
9124 }
9125 } else {
9126 $sqlwhere .= ' WHERE 1=1';
9127 }
9128
9129 // Add Usf filter on second line
9130 /*
9131 if ($Usf) {
9132 $errorstr = '';
9133 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
9134 if (!$errorstr) {
9135 $sqlwhere .= $sqlusf;
9136 } else {
9137 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
9138 }
9139 }
9140 */
9141
9142 // Some tables may have field, some other not. For the moment we disable it.
9143 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
9144 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
9145 }
9146 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
9147 // print $sql;
9148
9149 $sql .= $sqlwhere;
9150
9151 dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
9152
9153 $resql = $this->db->query($sql);
9154 if ($resql) {
9155 $num = $this->db->num_rows($resql);
9156 $i = 0;
9157
9158 $data = array();
9159
9160 while ($i < $num) {
9161 $labeltoshow = '';
9162 $obj = $this->db->fetch_object($resql);
9163
9164 $notrans = false;
9165 // Several field into label (eq table:code|libelle:rowid)
9166 $fields_label = explode('|', $InfoFieldList[1]);
9167 if (count($fields_label) > 1) {
9168 $notrans = true;
9169 foreach ($fields_label as $field_toshow) {
9170 $labeltoshow .= $obj->$field_toshow . ' ';
9171 }
9172 } else {
9173 $labeltoshow = $obj->{$InfoFieldList[1]};
9174 }
9175 $labeltoshow = dol_trunc($labeltoshow, 45);
9176
9177 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9178 foreach ($fields_label as $field_toshow) {
9179 $translabel = $langs->trans($obj->$field_toshow);
9180 if ($translabel != $obj->$field_toshow) {
9181 $labeltoshow = dol_trunc($translabel, 18) . ' ';
9182 } else {
9183 $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
9184 }
9185 }
9186
9187 $data[$obj->rowid] = $labeltoshow;
9188 } else {
9189 if (!$notrans) {
9190 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9191 if ($translabel != $obj->{$InfoFieldList[1]}) {
9192 $labeltoshow = dol_trunc($translabel, 18);
9193 } else {
9194 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
9195 }
9196 }
9197 if (empty($labeltoshow)) {
9198 $labeltoshow = '(not defined)';
9199 }
9200
9201 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9202 $data[$obj->rowid] = $labeltoshow;
9203 }
9204
9205 if (!empty($InfoFieldList[3]) && $parentField) {
9206 $parent = $parentName . ':' . $obj->{$parentField};
9207 $isDependList = 1;
9208 }
9209
9210 $data[$obj->rowid] = $labeltoshow; // Warning: $obj->rowid is an alias and can be an int, but also a string ref.
9211 }
9212
9213 $i++;
9214 }
9215 $this->db->free($resql);
9216
9217 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
9218 } else {
9219 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
9220 }
9221 } else {
9222 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
9223 $categcode = $InfoFieldList[5];
9224 if (is_numeric($categcode)) { // deprecated: must use the category code instead of id. For backward compatibility.
9225 $tmpcategory = new Categorie($this->db);
9226 $MAP_ID_TO_CODE = array_flip($tmpcategory->MAP_ID);
9227 $categcode = $MAP_ID_TO_CODE[(int) $categcode];
9228 }
9229
9230 $data = $form->select_all_categories($categcode, '', 'parent', 64, $InfoFieldList[6], 1, 1);
9231 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
9232 }
9233 }
9234 } elseif ($type == 'link') {
9235 // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
9236 // Filter can contains some ':' inside.
9237 $param_list = array_keys($param['options']);
9238 $param_list_array = explode(':', $param_list[0], 4);
9239
9240 $showempty = (($required && $default != '') ? 0 : 1);
9241
9242 if (!preg_match('/search_/', $keyprefix)) {
9243 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
9244 // @phan-suppress-next-line PhanTypeMismatchProperty
9245 if (!empty($this->fields[$key]['picto'])) {
9246 $morecss .= ' widthcentpercentminusxx';
9247 } else {
9248 $morecss .= ' widthcentpercentminusx';
9249 }
9250 } else {
9251 // @phan-suppress-next-line PhanTypeMismatchProperty
9252 if (!empty($this->fields[$key]['picto'])) {
9253 $morecss .= ' widthcentpercentminusx';
9254 }
9255 }
9256 }
9257
9258 // $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.
9259
9260 // $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.
9261
9262 $objectfield = $val;
9263
9264 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
9265 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, (int) $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), '', $objectfield);
9266
9267 if (!empty($param_list_array[2])) { // If the entry into $fields is set, we must add a create button
9268 if ((!GETPOSTISSET('backtopage') || strpos(GETPOST('backtopage'), $_SERVER['PHP_SELF']) === 0) // // To avoid to open several times the 'Plus' button (we accept only one level)
9269 && empty($val['disabled']) && empty($nonewbutton)) { // and to avoid to show the button if the field is protected by a "disabled".
9270 list($class, $classfile) = explode(':', $param_list[0]);
9271 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
9272 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
9273 } else {
9274 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
9275 }
9276 $paramforthenewlink = '';
9277 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
9278 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOSTINT('id') : '');
9279 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
9280 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOSTINT('originid') : '');
9281 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
9282 // TODO Add JavaScript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
9283 $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>';
9284 }
9285 }
9286 } elseif ($type == 'password') {
9287 // If prefix is 'search_', field is used as a filter, we use a common text field.
9288 if ($keyprefix.$key.$keysuffix == 'pass_crypted') {
9289 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="pass" id="pass" value="" '.($moreparam ? $moreparam : '').'>';
9290 $out .= '<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
9291 } else {
9292 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
9293 }
9294 } elseif ($type == 'array') {
9295 $newval = $val;
9296 $newval['type'] = 'varchar(256)';
9297
9298 $out = '';
9299 if (!empty($value)) {
9300 foreach ($value as $option) {
9301 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
9302 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
9303 }
9304 }
9305 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
9306
9307 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
9308 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
9309
9310 if (!empty($conf->use_javascript_ajax)) {
9311 $out .= '
9312 <script nonce="'.getNonce().'">
9313 $(document).ready(function() {
9314 $(\'a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add\').click(function() {
9315 $(\''.dol_escape_js($newInput).'\').insertBefore(this);
9316 });
9317
9318 $(document).on("click", \'a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del\', function() {
9319 $(this).parent().remove();
9320 });
9321 });
9322 </script>';
9323 }
9324 }
9325 if (!empty($hidden)) {
9326 $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
9327 }
9328
9329 if ($isDependList == 1) {
9330 $out .= $this->getJSListDependancies('_common');
9331 }
9332 /* Add comments
9333 if ($type == 'date') $out.=' (YYYY-MM-DD)';
9334 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
9335 */
9336
9337 // Display error message for field
9338 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
9339 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
9340 }
9341
9342 return $out;
9343 }
9344
9358 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
9359 {
9360 global $conf, $langs, $form;
9361
9362 // 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...)
9363
9364 if (!is_object($form)) {
9365 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
9366 $form = new Form($this->db);
9367 }
9368
9369 //$label = empty($val['label']) ? '' : $val['label'];
9370 $type = empty($val['type']) ? '' : $val['type'];
9371 $size = empty($val['css']) ? '' : $val['css'];
9372
9373 $reg = array();
9374
9375 // Convert var to be able to share same code than showOutputField of extrafields
9376 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
9377 $type = 'varchar'; // convert varchar(xx) int varchar
9378 $size = $reg[1];
9379 } elseif (preg_match('/varchar/', $type)) {
9380 $type = 'varchar'; // convert varchar(xx) int varchar
9381 } elseif (preg_match('/^double\‍(/', $type)) {
9382 $type = 'double'; // convert double(xx,yy) into double
9383 }
9384 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
9385 // @phan-suppress-next-line PhanTypeMismatchProperty
9386 if (empty($this->fields[$key]['multiinput'])) {
9387 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
9388 }
9389 }
9390 if (isset($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
9391 $type = 'link';
9392 }
9393
9394 $default = empty($val['default']) ? '' : $val['default'];
9395 $computed = empty($val['computed']) ? '' : $val['computed'];
9396 $unique = empty($val['unique']) ? '' : $val['unique'];
9397 $required = empty($val['required']) ? '' : $val['required'];
9398 $param = array();
9399 $param['options'] = array();
9400
9401 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
9402 $param['options'] = $val['arrayofkeyval'];
9403 }
9404 if (isset($val['type']) && preg_match('/^integer:([^:]*):([^:]*)/i', $val['type'], $reg)) { // ex: integer:User:user/class/user.class.php
9405 $type = 'link';
9406 $stringforoptions = $reg[1].':'.$reg[2];
9407 // Special case: Force addition of getnomurlparam1 to -1 for users
9408 if ($reg[1] == 'User') {
9409 $stringforoptions .= ':#getnomurlparam1=-1';
9410 }
9411 $param['options'] = array($stringforoptions => $stringforoptions);
9412 } elseif (isset($val['type']) && preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
9413 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
9414 $type = 'sellist';
9415 } elseif (isset($val['type']) && preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
9416 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
9417 $type = 'sellist';
9418 } elseif (isset($val['type']) && preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
9419 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
9420 $type = 'sellist';
9421 } elseif (isset($val['type']) && preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
9422 $param['options'] = array($reg[1] => 'N');
9423 $type = 'chkbxlst';
9424 } elseif (isset($val['type']) && preg_match('/stars\‍((\d+)\‍)/', $val['type'], $reg)) {
9425 $param['options'] = array();
9426 $type = 'stars';
9427 $size = $reg[1];
9428 }
9429
9430 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
9431 $list = (empty($val['list']) ? '' : $val['list']);
9432 $help = (empty($val['help']) ? '' : $val['help']);
9433 $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)
9434
9435 if ($hidden) {
9436 return '';
9437 }
9438
9439 // If field is a computed field, value must become result of compute
9440 if ($computed) {
9441 // Make the eval of compute string
9442 //var_dump($computed);
9443 $value = dol_eval((string) $computed, 1, 0, '2');
9444 }
9445
9446 if (empty($morecss)) {
9447 if ($type == 'date') {
9448 $morecss = 'minwidth100imp';
9449 } elseif ($type == 'datetime' || $type == 'timestamp') {
9450 $morecss = 'minwidth200imp';
9451 } elseif (in_array($type, array('int', 'double', 'price'))) {
9452 $morecss = 'maxwidth75';
9453 } elseif ($type == 'url') {
9454 $morecss = 'minwidth400';
9455 } elseif ($type == 'boolean') {
9456 $morecss = '';
9457 } else {
9458 if (is_numeric($size) && round((float) $size) < 12) {
9459 $morecss = 'minwidth100';
9460 } elseif (is_numeric($size) && round((float) $size) <= 48) {
9461 $morecss = 'minwidth200';
9462 } else {
9463 $morecss = 'minwidth400';
9464 }
9465 }
9466 }
9467
9468 // Format output value differently according to properties of field
9469 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
9470 // @phan-suppress-next-line PhanTypeMismatchProperty
9471 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.
9472 $value = $this->getNomUrl(1, '', 0, '', 1);
9473 }
9474 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
9475 $value = $this->getLibStatut(3);
9476 } elseif ($type == 'date') {
9477 if (!empty($value)) {
9478 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
9479 } else {
9480 $value = '';
9481 }
9482 } elseif ($type == 'datetime' || $type == 'timestamp') {
9483 if (!empty($value)) {
9484 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
9485 } else {
9486 $value = '';
9487 }
9488 } elseif ($type == 'duration') {
9489 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
9490 if (!is_null($value) && $value !== '') {
9491 $value = convertSecondToTime((int) $value, 'allhourmin');
9492 }
9493 } elseif ($type == 'double' || $type == 'real') {
9494 if (!is_null($value) && $value !== '') {
9495 $value = price($value);
9496 }
9497 } elseif ($type == 'boolean') {
9498 $checked = '';
9499 if (!empty($value)) {
9500 $checked = ' checked ';
9501 }
9502 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
9503 $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
9504 } else {
9505 $value = yn($value ? 1 : 0);
9506 }
9507 } elseif ($type == 'mail' || $type == 'email') {
9508 $value = dol_print_email((string) $value, 0, 0, 0, 64, 1, 1);
9509 } elseif ($type == 'url') {
9510 $value = dol_print_url((string) $value, '_blank', 32, 1);
9511 } elseif ($type == 'phone') {
9512 $value = dol_print_phone((string) $value, '', 0, 0, '', '&nbsp;', 'phone');
9513 } elseif ($type == 'ip') {
9514 $value = dol_print_ip((string) $value, 0);
9515 } elseif ($type == 'stars') {
9516 $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 : '').'>';
9517 $value .= '<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.'_selection">';
9518 $i = 1;
9519 while ($i <= $size) {
9520 $value .= '<span class="star" data-value="'.$i.'">'.img_picto('', 'fontawesome_star_fas').'</span>';
9521 $i++;
9522 }
9523 $value .= '</div>';
9524 $value .= '<script>
9525 $(document).ready(function() { /* commonobject.class.php 2 */
9526 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.'_selection");
9527 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.'").val()) || 0;
9528 container.find(".star").each(function() {
9529 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9530 });
9531 container.find(".star").on("mouseover", function() {
9532 let selectedStar = $(this).data("value");
9533 container.find(".star").each(function() {
9534 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
9535 });
9536 });
9537 container.on("mouseout", function() {
9538 container.find(".star").each(function() {
9539 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9540 });
9541 });
9542 container.find(".star").off("click").on("click", function() {
9543 selectedStars = $(this).data("value");
9544 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.'").val() == 1) {
9545 selectedStars = 0;
9546 }
9547 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.'").val(selectedStars);
9548 container.find(".star").each(function() {
9549 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
9550 });
9551 $.ajax({
9552 url: "ajax/'.$this->element.'.php",
9553 method: "POST",
9554 data: {
9555 objectId: "'.$this->id.'",
9556 field: "'.$keyprefix.$key.$keysuffix.'",
9557 value: selectedStars,
9558 token: "'.newToken().'"
9559 },
9560 success: function(response) {
9561 var res = JSON.parse(response);
9562 console[res.status === "success" ? "log" : "error"](res.message);
9563 },
9564 error: function(xhr, status, error) {
9565 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.':", error);
9566 }
9567 });
9568 });
9569 });
9570 </script>';
9571 } elseif ($type == 'price') {
9572 if (!is_null($value) && $value !== '') {
9573 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
9574 }
9575 } elseif ($type == 'select') {
9576 $value = isset($param['options'][(string) $value]) ? $param['options'][(string) $value] : '';
9577 if (strpos($value, "|") !== false) {
9578 $value = $langs->trans(explode('|', $value)[0]);
9579 } elseif (! is_numeric($value)) {
9580 $value = $langs->trans($value);
9581 }
9582 } elseif ($type == 'sellist') {
9583 $param_list = array_keys($param['options']);
9584 $InfoFieldList = explode(":", $param_list[0]);
9585
9586 $selectkey = "rowid";
9587 $keyList = 'rowid';
9588
9589 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
9590 $selectkey = $InfoFieldList[2];
9591 $keyList = $InfoFieldList[2].' as rowid';
9592 }
9593
9594 $fields_label = explode('|', $InfoFieldList[1]);
9595 if (is_array($fields_label)) {
9596 $keyList .= ', ';
9597 $keyList .= implode(', ', $fields_label);
9598 }
9599
9600 $filter_categorie = false;
9601 if (count($InfoFieldList) > 5) {
9602 if ($InfoFieldList[0] == 'categorie') {
9603 $filter_categorie = true;
9604 }
9605 }
9606
9607 $sql = "SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9608 $sql .= ' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9609 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra') !== false) {
9610 $sql .= ' as main';
9611 }
9612 if ($selectkey == 'rowid' && empty($value)) {
9613 $sql .= " WHERE ".$this->db->sanitize($selectkey)." = 0";
9614 } elseif ($selectkey == 'rowid') {
9615 $sql .= " WHERE ".$this->db->sanitize($selectkey)." = ".((int) $value);
9616 } else {
9617 $sql .= " WHERE ".$this->db->sanitize($selectkey)." = '".$this->db->escape((string) $value)."'";
9618 }
9619
9620 //$sql.= ' AND entity = '.((int) $conf->entity);
9621
9622 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
9623 $resql = $this->db->query($sql);
9624 if ($resql) {
9625 if (!$filter_categorie) {
9626 $value = ''; // value was used, so now we reset it to use it to build final output
9627 $numrows = $this->db->num_rows($resql);
9628 if ($numrows) {
9629 $obj = $this->db->fetch_object($resql);
9630
9631 // Several field into label (eq table:code|libelle:rowid)
9632 $fields_label = explode('|', $InfoFieldList[1]);
9633
9634 if (is_array($fields_label) && count($fields_label) > 1) {
9635 foreach ($fields_label as $field_toshow) {
9636 $translabel = '';
9637 if (!empty($obj->$field_toshow)) {
9638 $translabel = $langs->trans($obj->$field_toshow);
9639 }
9640 if ($translabel != $field_toshow) {
9641 $value .= dol_trunc($translabel, 18) . ' ';
9642 } else {
9643 $value .= $obj->$field_toshow . ' ';
9644 }
9645 }
9646 } else {
9647 $translabel = '';
9648 if (!empty($obj->{$InfoFieldList[1]})) {
9649 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9650 }
9651 if ($translabel != $obj->{$InfoFieldList[1]}) {
9652 $value = dol_trunc($translabel, 18);
9653 } else {
9654 $value = $obj->{$InfoFieldList[1]};
9655 }
9656 }
9657 }
9658 } else {
9659 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
9660
9661 $toprint = array();
9662 $obj = $this->db->fetch_object($resql);
9663 $c = new Categorie($this->db);
9664 $c->fetch($obj->rowid);
9665 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
9666 foreach ($ways as $way) {
9667 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
9668 }
9669 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
9670 }
9671 } else {
9672 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9673 }
9674 } elseif ($type == 'radio') {
9675 $value = $param['options'][(string) $value];
9676 } elseif ($type == 'checkbox') {
9677 $value_arr = explode(',', (string) $value);
9678 $value = '';
9679 if (is_array($value_arr) && count($value_arr) > 0) {
9680 $toprint = array();
9681 foreach ($value_arr as $keyval => $valueval) {
9682 if (!empty($valueval)) {
9683 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param['options'][$valueval] . '</li>';
9684 }
9685 }
9686 if (!empty($toprint)) {
9687 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
9688 }
9689 }
9690 } elseif ($type == 'chkbxlst') {
9691 $value_arr = (isset($value) ? explode(',', $value) : array());
9692
9693 $param_list = array_keys($param['options']);
9694 $InfoFieldList = explode(":", $param_list[0]);
9695
9696 $selectkey = "rowid";
9697 $keyList = 'rowid';
9698
9699 if (count($InfoFieldList) >= 3) {
9700 $selectkey = $InfoFieldList[2];
9701 $keyList = $InfoFieldList[2].' as rowid';
9702 }
9703
9704 $fields_label = explode('|', $InfoFieldList[1]);
9705 if (is_array($fields_label)) {
9706 $keyList .= ', ';
9707 $keyList .= implode(', ', $fields_label);
9708 }
9709
9710 $filter_categorie = false;
9711 if (count($InfoFieldList) > 5) {
9712 if ($InfoFieldList[0] == 'categorie') {
9713 $filter_categorie = true;
9714 }
9715 }
9716
9717 $sql = "SELECT ".$this->db->sanitize($keyList, 0, 0, 1);
9718 $sql .= ' FROM '.$this->db->prefix().$this->db->sanitize($InfoFieldList[0]);
9719 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra') !== false) {
9720 $sql .= ' as main';
9721 }
9722 // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
9723 // $sql.= ' AND entity = '.((int) $conf->entity);
9724
9725 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
9726 $resql = $this->db->query($sql);
9727 if ($resql) {
9728 if (!$filter_categorie) {
9729 $value = ''; // value was used, so now we reset it to use it to build final output
9730 $toprint = array();
9731 while ($obj = $this->db->fetch_object($resql)) {
9732 // Several field into label (eq table:code|libelle:rowid)
9733 $fields_label = explode('|', $InfoFieldList[1]);
9734 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9735 if (is_array($fields_label) && count($fields_label) > 1) {
9736 foreach ($fields_label as $field_toshow) {
9737 $translabel = '';
9738 if (!empty($obj->$field_toshow)) {
9739 $translabel = $langs->trans($obj->$field_toshow);
9740 }
9741 if ($translabel != $field_toshow) {
9742 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
9743 } else {
9744 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
9745 }
9746 }
9747 } else {
9748 $translabel = '';
9749 if (!empty($obj->{$InfoFieldList[1]})) {
9750 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
9751 }
9752 if ($translabel != $obj->{$InfoFieldList[1]}) {
9753 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
9754 } else {
9755 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
9756 }
9757 }
9758 }
9759 }
9760 } else {
9761 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
9762
9763 $toprint = array();
9764 while ($obj = $this->db->fetch_object($resql)) {
9765 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
9766 $c = new Categorie($this->db);
9767 $c->fetch($obj->rowid);
9768 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
9769 foreach ($ways as $way) {
9770 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
9771 }
9772 }
9773 }
9774 }
9775 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
9776 } else {
9777 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
9778 }
9779 } elseif ($type == 'link') {
9780 $out = '';
9781
9782 // only if something to display (perf)
9783 if ($value) {
9784 $param_list = array_keys($param['options']);
9785 // Example: $param_list='ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
9786 // Example: $param_list='ObjectClass:PathToClass:#getnomurlparam1=-1#getnomurlparam2=customer'
9787
9788 $InfoFieldList = explode(":", $param_list[0]);
9789
9790 $classname = $InfoFieldList[0];
9791 $classpath = $InfoFieldList[1];
9792
9793 // Set $getnomurlparam1 et getnomurlparam2
9794 $getnomurlparam = 3;
9795 $getnomurlparam2 = '';
9796 $regtmp = array();
9797 if (preg_match('/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
9798 $getnomurlparam = $regtmp[1];
9799 }
9800 if (preg_match('/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
9801 $getnomurlparam2 = $regtmp[1];
9802 }
9803
9804 if (!empty($classpath)) {
9805 dol_include_once($InfoFieldList[1]);
9806
9807 if ($classname && !class_exists($classname)) {
9808 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
9809 // TODO use newObjectByElement() introduce in V20 by PR #30036 for better errors management
9810 $element_prop = getElementProperties($classname);
9811 if ($element_prop) {
9812 $classname = $element_prop['classname'];
9813 }
9814 }
9815
9816
9817 if ($classname && class_exists($classname)) {
9818 $object = new $classname($this->db);
9819 '@phan-var-force CommonObject $object';
9820 if ($object->element === 'product') { // Special case for product because default valut of fetch are wrong
9821 '@phan-var-force Product $object';
9822 $result = $object->fetch((int) $value, '', '', '', 0, 1, 1);
9823 } else {
9824 $result = $object->fetch($value);
9825 }
9826 if ($result > 0) {
9827 if ($object->element === 'product') {
9828 '@phan-var-force Product $object';
9829 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
9830 if (isset($val['get_name_url_params'])) {
9831 $get_name_url_params = explode(':', $val['get_name_url_params']);
9832 if (!empty($get_name_url_params)) {
9833 $param_num_max = count($get_name_url_param_arr) - 1;
9834 foreach ($get_name_url_params as $param_num => $param_value) {
9835 if ($param_num > $param_num_max) {
9836 break;
9837 }
9838 $get_name_url_param_arr[$param_num] = $param_value;
9839 }
9840 }
9841 }
9842
9846 $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]);
9847 } else {
9848 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
9849 }
9850 } else {
9851 $value = '';
9852 }
9853 }
9854 } else {
9855 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
9856 return 'Error bad setup of extrafield';
9857 }
9858 } else {
9859 $value = '';
9860 }
9861 } elseif ($type == 'password') {
9862 $value = '<span class="opacitymedium">'.$langs->trans("Encrypted").'</span>';
9863 //$value = preg_replace('/./i', '*', $value);
9864 } elseif ($type == 'array') {
9865 if (is_array($value)) {
9866 $value = implode('<br>', $value);
9867 } else {
9868 dol_syslog(__METHOD__.' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
9869 return 'Error unexpected result from code evaluation';
9870 }
9871 } else { // text|html|varchar
9872 if (!empty($value) && preg_match('/^text/', (string) $type) && !preg_match('/search_/', $keyprefix) && !empty($param['options'])) {
9873 $value = str_replace(',', "\n", $value);
9874 }
9875 $value = dol_htmlentitiesbr((string) $value);
9876 }
9877
9878 //print $type.'-'.$size.'-'.$value;
9879 $out = $value;
9880
9881 return is_null($out) ? '' : $out;
9882 }
9883
9890 public function clearFieldError($fieldKey)
9891 {
9892 $this->error = '';
9893 unset($this->validateFieldsErrors[$fieldKey]);
9894 }
9895
9903 public function setFieldError($fieldKey, $msg = '')
9904 {
9905 global $langs;
9906 if (empty($msg)) {
9907 $msg = $langs->trans("UnknownError");
9908 }
9909
9910 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
9911 }
9912
9919 public function getFieldError($fieldKey)
9920 {
9921 if (!empty($this->validateFieldsErrors[$fieldKey])) {
9922 return $this->validateFieldsErrors[$fieldKey];
9923 }
9924 return '';
9925 }
9926
9935 public function validateField($fields, $fieldKey, $fieldValue)
9936 {
9937 global $langs;
9938
9939 if (!class_exists('Validate')) {
9940 require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
9941 }
9942
9943 $this->clearFieldError($fieldKey);
9944
9945 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
9946 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
9947 return false;
9948 }
9949
9950 $val = $fields[$fieldKey];
9951
9952 $param = array();
9953 $param['options'] = array();
9954 $type = $val['type'];
9955
9956 $required = false;
9957 if (isset($val['notnull']) && $val['notnull'] === 1) {
9958 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
9959 $required = true;
9960 }
9961
9962 $maxSize = 0;
9963 $minSize = 0;
9964
9965 //
9966 // PREPARE Elements
9967 //
9968 $reg = array();
9969
9970 // Convert var to be able to share same code than showOutputField of extrafields
9971 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
9972 $type = 'varchar'; // convert varchar(xx) int varchar
9973 $maxSize = (int) $reg[1];
9974 } elseif (preg_match('/varchar/', $type)) {
9975 $type = 'varchar'; // convert varchar(xx) int varchar
9976 } elseif (preg_match('/^double\‍(/', $type)) {
9977 $type = 'double'; // convert double(xx,yy) into double
9978 }
9979
9980 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
9981 $type = 'select';
9982 }
9983
9984 if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
9985 $type = 'link';
9986 }
9987
9988 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
9989 $param['options'] = $val['arrayofkeyval'];
9990 }
9991
9992 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
9993 $type = 'link';
9994 $param['options'] = array($reg[1].':'.$reg[2] => $reg[1].':'.$reg[2]);
9995 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
9996 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
9997 $type = 'sellist';
9998 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
9999 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
10000 $type = 'sellist';
10001 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
10002 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
10003 $type = 'sellist';
10004 }
10005
10006 //
10007 // TEST Value
10008 //
10009
10010 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
10011 $validate = new Validate($this->db, $langs);
10012
10013
10014 // little trick : to perform tests with good performances sort tests by quick to low
10015
10016 //
10017 // COMMON TESTS
10018 //
10019
10020 // Required test and empty value
10021 if ($required && !$validate->isNotEmptyString($fieldValue)) {
10022 $this->setFieldError($fieldKey, $validate->error);
10023 return false;
10024 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
10025 // if no value sent and the field is not mandatory, no need to perform tests
10026 return true;
10027 }
10028
10029 // MAX Size test
10030 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
10031 $this->setFieldError($fieldKey, $validate->error);
10032 return false;
10033 }
10034
10035 // MIN Size test
10036 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
10037 $this->setFieldError($fieldKey, $validate->error);
10038 return false;
10039 }
10040
10041 //
10042 // TESTS for TYPE
10043 //
10044
10045 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
10046 if (!$validate->isTimestamp($fieldValue)) {
10047 $this->setFieldError($fieldKey, $validate->error);
10048 return false;
10049 } else {
10050 return true;
10051 }
10052 } elseif ($type == 'duration') {
10053 if (!$validate->isDuration($fieldValue)) {
10054 $this->setFieldError($fieldKey, $validate->error);
10055 return false;
10056 } else {
10057 return true;
10058 }
10059 } elseif (in_array($type, array('double', 'real', 'price'))) {
10060 // is numeric
10061 if (!$validate->isNumeric($fieldValue)) {
10062 $this->setFieldError($fieldKey, $validate->error);
10063 return false;
10064 } else {
10065 return true;
10066 }
10067 } elseif ($type == 'boolean') {
10068 if (!$validate->isBool($fieldValue)) {
10069 $this->setFieldError($fieldKey, $validate->error);
10070 return false;
10071 } else {
10072 return true;
10073 }
10074 } elseif ($type == 'mail' || $type == 'email') {
10075 if (!$validate->isEmail($fieldValue)) {
10076 $this->setFieldError($fieldKey, $validate->error);
10077 return false;
10078 }
10079 } elseif ($type == 'url') {
10080 if (!$validate->isUrl($fieldValue)) {
10081 $this->setFieldError($fieldKey, $validate->error);
10082 return false;
10083 } else {
10084 return true;
10085 }
10086 } elseif ($type == 'phone') {
10087 if (!$validate->isPhone($fieldValue)) {
10088 $this->setFieldError($fieldKey, $validate->error);
10089 return false;
10090 } else {
10091 return true;
10092 }
10093 } elseif ($type == 'select' || $type == 'radio') {
10094 if (!isset($param['options'][$fieldValue])) {
10095 $this->error = $langs->trans('RequireValidValue');
10096 return false;
10097 } else {
10098 return true;
10099 }
10100 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
10101 $param_list = array_keys($param['options']);
10102 $InfoFieldList = explode(":", $param_list[0]);
10103 $value_arr = explode(',', $fieldValue);
10104
10105 $selectkey = "rowid";
10106 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
10107 $selectkey = $InfoFieldList[2];
10108 }
10109
10110 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
10111 $this->setFieldError($fieldKey, $validate->error);
10112 return false;
10113 } else {
10114 return true;
10115 }
10116 } elseif ($type == 'link') {
10117 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
10118 $InfoFieldList = explode(":", $param_list[0]);
10119 $classname = $InfoFieldList[0];
10120 $classpath = $InfoFieldList[1];
10121 if (!$validate->isFetchable((int) $fieldValue, $classname, $classpath)) {
10122 $lastIsFetchableError = $validate->error;
10123
10124 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
10125 if ($validate->isFetchableElement((int) $fieldValue, $classname)) {
10126 return true;
10127 }
10128
10129 $this->setFieldError($fieldKey, $lastIsFetchableError);
10130 return false;
10131 } else {
10132 return true;
10133 }
10134 }
10135
10136 // if no test failed all is ok
10137 return true;
10138 }
10139
10153 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = '', $display_type = 'card')
10154 {
10155 global $db, $conf, $langs, $action, $form, $hookmanager;
10156 global $objectoffield;
10157
10158 if (!is_object($form)) {
10159 $form = new Form($db);
10160 }
10161 if (!is_object($extrafields)) {
10162 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
10163 return 'Bad parameter extrafields for showOptionals';
10164 }
10165 if (!is_array($extrafields->attributes[$this->table_element])) {
10166 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
10167 }
10168
10169 // Ensure $objectoffield is available for dol_eval visibility formulas.
10170 $objectoffield = $this;
10171
10172 $out = '';
10173
10174 $parameters = array('mode' => $mode, 'params' => $params, 'keysuffix' => $keysuffix, 'keyprefix' => $keyprefix, 'display_type' => $display_type);
10175 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
10176 $hookResPrint = $hookmanager->resPrint;
10177
10178 if (empty($reshook)) {
10179 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) {
10180 $out .= "\n";
10181 $out .= '<!-- commonobject:showOptionals --> ';
10182 $out .= "\n";
10183
10184 $nbofextrafieldsshown = 0;
10185 $e = 0; // var to manage the modulo (odd/even)
10186
10187 $lastseparatorkeyfound = '';
10188 $extrafields_collapse_num = '';
10189 $extrafields_collapse_num_old = '';
10190 $i = 0;
10191
10192 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
10193 $i++;
10194
10195 // Show only the key field in params @phan-suppress-next-line PhanTypeArraySuspiciousNullable
10196 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
10197 continue;
10198 }
10199
10200 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
10201 $enabled = 1;
10202 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
10203 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
10204 }
10205 if (empty($enabled)) {
10206 continue;
10207 }
10208
10209 $visibility = 1;
10210 if (isset($extrafields->attributes[$this->table_element]['list'][$key])) {
10211 $visibility = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
10212 }
10213
10214 $perms = 1;
10215 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
10216 $perms = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
10217 }
10218
10219 if (($mode == 'create') && !in_array(abs($visibility), array(1, 3))) {
10220 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
10221 } elseif (($mode == 'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
10222 // We need to make sure, that the values of hidden extrafields are also part of $_POST.
10223 // Otherwise, they would be empty after an update of the object. See also getOptionalsFromPost
10224 // TODO: We should not have this hidden field, and action='update' should be done only if field was POSTED by form.
10225 $ef_name = 'options_' . $key;
10226 $ef_value = $this->array_options[$ef_name] ?? '';
10227 $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).
10228 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
10229 } elseif ($mode == 'view' && empty($visibility)) {
10230 continue;
10231 }
10232 if (empty($perms)) {
10233 continue;
10234 }
10235
10236 // Load language if required
10237 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
10238 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
10239 }
10240
10241 $colspan = 0;
10242 $value = null;
10243 if (is_array($params) && count($params) > 0 && $display_type == 'card') {
10244 if (array_key_exists('cols', $params)) {
10245 $colspan = $params['cols'];
10246 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
10247 $reg = array();
10248 if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
10249 $colspan = $reg[1];
10250 } else {
10251 $colspan = $params['colspan'];
10252 }
10253 }
10254 }
10255 $colspan = intval($colspan);
10256
10257 switch ($mode) {
10258 case "view":
10259 $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
10260 break;
10261 case "create":
10262 case "edit":
10263 // We get the value of property found with GETPOST so it takes into account:
10264 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
10265 $check = 'alphanohtml';
10266 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
10267 $check = 'restricthtml';
10268 }
10269 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
10270 // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
10271 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
10272 if (is_array($getposttemp)) {
10273 // $getposttemp is an array but following code expects a comma separated string
10274 $value = implode(",", $getposttemp);
10275 } else {
10276 $value = $getposttemp;
10277 }
10278 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('int'))) {
10279 $value = (!empty($this->array_options["options_".$key]) || (isset($this->array_options["options_".$key]) && $this->array_options["options_".$key] === '0')) ? $this->array_options["options_".$key] : '';
10280 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('varchar', 'char'))) {
10281 $value = (isset($this->array_options["options_".$key]) && $this->array_options["options_".$key] !== '') ? $this->array_options["options_".$key] : '';
10282 } else {
10283 $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.
10284 }
10285 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
10286 break;
10287 }
10288
10289 $nbofextrafieldsshown++;
10290
10291 // Output value of the current field
10292 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
10293 $extrafields_collapse_num = $key;
10294 /*
10295 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
10296 if (!empty($extrafield_param) && is_array($extrafield_param)) {
10297 $extrafield_param_list = array_keys($extrafield_param['options']);
10298
10299 if (count($extrafield_param_list) > 0) {
10300 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
10301
10302 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
10303 //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
10304 $extrafields_collapse_num = $key;
10305 }
10306 }
10307 }
10308 */
10309
10310 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
10311 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
10312
10313 $lastseparatorkeyfound = $key;
10314 } else {
10315 $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
10316
10317 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
10318 $csstyle = '';
10319 if (is_array($params) && count($params) > 0) {
10320 if (array_key_exists('class', $params)) {
10321 $class .= $params['class'].' ';
10322 }
10323 if (array_key_exists('style', $params)) {
10324 $csstyle = $params['style'];
10325 }
10326 }
10327
10328 // add html5 elements
10329 $domData = ' data-element="extrafield"';
10330 $domData .= ' data-targetelement="'.$this->element.'"';
10331 $domData .= ' data-targetid="'.$this->id.'"';
10332
10333 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
10334 if ($display_type == 'card') {
10335 if (getDolGlobalString('MAIN_EXTRAFIELDS_USE_TWO_COLUMS') && ($e % 2) == 0) {
10336 $colspan = 0;
10337 }
10338
10339 if ($action == 'selectlines') {
10340 $colspan++;
10341 }
10342 }
10343
10344 // Expected behavior : if THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_XXX is set, when we change company,
10345 // Then we use the extrafields of the object (they are filled in the card when constant THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_XXX is set)
10346 $force_values_on_change_company = (
10347 ($this->element == 'facture' && getDolGlobalInt('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE'))
10348 || ($this->element == 'commande' && getDolGlobalInt('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER'))
10349 || ($this->element == 'order_supplier' && getDolGlobalInt('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_SUPPLIER_ORDER'))
10350 );
10351 if ($force_values_on_change_company && GETPOSTINT('changecompany')) {
10352 $value = $this->array_options['options_'.$key] ?? $value;
10353 }
10354
10355 // Convert date into timestamp format (value in memory must be a timestamp)
10356 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
10357 $datenotinstring = null;
10358 if (array_key_exists('options_'.$key, $this->array_options)) {
10359 $datenotinstring = $this->array_options['options_'.$key];
10360 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
10361 $datenotinstring = $this->db->jdate($datenotinstring);
10362 }
10363 }
10364 $datekey = $keyprefix.'options_'.$key.$keysuffix;
10365 $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;
10366 }
10367 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
10368 $datenotinstring = null;
10369 if (array_key_exists('options_'.$key, $this->array_options)) {
10370 $datenotinstring = $this->array_options['options_'.$key];
10371 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
10372 $datenotinstring = $this->db->jdate($datenotinstring);
10373 }
10374 }
10375 $timekey = $keyprefix.'options_'.$key.$keysuffix;
10376 $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;
10377 }
10378 // Convert float submitted string into real php numeric (value in memory must be a php numeric)
10379 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
10380 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
10381 $value = price2num($value);
10382 } elseif (isset($this->array_options['options_'.$key])) {
10383 $value = $this->array_options['options_'.$key];
10384 }
10385 }
10386
10387 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
10388 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'radio', 'int', 'boolean'))) {
10389 if ($action == 'create' || $mode == 'create') {
10390 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
10391 }
10392 }
10393
10394 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('checkbox'))) {
10395 if ($action == 'create') {
10396 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : explode(',', $extrafields->attributes[$this->table_element]['default'][$key]);
10397 }
10398 }
10399
10400
10401 $labeltoshow = $langs->trans($label);
10402 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
10403 if ($display_type == 'card') {
10404 $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.' >';
10405 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER') && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
10406 $out .= '<td></td>';
10407 }
10408 $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldmax45' : $params['tdclass']).' wordbreak';
10409 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'text') {
10410 $out .= ' tdtop';
10411 }
10412 } elseif ($display_type == 'line') {
10413 $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
10414 $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
10415 }
10416 //$out .= "titlefield";
10417 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
10418 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
10419 $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
10420 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
10421 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
10422 $out .= ' fieldrequired';
10423 }
10424 }
10425 $out .= '">';
10426 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
10427 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
10428 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
10429 } else {
10430 $out .= $labeltoshow;
10431 }
10432 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
10433 $out .= '&nbsp;<span style="color: red">*</span>';
10434 }
10435 } else {
10436 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
10437 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
10438 } else {
10439 $out .= $labeltoshow;
10440 }
10441 }
10442
10443 $out .= ($display_type == 'card' ? '</td>' : '</div>');
10444
10445 // Second column
10446 $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
10447 if ($display_type == 'card') {
10448 // 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
10449 $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key;
10450 $out .= '" '.($colspan ? ' colspan="'.$colspan.'"' : '');
10451 $out .= '>';
10452 } elseif ($display_type == 'line') {
10453 $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].'">';
10454 }
10455
10456 switch ($mode) {
10457 case "view":
10458 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
10459 break;
10460 case "create":
10461 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICTO', 'email,ip,password'));
10462 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
10463 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
10464 }
10465 //$out .= '<!-- type = '.$extrafields->attributes[$this->table_element]['type'][$key].' -->';
10466 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', '', $this, $this->table_element);
10467 break;
10468 case "edit":
10469 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICTO', 'email,phone,ip,password'));
10470 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
10471 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
10472 }
10473 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', '', $this, $this->table_element);
10474 break;
10475 }
10476
10477 $out .= ($display_type == 'card' ? '</td>' : '</div>');
10478 $out .= ($display_type == 'card' ? '</tr>'."\n" : '</div>');
10479 $e++;
10480 }
10481 }
10482 $out .= "\n";
10483 // Add code to manage list depending on others
10484 if (!empty($conf->use_javascript_ajax)) {
10485 $out .= $this->getJSListDependancies();
10486 }
10487
10488 $out .= '<!-- commonobject:showOptionals end --> '."\n";
10489
10490 if (empty($nbofextrafieldsshown)) {
10491 $out = '';
10492 }
10493 }
10494 }
10495
10496 $out .= $hookResPrint;
10497
10498 return $out;
10499 }
10500
10505 public function getJSListDependancies($type = '_extra')
10506 {
10507 $out = '
10508 <script nonce="'.getNonce().'">
10509 jQuery(document).ready(function() {
10510 function showOptions'.$type.'(child_list, parent_list, orig_select)
10511 {
10512 var val = $("select[name=\""+parent_list+"\"]").val();
10513 var parentVal = parent_list + ":" + val;
10514 if(typeof val == "string"){
10515 if(val != "") {
10516 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10517 $("select[name=\""+child_list+"\"] option[parent]").remove();
10518 $("select[name=\""+child_list+"\"]").append(options);
10519 } else {
10520 var options = orig_select.find("option[parent]").clone();
10521 $("select[name=\""+child_list+"\"] option[parent]").remove();
10522 $("select[name=\""+child_list+"\"]").append(options);
10523 }
10524 } else if(val > 0) {
10525 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
10526 $("select[name=\""+child_list+"\"] option[parent]").remove();
10527 $("select[name=\""+child_list+"\"]").append(options);
10528 } else {
10529 var options = orig_select.find("option[parent]").clone();
10530 $("select[name=\""+child_list+"\"] option[parent]").remove();
10531 $("select[name=\""+child_list+"\"]").append(options);
10532 }
10533 }
10534 function setListDependencies'.$type.'() {
10535 jQuery("select option[parent]").parent().each(function() {
10536 var orig_select = {};
10537 var child_list = $(this).attr("name");
10538 orig_select[child_list] = $(this).clone();
10539 var parent = $(this).find("option[parent]:first").attr("parent");
10540 var infos = parent.split(":");
10541 var parent_list = infos[0];
10542
10543 //Hide daughters lists
10544 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
10545 $("#"+child_list).hide();
10546 //Show mother lists
10547 } else if ($("#"+parent_list).val() != 0){
10548 $("#"+parent_list).show();
10549 }
10550 //Show the child list if the parent list value is selected
10551 $("select[name=\""+parent_list+"\"]").click(function() {
10552 if ($(this).val() != 0){
10553 $("#"+child_list).show()
10554 }
10555 });
10556
10557 //When we change parent list
10558 $("select[name=\""+parent_list+"\"]").change(function() {
10559 showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
10560 //Select the value 0 on child list after a change on the parent list
10561 $("#"+child_list).val(0).trigger("change");
10562 //Hide child lists if the parent value is set to 0
10563 if ($(this).val() == 0){
10564 $("#"+child_list).hide();
10565 }
10566 });
10567 });
10568 }
10569
10570 setListDependencies'.$type.'();
10571 });
10572 </script>'."\n";
10573 return $out;
10574 }
10575
10582 public function getRights()
10583 {
10584 global $user;
10585 return $this->getRightsForUser($user);
10586 }
10587
10595 public function getRightsForUser(User $user)
10596 {
10597 $module = empty($this->module) ? '' : $this->module;
10598 $element = $this->element;
10599
10600 if ($module && $user->hasRight($module, $element)) {
10601 // for modules built with ModuleBuilder (permissions $module->$element->read, write, delete)
10602 $rights = $user->hasRight($module, $element);
10603 // Some core modules have a permission named like the element, but it is not the permissions of the object
10604 // (ex: commande->commande->export), their permissions are $element->lire, creer... like when module is not set
10605 if (!is_object($rights) || isset($rights->read) || isset($rights->write) || isset($rights->delete) || isset($rights->lire) || isset($rights->creer) || isset($rights->supprimer)) {
10606 return $rights;
10607 }
10608 }
10609
10610 return isset($user->rights->$element) ? $user->rights->$element : null;
10611 }
10612
10623 public function hasUserPermission(User $user, $mode = 'write')
10624 {
10625 $rights = $this->getRightsForUser($user);
10626 if (is_int($rights)) {
10627 // A single permission without sub levels grants every mode
10628 return $rights === 1;
10629 }
10630 if (!is_object($rights)) {
10631 return false;
10632 }
10633
10634 if ($mode == 'read') {
10635 return !empty($rights->lire) || !empty($rights->read);
10636 }
10637 if ($mode == 'create' || $mode == 'write') {
10638 return !empty($rights->creer) || !empty($rights->write);
10639 }
10640 if ($mode == 'delete') {
10641 return !empty($rights->supprimer) || !empty($rights->delete);
10642 }
10643
10644 return false;
10645 }
10646
10656 public function hasUserWritePermissionOnField(User $user, $field)
10657 {
10658 return $this->hasUserPermissionOnField($user, $field, 'write');
10659 }
10660
10671 public function hasUserPermissionOnField(User $user, $field, $mode = 'write')
10672 {
10673 if (empty($field)) {
10674 return false;
10675 }
10676
10677 return $this->hasUserPermission($user, $mode);
10678 }
10679
10697 public function isFieldEditAllowed(User $user, $field, $byPassUserPermission = false)
10698 {
10699 // TODO : Implement error message ?
10700
10701 // Ensure user has write permission for field
10702 if (!$byPassUserPermission && !$this->hasUserPermissionOnField($user, $field, 'write')) {
10703 return false;
10704 }
10705
10706 // Ensure field exists in object definition
10707 if (!$this->isFieldDefined($field)) {
10708 return false;
10709 }
10710
10711 // Field explicitly disabled
10712 if ($this->isFieldDisabled($field)) {
10713 return false;
10714 }
10715
10716 // Field must be enabled (default = enabled if not defined)
10717 if (!$this->isFieldEnabled($field)) {
10718 return false;
10719 }
10720
10721 // Field explicitly marked as not editable
10722 if ($this->isFieldMarkedNotEditable($field)) {
10723 return false;
10724 }
10725
10726 // Object state restriction
10727 if ($this->isFieldBlockedByObjectState($field)) {
10728 return false;
10729 }
10730
10731 return true;
10732 }
10733
10749 public function isFieldEditableFromUi(User $user, $field)
10750 {
10751 if (!$this->isFieldDefined($field) || empty($this->fields[$field]['uieditable'])) {
10752 return false;
10753 }
10754
10755 if ($field == 'note_private' && !empty($user->socid)) {
10756 return false;
10757 }
10758
10759 return $this->isFieldEditAllowed($user, $field);
10760 }
10761
10775 public function isFieldReadableFromUi(User $user, $field)
10776 {
10777 if (!$this->isFieldDefined($field) || !$this->isFieldEnabled($field)) {
10778 return false;
10779 }
10780
10781 if (preg_match('/^password/', (string) $this->fields[$field]['type'])) {
10782 return false;
10783 }
10784
10785 if ($field == 'note_private' && !empty($user->socid)) {
10786 return false;
10787 }
10788
10789 if (!empty($this->fields[$field]['uieditable'])) {
10790 return true;
10791 }
10792
10793 $visible = isset($this->fields[$field]['visible']) ? $this->fields[$field]['visible'] : 0;
10794 if (!is_numeric($visible)) {
10795 $visible = dol_eval((string) $visible);
10796 }
10797
10798 return in_array(abs((int) $visible), array(1, 3, 4, 5));
10799 }
10800
10801
10808 protected function isFieldDefined($field)
10809 {
10810 return !empty($this->fields)
10811 && is_array($this->fields)
10812 && isset($this->fields[$field]);
10813 }
10814
10821 protected function isFieldDisabled($field)
10822 {
10823 return !empty($this->fields[$field]['disabled']);
10824 }
10825
10832 protected function isFieldValidationRequired($field)
10833 {
10834 return !empty($this->fields[$field]['validate']);
10835 }
10836
10837
10838
10846 protected function isFieldEnabled($field)
10847 {
10848 return !isset($this->fields[$field]['enabled']) || (bool) (int) dol_eval((string) $this->fields[$field]['enabled']);
10849 }
10850
10857 protected function isFieldMarkedNotEditable($field)
10858 {
10859 return !empty($this->fields[$field]['noteditable']);
10860 }
10861
10876 protected function isFieldBlockedByObjectState($field)
10877 {
10878 if (!empty($this->fields[$field]['alwayseditable'])) {
10879 return false;
10880 }
10881
10882 if (!defined(static::class.'::STATUS_DRAFT')) {
10883 return false;
10884 }
10885
10886 $draftStatus = (int) constant(static::class.'::STATUS_DRAFT');
10887
10888 return (isset($this->status) && (int) $this->status !== $draftStatus)
10889 || (isset($this->statut) && (int) $this->statut !== $draftStatus);
10890 }
10891
10904 public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
10905 {
10906 global $hookmanager;
10907
10908 $parameters = array(
10909 'origin_id' => $origin_id,
10910 'dest_id' => $dest_id,
10911 'tables' => $tables,
10912 );
10913 $reshook = $hookmanager->executeHooks('commonReplaceThirdparty', $parameters);
10914 if ($reshook) {
10915 return true; // replacement code
10916 } elseif ($reshook < 0) {
10917 return $ignoreerrors === 1; // failure
10918 } // reshook = 0 => execute normal code
10919
10920 foreach ($tables as $table) {
10921 $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
10922
10923 if (!$dbs->query($sql)) {
10924 if ($ignoreerrors) {
10925 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.
10926 }
10927 //$this->errors = $db->lasterror();
10928 return false;
10929 }
10930 }
10931
10932 return true;
10933 }
10934
10947 public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
10948 {
10949 foreach ($tables as $table) {
10950 $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
10951
10952 if (!$dbs->query($sql)) {
10953 if ($ignoreerrors) {
10954 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.
10955 }
10956 //$this->errors = $db->lasterror();
10957 return false;
10958 }
10959 }
10960
10961 return true;
10962 }
10963
10978 public static function commonReplaceContact(DoliDB $dbs, $origin_id, $dest_id, array $tables, $fieldname = 'fk_socpeople', $ignoreerrors = 0)
10979 {
10980 global $hookmanager;
10981
10982 // Table and column names are concatenated into the SQL, so they are validated as a defence in
10983 // depth: this method is public and static, hence callable from any module.
10984 if (!preg_match('/^[a-z0-9_]+$/', $fieldname)) {
10985 dol_syslog(__METHOD__.' Refused an invalid column name: '.$fieldname, LOG_ERR);
10986 return false;
10987 }
10988
10989 $parameters = array(
10990 'origin_id' => $origin_id,
10991 'dest_id' => $dest_id,
10992 'tables' => $tables,
10993 'fieldname' => $fieldname,
10994 );
10995 $reshook = $hookmanager->executeHooks('commonReplaceContact', $parameters);
10996 if ($reshook > 0) {
10997 return true; // replacement code
10998 } elseif ($reshook < 0) {
10999 return $ignoreerrors === 1; // failure
11000 } // reshook = 0 => execute normal code
11001
11002 foreach ($tables as $table) {
11003 if (!preg_match('/^[a-z0-9_]+$/', $table)) {
11004 dol_syslog(__METHOD__.' Refused an invalid table name: '.$table, LOG_ERR);
11005 return false;
11006 }
11007
11008 $sanitizedtable = $dbs->sanitize($table);
11009 $sanitizedfieldname = $dbs->sanitize($fieldname);
11010
11011 $sql = "UPDATE ".$dbs->prefix().$sanitizedtable;
11012 $sql .= " SET ".$sanitizedfieldname." = ".((int) $dest_id);
11013 $sql .= " WHERE ".$sanitizedfieldname." = ".((int) $origin_id);
11014
11015 if (!$dbs->query($sql)) {
11016 if ($ignoreerrors) {
11017 return true;
11018 }
11019 return false;
11020 }
11021 }
11022
11023 return true;
11024 }
11025
11039 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0, $qty = 0)
11040 {
11041 global $conf;
11042
11043 $buyPrice = 0;
11044
11045 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && getDolGlobalInt('ForceBuyingPriceIfNull') > 0)) {
11046 // When ForceBuyingPriceIfNull is set
11047 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
11048 } else {
11049 // Get cost price for margin calculation
11050 if (!empty($fk_product) && $fk_product > 0) {
11051 $result = 0;
11052 if (getDolGlobalString('MARGIN_TYPE') == 'costprice') {
11053 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
11054 $product = new Product($this->db);
11055 $result = $product->fetch($fk_product);
11056 if ($result <= 0) {
11057 $this->errors[] = 'ErrorProductIdDoesNotExists';
11058 return -1;
11059 }
11060 if ($product->cost_price > 0) {
11061 $buyPrice = $product->cost_price;
11062 } elseif ($product->pmp > 0) {
11063 $buyPrice = $product->pmp;
11064 }
11065 } elseif (getDolGlobalString('MARGIN_TYPE') == 'pmp') {
11066 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
11067 $product = new Product($this->db);
11068 $result = $product->fetch($fk_product);
11069 if ($result <= 0) {
11070 $this->errors[] = 'ErrorProductIdDoesNotExists';
11071 return -1;
11072 }
11073 if ($product->pmp > 0) {
11074 $buyPrice = $product->pmp;
11075 }
11076 }
11077
11078 if (empty($buyPrice) && in_array(getDolGlobalString('MARGIN_TYPE'), array('1', 'pmp', 'costprice'))) {
11079 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
11080 $productFournisseur = new ProductFournisseur($this->db);
11081 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product, $qty);
11082 if ($result == 0 && $qty > 0) {
11083 // No supplier price defined for such a low quantity, fall back on the lowest known price
11084 $result = $productFournisseur->find_min_price_product_fournisseur($fk_product);
11085 }
11086 if ($result > 0) {
11087 $buyPrice = $productFournisseur->fourn_unitprice;
11088 } elseif ($result < 0) {
11089 $this->errors[] = $productFournisseur->error;
11090 return -2;
11091 }
11092 }
11093 }
11094 }
11095
11096 return (float) $buyPrice;
11097 }
11098
11110 public function getLinkedBuyPriceDocuments($user, $lineid, $oldbuyprice = null)
11111 {
11112 $documents = array();
11113
11114 if (!getDolGlobalString('MARGIN_CAN_UPDATE_BUYINGPRICE_ON_LINKED_DOCUMENTS') || !$user->hasRight('margins', 'creer')) {
11115 return $documents;
11116 }
11117
11118 $sql = "SELECT fk_product, ".($this->element == 'order_supplier' ? "subprice * (1 - remise_percent / 100)" : "buy_price_ht")." as buy_price_ht FROM ".$this->db->prefix().$this->table_element_line;
11119 $sql .= " WHERE rowid = ".((int) $lineid)." AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
11120 $resql = $this->db->query($sql);
11121 $line = ($resql ? $this->db->fetch_object($resql) : null);
11122 if (!$line || $line->fk_product <= 0 || $line->buy_price_ht <= 0 || (isset($oldbuyprice) && price2num($oldbuyprice, 'MU') == price2num($line->buy_price_ht, 'MU'))) {
11123 return $documents;
11124 }
11125
11126 // The cost price is not an accounting data, so the status of the linked documents is not checked (like in margin/checkMargins.php)
11127 $this->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
11128
11129 if ($this->element == 'order_supplier') {
11130 // Several purchase orders can be linked to the same documents, so the cost is the average net unit price of the product on all of them, weighted by the quantities
11131 $orderids = array((int) $this->id);
11132 $sql = "SELECT fk_source, sourcetype, fk_target, targettype FROM ".$this->db->prefix()."element_element WHERE 1 = 0";
11133 foreach (array('propal', 'commande', 'facture') as $element) {
11134 $linkedids = array_map('intval', $this->linkedObjectsIds[$element] ?? array());
11135 if ($linkedids) {
11136 $sql .= " OR (sourcetype = '".$this->db->escape($element)."' AND fk_source IN (".$this->db->sanitize(implode(',', $linkedids)).") AND targettype = 'order_supplier')";
11137 $sql .= " OR (targettype = '".$this->db->escape($element)."' AND fk_target IN (".$this->db->sanitize(implode(',', $linkedids)).") AND sourcetype = 'order_supplier')";
11138 }
11139 }
11140 $resql = $this->db->query($sql);
11141 while ($resql && $obj = $this->db->fetch_object($resql)) {
11142 $orderids[] = (int) ($obj->targettype == 'order_supplier' ? $obj->fk_target : $obj->fk_source);
11143 }
11144
11145 // Limit: the purchase orders are supposed to cover the sold quantity, a part bought elsewhere (stock) is not valued
11146 $sql = "SELECT SUM(d.qty * d.subprice * (1 - d.remise_percent / 100)) / SUM(d.qty) as cost";
11147 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t, ".$this->db->prefix().$this->table_element_line." as d";
11148 $sql .= " WHERE d.".$this->db->sanitize($this->fk_element)." = t.rowid AND t.entity IN (".getEntity($this->table_element).")";
11149 $sql .= " AND t.rowid IN (".$this->db->sanitize(implode(',', $orderids)).")";
11150 $sql .= " AND (t.rowid = ".((int) $this->id)." OR t.fk_statut BETWEEN 3 AND 5)"; // This purchase order, and the other ones if ordered or received
11151 $sql .= " AND d.fk_product = ".((int) $line->fk_product)." AND d.qty > 0";
11152 $resql = $this->db->query($sql);
11153 $obj = ($resql ? $this->db->fetch_object($resql) : null);
11154 if ($obj && $obj->cost > 0) {
11155 $line->buy_price_ht = $obj->cost;
11156 }
11157 }
11158
11159 foreach (array('propal', 'commande', 'facture') as $element) {
11160 $ids = array();
11161 foreach ($this->linkedObjectsIds[$element] ?? array() as $id) {
11162 if (restrictedArea($user, $element, $id, '', '', 'fk_soc', 'rowid', 0, 1, 'write')) {
11163 $ids[] = (int) $id;
11164 }
11165 }
11166 if (empty($ids)) {
11167 continue;
11168 }
11169 $sql = "SELECT d.rowid, d.buy_price_ht, t.ref FROM ".$this->db->prefix().$element." as t, ".$this->db->prefix().$element."det as d";
11170 $sql .= " WHERE d.fk_".$this->db->sanitize($element)." = t.rowid AND t.entity IN (".getEntity($element).")";
11171 $sql .= " AND t.rowid IN (".$this->db->sanitize(implode(',', $ids)).")";
11172 $sql .= " AND d.fk_product = ".((int) $line->fk_product);
11173 $resql = $this->db->query($sql);
11174 while ($resql && $obj = $this->db->fetch_object($resql)) {
11175 if (price2num($obj->buy_price_ht, 'MU') != price2num($line->buy_price_ht, 'MU')) {
11176 $documents[$element]['refs'][$obj->ref] = $obj->ref;
11177 $documents[$element]['lineids'][] = (int) $obj->rowid;
11178 $documents[$element]['buyprice'] = (float) $line->buy_price_ht;
11179 }
11180 }
11181 }
11182
11183 return $documents;
11184 }
11185
11194 public function updateLinkedBuyPrice($user, $lineid, $elements)
11195 {
11196 $nbupdated = 0;
11197
11198 $this->db->begin();
11199 foreach ($this->getLinkedBuyPriceDocuments($user, $lineid) as $element => $document) {
11200 if (empty($elements[$element])) {
11201 continue;
11202 }
11203 $sql = "UPDATE ".$this->db->prefix().$element."det SET buy_price_ht = ".((float) $document['buyprice']);
11204 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $document['lineids'])).")";
11205 if (!$this->db->query($sql)) {
11206 $this->error = $this->db->lasterror();
11207 $this->db->rollback();
11208 return -1;
11209 }
11210 $nbupdated += count($document['lineids']);
11211 }
11212 $this->db->commit();
11213
11214 return $nbupdated;
11215 }
11216
11224 public function getDataToShowPhoto($modulepart, $imagesize)
11225 {
11226 // See getDataToShowPhoto() implemented by Product for example.
11227 return array('dir' => '', 'file' => '', 'originalfile' => '', 'altfile' => '', 'email' => '', 'capture' => '');
11228 }
11229
11230
11231 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
11251 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')
11252 {
11253 // phpcs:enable
11254 global $user, $langs;
11255
11256 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
11257 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
11258 include_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
11259
11260 $sortfield = 'position_name';
11261 $sortorder = 'asc';
11262
11263 $dir = $sdir.'/';
11264 $pdir = '/';
11265
11266 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
11267 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
11268
11269 // For backward compatibility
11270 if ($modulepart == 'product') {
11271 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
11272 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
11273 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
11274 }
11275 }
11276 if ($modulepart == 'category') {
11277 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
11278 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
11279 }
11280
11281 // Defined relative dir to DOL_DATA_ROOT
11282 $relativedir = '';
11283 if ($dir) {
11284 $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
11285 $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
11286 $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
11287 }
11288
11289 $dirthumb = $dir.'thumbs/';
11290 $pdirthumb = $pdir.'thumbs/';
11291
11292 $return = '<!-- Photo -->'."\n";
11293 $nbphoto = 0;
11294
11295 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
11296
11297 /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatibility, we scan also old dirs
11298 {
11299 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
11300 $filearray=array_merge($filearray, $filearrayold);
11301 }*/
11302
11303 completeFileArrayWithDatabaseInfo($filearray, $relativedir, $this);
11304 '@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';
11305
11306 $useLinkPathPhoto = false;
11307
11308 if (getDolGlobalInt('PRODUCT_USE_LINK_PATH_FOR_PHOTO')) {
11309 $link = new Link($this->db);
11310 $links = array();
11311 $link->fetchAll($links, 'product', $this->id);
11312
11313 if (count($links) > 0) {
11314 $useLinkPathPhoto = true;
11315 }
11316
11317 if ($useLinkPathPhoto) {
11318 // Start table or div based on nbbyrow
11319 if ($nbbyrow > 0) {
11320 $return .= '<table class="valigntop center centpercent" style="border:0; padding:2px; border-spacing:2px; border-collapse: separate;">';
11321 }
11322
11323 $i = 0;
11324 foreach ($links as $link) {
11325 if (!empty($link->url) && preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $link->url)) {
11326 $url = dol_escape_htmltag($link->url);
11327 $i++;
11328 $nbphoto++;
11329
11330 if ($nbbyrow > 0 && ($i % $nbbyrow == 1)) {
11331 $return .= '<tr class="center valignmiddle">';
11332 }
11333
11334 if ($nbbyrow > 0) {
11335 $return .= '<td style="width:'.ceil(100 / $nbbyrow).'%" class="photo">';
11336 } else {
11337 $return .= '<div class="inline-block">';
11338 }
11339
11340 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'"'.($maxHeight ? ' height="'.$maxHeight.'"' : '').' src="'.$url.'" title="External image">';
11341
11342 if ($nbbyrow > 0) {
11343 $return .= '</td>';
11344 if ($i % $nbbyrow == 0) {
11345 $return .= '</tr>';
11346 }
11347 } else {
11348 $return .= '</div>';
11349 }
11350
11351 if ($nbmax && $nbphoto >= $nbmax) {
11352 break;
11353 }
11354 }
11355 }
11356
11357 if ($nbbyrow > 0) {
11358 while ($i % $nbbyrow) {
11359 $return .= '<td style="width:'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
11360 $i++;
11361 }
11362 if ($nbphoto) {
11363 $return .= '</table>';
11364 }
11365 }
11366 }
11367 }
11368
11369 if (count($filearray)) {
11370 if ($sortfield && $sortorder) {
11371 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
11372 }
11373
11374 foreach ($filearray as $key => $val) {
11375 $photo = '';
11376 $file = $val['name'];
11377
11378 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
11379 if (image_format_supported($file) >= 0) {
11380 $nbphoto++;
11381 $photo = $file;
11382 $viewfilename = $file;
11383
11384 if ($size == 1 || $size == 'small') { // Format vignette
11385 // Find name of thumb file
11386 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
11387 if (!dol_is_file($dirthumb.$photo_vignette)) {
11388 // The thumb does not exists, so we will use the original file
11389 $dirthumb = $dir;
11390 $pdirthumb = $pdir;
11391 $photo_vignette = basename($file);
11392 }
11393
11394 // Get filesize of original file
11395 $imgarray = dol_getImageSize($dir.$photo);
11396
11397 if ($nbbyrow > 0) {
11398 if ($nbphoto == 1) {
11399 $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
11400 }
11401
11402 if ($nbphoto % $nbbyrow == 1) {
11403 $return .= '<tr class="center valignmiddle" style="border: 1px">';
11404 }
11405 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
11406 } elseif ($nbbyrow < 0) {
11407 $return .= '<div class="inline-block">'."\n";
11408 }
11409
11410 $relativefile = preg_replace('/^\//', '', $pdir.$photo);
11411 if (empty($nolink)) {
11412 $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
11413 if ($urladvanced) {
11414 $return .= '<a href="'.$urladvanced.'">';
11415 } else {
11416 $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
11417 }
11418 }
11419
11420 // Show image (width height=$maxHeight)
11421 // If thumb file available and image source is too large, we use the thumb, otherwise we use the original photo
11422 $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
11423 $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
11424 if ($overwritetitle) {
11425 if (is_numeric($overwritetitle)) {
11426 $alt = '';
11427 } else {
11428 $alt = $overwritetitle;
11429 }
11430 }
11431 if (empty($cache) && !empty($val['label'])) {
11432 // label is md5 of file
11433 // use it in url to say we want to cache this version of the file
11434 $cache = $val['label'];
11435 }
11436 if ($usesharelink) {
11437 if (array_key_exists('share', $val) && $val['share']) {
11438 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
11439 $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
11440 $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).'">';
11441 } else {
11442 $return .= '<!-- Show original file -->';
11443 $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).'">';
11444 }
11445 } else {
11446 $return .= '<!-- Show nophoto file (because file is not shared) -->';
11447 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
11448 }
11449 } else {
11450 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
11451 $return .= '<!-- Show thumb -->';
11452 $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).'">';
11453 } else {
11454 $return .= '<!-- Show original file -->';
11455 $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).'">';
11456 }
11457 }
11458
11459 if (empty($nolink)) {
11460 $return .= '</a>';
11461 }
11462
11463 if ($showfilename) {
11464 $return .= '<br>'.$viewfilename;
11465 }
11466 if ($showaction) {
11467 $return .= '<br>';
11468 // If $photo_vignette set, we add a link to generate thumbs if file is an image and width or height higher than limits
11469 if ($photo_vignette && (image_format_supported($photo) > 0) && ((isset($imgarray['width']) && $imgarray['width'] > $maxWidth) || (isset($imgarray['width']) && $imgarray['width'] > $maxHeight))) {
11470 $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>';
11471 }
11472 // Special case for product
11473 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
11474 // Link to resize
11475 $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; ';
11476
11477 // Link to delete
11478 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
11479 $return .= img_delete().'</a>';
11480 }
11481 }
11482 $return .= "\n";
11483
11484 if ($nbbyrow > 0) {
11485 $return .= '</td>';
11486 if (($nbphoto % $nbbyrow) == 0) {
11487 $return .= '</tr>';
11488 }
11489 } elseif ($nbbyrow < 0) {
11490 $return .= '</div>'."\n";
11491 }
11492 }
11493
11494 if (empty($size)) { // Format origine
11495 $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
11496
11497 if ($showfilename) {
11498 $return .= '<br>'.$viewfilename;
11499 }
11500 if ($showaction) {
11501 // Special case for product
11502 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
11503 // Link to resize
11504 $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; ';
11505
11506 // Link to delete
11507 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
11508 $return .= img_delete().'</a>';
11509 }
11510 }
11511 }
11512
11513 // On continue ou on arrete de boucler ?
11514 if ($nbmax && $nbphoto >= $nbmax) {
11515 break;
11516 }
11517 }
11518 }
11519
11520 if ($size == 1 || $size == 'small') {
11521 if ($nbbyrow > 0) {
11522 // Ferme tableau
11523 while ($nbphoto % $nbbyrow) {
11524 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
11525 $nbphoto++;
11526 }
11527
11528 if ($nbphoto) {
11529 $return .= '</table>';
11530 }
11531 }
11532 }
11533 }
11534
11535 $this->nbphoto = $nbphoto;
11536
11537 return $return;
11538 }
11539
11540
11547 protected function isArray($info)
11548 {
11549 if (is_array($info)) {
11550 if (isset($info['type']) && $info['type'] == 'array') {
11551 return true;
11552 } else {
11553 return false;
11554 }
11555 }
11556 return false;
11557 }
11558
11565 public function isDate($info)
11566 {
11567 if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
11568 return true;
11569 }
11570 return false;
11571 }
11572
11579 public function isDuration($info)
11580 {
11581 if (is_array($info)) {
11582 if (isset($info['type']) && ($info['type'] == 'duration')) {
11583 return true;
11584 } else {
11585 return false;
11586 }
11587 } else {
11588 return false;
11589 }
11590 }
11591
11598 public function isInt($info)
11599 {
11600 if (is_array($info)) {
11601 if (isset($info['type']) && (preg_match('/^(?:tiny|small|medium|big)?int|int$/i', $info['type']))) {
11602 return true;
11603 } else {
11604 return false;
11605 }
11606 } else {
11607 return false;
11608 }
11609 }
11610
11617 public function isFloat($info)
11618 {
11619 if (is_array($info)) {
11620 if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
11621 return true;
11622 } else {
11623 return false;
11624 }
11625 }
11626 return false;
11627 }
11628
11635 public function isText($info)
11636 {
11637 if (is_array($info)) {
11638 if (isset($info['type']) && $info['type'] == 'text') {
11639 return true;
11640 } else {
11641 return false;
11642 }
11643 }
11644 return false;
11645 }
11646
11653 protected function canBeNull($info)
11654 {
11655 if (is_array($info)) {
11656 if (array_key_exists('notnull', $info) && $info['notnull'] != '1') {
11657 return true;
11658 } else {
11659 return false;
11660 }
11661 }
11662 return true;
11663 }
11664
11671 protected function isForcedToNullIfZero($info)
11672 {
11673 if (is_array($info)) {
11674 if (array_key_exists('notnull', $info) && $info['notnull'] == '-1') {
11675 return true;
11676 } else {
11677 return false;
11678 }
11679 }
11680 return false;
11681 }
11682
11689 protected function isIndex($info)
11690 {
11691 if (is_array($info)) {
11692 if (array_key_exists('index', $info) && $info['index'] == true) {
11693 return true;
11694 } else {
11695 return false;
11696 }
11697 }
11698 return false;
11699 }
11700
11701
11711 protected function setSaveQuery()
11712 {
11713 global $conf;
11714
11715 $queryarray = array();
11716 foreach ($this->fields as $field => $info) { // Loop on definition of fields
11717 // Depending on field type ('datetime', ...)
11718 if ($this->isDate($info)) {
11719 if (empty($this->{$field})) {
11720 $queryarray[$field] = null;
11721 } else {
11722 $queryarray[$field] = $this->db->idate($this->{$field});
11723 }
11724 } elseif ($this->isDuration($info)) {
11725 // $this->{$field} may be null, '', 0, '0', 123, '123'
11726 if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
11727 if (!isset($this->{$field})) {
11728 if (!empty($info['default'])) {
11729 $queryarray[$field] = $info['default']; // From safe source @phan-suppress-current-line SqlInjection
11730 } else {
11731 $queryarray[$field] = 0;
11732 }
11733 } else {
11734 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
11735 }
11736 } else {
11737 $queryarray[$field] = null;
11738 }
11739 } elseif ($this->isInt($info) || $this->isFloat($info)) {
11740 if ($field == 'entity' && is_null($this->{$field})) {
11741 $queryarray[$field] = ((int) $conf->entity);
11742 } else {
11743 // $this->{$field} may be null, '', 0, '0', 123, '123'
11744 if ((isset($this->{$field}) && ((string) $this->{$field}) != '') || !empty($info['notnull'])) {
11745 if (!isset($this->{$field})) {
11746 $queryarray[$field] = 0;
11747 } elseif ($this->isInt($info)) {
11748 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
11749 } elseif ($this->isFloat($info)) {
11750 $queryarray[$field] = (float) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
11751 }
11752 } else {
11753 $queryarray[$field] = null;
11754 }
11755 }
11756 } else {
11757 // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
11758 // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
11759 $queryarray[$field] = $this->{$field}; // @phan-suppress-current-line SqlInjection
11760 }
11761
11762 if (is_array($info) && array_key_exists('type', $info) && !empty($info['type']) && $info['type'] == 'timestamp' && empty($queryarray[$field])) {
11763 unset($queryarray[$field]);
11764 }
11765 if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
11766 $queryarray[$field] = null; // May force 0 to null
11767 }
11768 }
11769
11770 return $queryarray;
11771 }
11772
11779 public function setVarsFromFetchObj(&$obj)
11780 {
11781 global $db;
11782
11783 foreach ($this->fields as $field => $info) {
11784 if ($this->isDate($info)) {
11785 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') {
11786 $this->$field = '';
11787 } else {
11788 $this->$field = $db->jdate($obj->$field);
11789 }
11790 } elseif ($this->isInt($info)) {
11791 if ($field == 'rowid') {
11792 $this->id = (int) $obj->$field;
11793 } else {
11794 if ($this->isForcedToNullIfZero($info)) {
11795 if (empty($obj->$field)) {
11796 $this->$field = null;
11797 } else {
11798 $this->$field = (int) $obj->$field;
11799 }
11800 } else {
11801 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
11802 $this->$field = (int) $obj->$field;
11803 } else {
11804 $this->$field = null;
11805 }
11806 }
11807 }
11808 } elseif ($this->isFloat($info)) {
11809 if ($this->isForcedToNullIfZero($info)) {
11810 if (empty($obj->$field)) {
11811 $this->$field = null;
11812 } else {
11813 $this->$field = (float) $obj->$field;
11814 }
11815 } else {
11816 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
11817 $this->$field = (float) $obj->$field;
11818 } else {
11819 $this->$field = null;
11820 }
11821 }
11822 } else {
11823 $this->$field = isset($obj->$field) ? $obj->$field : null;
11824 }
11825 }
11826
11827 // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
11828 if (!isset($this->fields['ref']) && isset($this->id)) {
11829 $this->ref = (string) $this->id;
11830 }
11831 }
11832
11837 public function emtpyObjectVars()
11838 {
11839 foreach ($this->fields as $field => $arr) {
11840 $this->$field = null;
11841 }
11842 }
11843
11851 public function getFieldList($alias = '', $excludefields = array())
11852 {
11853 $keys = array_keys($this->fields);
11854 if (!empty($alias)) {
11855 $keys_with_alias = array();
11856 foreach ($keys as $fieldname) {
11857 if (!empty($excludefields)) {
11858 if (in_array($fieldname, $excludefields)) { // The field is excluded and must not be in output
11859 continue;
11860 }
11861 }
11862 $keys_with_alias[] = $this->db->sanitize($alias . '.' . $fieldname);
11863 }
11864 return implode(', ', $keys_with_alias);
11865 } else {
11866 return implode(', ', $keys);
11867 }
11868 }
11869
11877 protected function quote($value, $fieldsentry)
11878 {
11879 if (is_null($value)) {
11880 return 'NULL';
11881 } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
11882 return price2num((string) $value);
11883 } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
11884 return (int) $value;
11885 } elseif ($fieldsentry['type'] == 'boolean') {
11886 if ($value) {
11887 return 'true';
11888 } else {
11889 return 'false';
11890 }
11891 } else {
11892 return "'".$this->db->escape($value)."'";
11893 }
11894 }
11895
11896
11904 public function createCommon(User $user, $notrigger = 0)
11905 {
11906 global $conf;
11907 //global $langs; // Should be able to work with $langs loaded
11908
11909 dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
11910
11911 $error = 0;
11912
11913 $now = dol_now();
11914
11915 $fieldvalues = $this->setSaveQuery();
11916
11917 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
11918
11919 if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
11920 $fieldvalues['date_creation'] = $this->db->idate($now);
11921 $this->date_creation = $this->db->idate($now);
11922 }
11923 // For backward compatibility, if a property ->fk_user_creat exists and not filled.
11924 if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
11925 $fieldvalues['fk_user_creat'] = $user->id;
11926 $this->fk_user_creat = $user->id;
11927 }
11928 if (array_key_exists('user_creation_id', $fieldvalues) && !($fieldvalues['user_creation_id'] > 0)) {
11929 $fieldvalues['user_creation_id'] = $user->id;
11930 $this->user_creation_id = $user->id;
11931 }
11932 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass')) {
11933 // @phan-suppress-next-line PhanUndeclaredProperty
11934 $tmparray = dol_hash($this->pass, '0', 0, 1);
11935 $fieldvalues['pass_crypted'] = $tmparray['pass_encrypted'];
11936 if (array_key_exists('pass_encoding', $fieldvalues) && property_exists($this, 'pass_encoding')) {
11937 $fieldvalues['pass_encoding'] = $tmparray['pass_encoding'];
11938 }
11939 }
11940 if (array_key_exists('ref', $fieldvalues)) {
11941 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
11942 }
11943 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
11944 $fieldvalues['tms'] = $this->db->idate($now);
11945 }
11946
11947 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
11948
11949 $sanitized_keys = array();
11950 $sanitized_values = array(); // Array to store string forged for SQL syntax
11951 foreach ($fieldvalues as $k => $v) {
11952 $sanitized_keys[$k] = $k; // Safe source @phan-suppress-current-line SqlInjection
11953 $value = $this->fields[$k];
11954 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
11955 $sanitized_values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
11956 }
11957
11958 // Clean and check mandatory
11959 foreach ($sanitized_keys as $key) {
11960 if (!isset($this->fields[$key])) {
11961 continue;
11962 }
11963 $key_fields = $this->fields[$key];
11964
11965 // If field is an implicit foreign key field (so type = 'integer:...')
11966 if (preg_match('/^integer:/i', $key_fields['type']) && $sanitized_values[$key] == '-1') {
11967 $sanitized_values[$key] = '';
11968 }
11969 if (!empty($key_fields['foreignkey']) && $sanitized_values[$key] == '-1') {
11970 $sanitized_values[$key] = '';
11971 }
11972
11973 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']))) {
11974 $error++;
11975 global $langs;
11976 if (empty($langs)) {
11977 require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
11978 $langs = new Translate('', $conf);
11979 $langs->setDefaultLang();
11980 $langs->load("errors");
11981 }
11982 dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
11983 $this->errors[] = $langs->trans("ErrorFieldRequired", isset($key_fields['label']) ? $key_fields['label'] : $key);
11984 }
11985
11986 // If value is null and there is a default value for field @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
11987 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'])) {
11988 $sanitized_values[$key] = $this->quote($key_fields['default'], $key_fields);
11989 }
11990
11991 // If field is an implicit foreign key field (so type = 'integer:...')
11992 if (isset($key_fields['type']) && preg_match('/^integer:/i', $key_fields['type']) && empty($sanitized_values[$key])) {
11993 if (isset($key_fields['default'])) {
11994 $sanitized_values[$key] = ((int) $key_fields['default']);
11995 } else {
11996 $sanitized_values[$key] = 'null';
11997 }
11998 }
11999 if (!empty($key_fields['foreignkey']) && empty($sanitized_values[$key])) {
12000 $sanitized_values[$key] = 'null';
12001 }
12002 }
12003
12004 if ($error) {
12005 return -1;
12006 }
12007
12008 $this->db->begin();
12009
12010 if (!$error) {
12011 $sql = "INSERT INTO ".$this->db->prefix().$this->db->sanitize($this->table_element);
12012 $sql .= " (".implode(", ", $sanitized_keys).')';
12013 $sql .= " VALUES (".implode(", ", $sanitized_values).")"; // $sanitized_values can contains 'abc' or 123
12014
12015 $res = $this->db->query($sql);
12016 if (!$res) {
12017 $error++;
12018 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
12019 $this->errors[] = "ErrorRefAlreadyExists";
12020 } else {
12021 $this->errors[] = $this->db->lasterror();
12022 }
12023 }
12024 }
12025
12026 if (!$error) {
12027 $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
12028 }
12029
12030 // If we have a field ref with a default value of (PROV)
12031 if (!$error) {
12032 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
12033 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)') {
12034 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
12035 $sql .= " SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
12036 $resqlupdate = $this->db->query($sql);
12037
12038 if ($resqlupdate === false) {
12039 $error++;
12040 $this->errors[] = $this->db->lasterror();
12041 } else {
12042 $this->ref = '(PROV'.$this->id.')';
12043 }
12044 }
12045 }
12046
12047 // Create extrafields
12048 if (!$error) {
12049 $result = $this->insertExtraFields();
12050 if ($result < 0) {
12051 $error++;
12052 }
12053 }
12054
12055 // Create lines
12056 if (!empty($this->table_element_line) && !empty($this->fk_element) && !empty($this->lines)) {
12057 foreach ($this->lines as $line) {
12058 $keyforparent = $this->fk_element;
12059 $line->$keyforparent = $this->id;
12060
12061 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
12062 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
12063 if (!is_object($line)) {
12064 $line = (object) $line;
12065 }
12066
12067 $result = 0;
12068 if (method_exists($line, 'insert')) {
12069 $result = $line->insert($user, 1);
12070 } elseif (method_exists($line, 'create')) {
12071 $result = $line->create($user, 1);
12072 }
12073 if ($result < 0) {
12074 $this->error = $line->error;
12075 $this->db->rollback();
12076 return -1;
12077 }
12078 }
12079 }
12080
12081 // Triggers
12082 if (!$error && !$notrigger) {
12083 // Call triggers
12084 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
12085 $result = $this->call_trigger($triggerPrefix.'_CREATE', $user);
12086 if ($result < 0) {
12087 $error++;
12088 }
12089 // End call triggers
12090 }
12091
12092 // Commit or rollback
12093 if ($error) {
12094 $this->db->rollback();
12095 return -1;
12096 } else {
12097 $this->db->commit();
12098 return $this->id;
12099 }
12100 }
12101
12102
12112 public function fetchCommon($id, $ref = null, $morewhere = '', $noextrafields = 0)
12113 {
12114 if (empty($id) && empty($ref) && empty($morewhere)) {
12115 return -1;
12116 }
12117
12118 $fieldlist = $this->getFieldList('t');
12119 if (empty($fieldlist)) {
12120 return 0;
12121 }
12122
12123 $sql = "SELECT ".$this->db->sanitize($fieldlist, 0, 0, 1);
12124 $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
12125
12126 if (!empty($id)) {
12127 $sql .= ' WHERE t.rowid = '.((int) $id);
12128 } elseif (!empty($ref)) {
12129 $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
12130 } else {
12131 $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
12132 }
12133 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
12134 $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
12135 }
12136 if ($morewhere) {
12137 $sql .= $morewhere;
12138 }
12139 $sql .= ' LIMIT 1'; // This is a fetch, to be certain to get only one record
12140
12141 $res = $this->db->query($sql);
12142 if ($res) {
12143 $obj = $this->db->fetch_object($res);
12144 if ($obj) {
12145 $this->setVarsFromFetchObj($obj);
12146
12147 // Retrieve all extrafield
12148 // fetch optionals attributes and labels
12149 if (empty($noextrafields)) {
12150 $result = $this->fetch_optionals();
12151 if ($result < 0) {
12152 $this->error = $this->db->lasterror();
12153 $this->errors[] = $this->error;
12154 return -4;
12155 }
12156 }
12157
12158 return $this->id;
12159 } else {
12160 return 0;
12161 }
12162 } else {
12163 $this->error = $this->db->lasterror();
12164 $this->errors[] = $this->error;
12165 return -1;
12166 }
12167 }
12168
12176 public function fetchLinesCommon($morewhere = '', $noextrafields = 0)
12177 {
12178 $objectlineclassname = get_class($this).'Line';
12179 if (!class_exists($objectlineclassname)) {
12180 $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
12181 return -1;
12182 }
12183
12184 $objectline = new $objectlineclassname($this->db);
12185 '@phan-var-force CommonObjectLine $objectline';
12186
12187 $sql = "SELECT ".$objectline->getFieldList('l');
12188 $sql .= " FROM ".$this->db->prefix().$this->db->sanitize($objectline->table_element)." as l";
12189 $sql .= " WHERE l.fk_".$this->db->sanitize($this->element)." = ".((int) $this->id);
12190 if ($morewhere) {
12191 $sql .= $morewhere;
12192 }
12193 if (isset($objectline->fields['position'])) {
12194 $sql .= $this->db->order('position', 'ASC');
12195 }
12196
12197 $resql = $this->db->query($sql);
12198 if ($resql) {
12199 $num_rows = $this->db->num_rows($resql);
12200 $i = 0;
12201 $this->lines = array();
12202 while ($i < $num_rows) {
12203 $obj = $this->db->fetch_object($resql);
12204 if ($obj) {
12205 $newline = new $objectlineclassname($this->db);
12206 '@phan-var-force CommonObjectLine $newline';
12207 $newline->setVarsFromFetchObj($obj);
12208
12209 // Load also extrafields for the line
12210 if (empty($noextrafields)) {
12211 $newline->fetch_optionals();
12212 }
12213
12214 $this->lines[] = $newline;
12215 }
12216 $i++;
12217 }
12218
12219 return 1;
12220 } else {
12221 $this->error = $this->db->lasterror();
12222 $this->errors[] = $this->error;
12223 return -1;
12224 }
12225 }
12226
12234 public function updateCommon(User $user, $notrigger = 0)
12235 {
12236 dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
12237
12238 $error = 0;
12239
12240 $now = dol_now();
12241
12242 // $this->oldcopy should have been set by the caller of update
12243 //if (empty($this->oldcopy)) {
12244 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
12245 // $this->oldcopy = dol_clone($this, 2);
12246 //}
12247
12248 $fieldvalues = $this->setSaveQuery();
12249
12250 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
12251
12252 if (array_key_exists('date_modification', $fieldvalues)) {
12253 $fieldvalues['date_modification'] = $this->db->idate($now);
12254 }
12255 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
12256 $fieldvalues['tms'] = $this->db->idate($now);
12257 }
12258 if (array_key_exists('fk_user_modif', $fieldvalues)) {
12259 $fieldvalues['fk_user_modif'] = $user->id;
12260 }
12261 if (array_key_exists('user_modification_id', $fieldvalues)) {
12262 $fieldvalues['user_modification_id'] = $user->id;
12263 }
12264 // @phan-suppress-next-line PhanUndeclaredProperty
12265 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass') && !empty($this->pass)) {
12266 // @phan-suppress-next-line PhanUndeclaredProperty
12267 $tmparray = dol_hash($this->pass, '0', 0, 1);
12268 $fieldvalues['pass_crypted'] = $tmparray['pass_encrypted'];
12269 if (array_key_exists('pass_encoding', $fieldvalues) && property_exists($this, 'pass_encoding')) {
12270 $fieldvalues['pass_encoding'] = $tmparray['pass_encoding'];
12271 }
12272 }
12273 if (array_key_exists('ref', $fieldvalues)) {
12274 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
12275 }
12276
12277 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
12278
12279 // Add quotes and escape on fields with type string
12280 $keys = array();
12281 $values = array();
12282 $sanitized_tmp = array();
12283 foreach ($fieldvalues as $k => $v) {
12284 $keys[$k] = $k;
12285 $value = $this->fields[$k];
12286 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
12287 $values[$k] = $this->quote($v, $value);
12288 if ((!empty($value["type"]) && $value["type"] == "text") && !empty($value['arrayofkeyval']) && is_array($value['arrayofkeyval'])) {
12289 // Clean values for text with selectbox
12290 $v = preg_replace('/\s/', ',', $v);
12291 $v = preg_replace('/,+/', ',', $v);
12292 }
12293 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition, SqlInjection
12294 $sanitized_tmp[] = $this->db->sanitize($k).'='.$this->quote($v, $this->fields[$k]);
12295 }
12296
12297 // Clean and check mandatory fields
12298 foreach ($keys as $key) {
12299 if (!empty($this->fields[$key]['type']) && preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
12300 $values[$key] = ''; // This is an implicit foreign key field
12301 }
12302 if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
12303 $values[$key] = ''; // This is an explicit foreign key field
12304 }
12305
12306 //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
12307 /*
12308 if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
12309 {
12310 $error++;
12311 $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
12312 }*/
12313 }
12314
12315 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
12316 $sql .= " SET ".implode(', ', $sanitized_tmp);
12317 $sql .= " WHERE rowid = ".((int) $this->id);
12318
12319 $this->db->begin();
12320
12321 if (!$error) {
12322 $res = $this->db->query($sql);
12323 if (!$res) {
12324 $error++;
12325 $this->errors[] = $this->db->lasterror();
12326 }
12327 }
12328
12329 // Update extrafield
12330 if (!$error) {
12331 $result = $this->insertExtraFields(); // This update extrafields
12332 if ($result < 0) {
12333 $error++;
12334 }
12335 }
12336
12337 // Triggers
12338 if (!$error && !$notrigger) {
12339 // Call triggers
12340 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
12341 $result = $this->call_trigger($triggerPrefix.'_MODIFY', $user);
12342 if ($result < 0) {
12343 $error++;
12344 } //Do also here what you must do to rollback action if trigger fail
12345 // End call triggers
12346 }
12347
12348 // Commit or rollback
12349 if ($error) {
12350 $this->db->rollback();
12351 return -1;
12352 } else {
12353 $this->db->commit();
12354 return $this->id;
12355 }
12356 }
12357
12366 public function deleteCommon(User $user, $notrigger = 0, $forcechilddeletion = 0)
12367 {
12368 dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
12369
12370 $error = 0;
12371
12372 $this->db->begin();
12373
12374 if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
12375 foreach ($this->childtables as $table) {
12376 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($table);
12377 $sql .= " WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
12378 $resql = $this->db->query($sql);
12379 if (!$resql) {
12380 $this->error = $this->db->lasterror();
12381 $this->errors[] = $this->error;
12382 $this->db->rollback();
12383 return -1;
12384 }
12385 }
12386 } elseif (!empty($this->childtables)) { // If object has children linked with a foreign key field, we check all child tables.
12387 $objectisused = $this->isObjectUsed($this->id);
12388 if (!empty($objectisused)) {
12389 dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
12390 $this->error = 'ErrorRecordHasChildren';
12391 $this->errors[] = $this->error;
12392 $this->db->rollback();
12393 return 0;
12394 }
12395 }
12396
12397 // Delete cascade first
12398 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
12399 foreach ($this->childtablesoncascade as $tabletodelete) {
12400 $deleteFromObject = explode(':', $tabletodelete, 4);
12401 if (count($deleteFromObject) >= 2) {
12402 $className = str_replace('@', '', $deleteFromObject[0]);
12403 $filePath = $deleteFromObject[1];
12404 $columnName = $deleteFromObject[2];
12405 $filter = '';
12406 if (!empty($deleteFromObject[3])) {
12407 $filter = $deleteFromObject[3];
12408 }
12409
12410 if (dol_include_once($filePath)) {
12411 $childObject = new $className($this->db);
12412 if (method_exists($childObject, 'deleteByParentField')) {
12413 '@phan-var-force CommonObject $childObject';
12414 $result = $childObject->deleteByParentField($this->id, $columnName, $filter);
12415 if ($result < 0) {
12416 $error++;
12417 $this->errors[] = $childObject->error;
12418 break;
12419 }
12420 } else {
12421 $error++;
12422 $this->errors[] = "You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
12423 break;
12424 }
12425 } else {
12426 $error++;
12427 $this->errors[] = 'Cannot include child class file '.$filePath;
12428 break;
12429 }
12430 } else {
12431 // Delete record in child table
12432 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($tabletodelete)." WHERE ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
12433
12434 $resql = $this->db->query($sql);
12435 if (!$resql) {
12436 $error++;
12437 $this->error = $this->db->lasterror();
12438 $this->errors[] = $this->error;
12439 break;
12440 }
12441 }
12442 }
12443 }
12444
12445 if (!$error) {
12446 if (!$notrigger) {
12447 // Call triggers
12448 $triggerPrefix = (empty($this->TRIGGER_PREFIX) ? strtoupper(get_class($this)) : $this->TRIGGER_PREFIX);
12449 $result = $this->call_trigger($triggerPrefix.'_DELETE', $user);
12450 if ($result < 0) {
12451 $error++;
12452 } // Do also here what you must do to rollback action if trigger fail
12453 // End call triggers
12454 }
12455 }
12456
12457 // Delete llx_ecm_files
12458 if (!$error) {
12459 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
12460 if (!$res) {
12461 $error++;
12462 }
12463 }
12464
12465 if (!$error) {
12466 $dir = getMultidirOutput($this)."/".dol_sanitizeFileName($this->ref);
12467 // For remove dir
12468 require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
12469 if (dol_is_dir($dir)) {
12470 if (!dol_delete_dir_recursive($dir)) {
12471 $this->errors[] = 'ErrorFailToDeleteDir';
12472 }
12473 }
12474 }
12475
12476 // Delete linked object
12477 $res = $this->deleteObjectLinked();
12478 if ($res < 0) {
12479 $error++;
12480 }
12481
12482 if (!$error && !empty($this->isextrafieldmanaged)) {
12483 $result = $this->deleteExtraFields();
12484 if ($result < 0) {
12485 $error++;
12486 }
12487 }
12488
12489 if (!$error) {
12490 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
12491 $sql .= " WHERE rowid = ".((int) $this->id);
12492
12493 $resql = $this->db->query($sql);
12494 if (!$resql) {
12495 $error++;
12496 $this->errors[] = $this->db->lasterror();
12497 }
12498 }
12499
12500 // Commit or rollback
12501 if ($error) {
12502 $this->db->rollback();
12503 return -1;
12504 } else {
12505 $this->db->commit();
12506 return 1;
12507 }
12508 }
12509
12521 public function deleteByParentField($parentId = 0, $parentField = '', $filter = '', $filtermode = "AND")
12522 {
12523 global $user;
12524
12525 $error = 0;
12526 $deleted = 0;
12527
12528 //dol_syslog("deleteByParentField for ".$parentId.' '.$parentField);
12529
12530 if (!empty($parentId) && !empty($parentField)) {
12531 if (empty($this->table_element)) {
12532 $this->error = 'Property table_element for object is not defined';
12533 $this->errors[] = $this->error;
12534 $error++;
12535 return -1;
12536 }
12537 if (!method_exists($this, 'fetch')) {
12538 $this->error = 'Method fetch for object is not defined';
12539 $this->errors[] = $this->error;
12540 $error++;
12541 return -1;
12542 }
12543 if (!method_exists($this, 'delete')) {
12544 $this->error = 'Method delete for object is not defined';
12545 $this->errors[] = $this->error;
12546 $error++;
12547 return -1;
12548 }
12549
12550 $this->db->begin();
12551
12552 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element);
12553 $sql .= " WHERE ".$this->db->sanitize($parentField)." = ".(int) $parentId;
12554
12555 // Manage filter
12556 $errormessage = '';
12557 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
12558 if ($errormessage) {
12559 $this->errors[] = $errormessage;
12560 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
12561 return -1;
12562 }
12563
12564 $resql = $this->db->query($sql);
12565 if (!$resql) {
12566 $this->errors[] = $this->db->lasterror();
12567 $error++;
12568 } else {
12569 while ($obj = $this->db->fetch_object($resql)) {
12570 $result = $this->fetch($obj->rowid); // @phpstan-ignore-line
12571 if ($result < 0) {
12572 $error++;
12573 $this->errors[] = $this->error;
12574 } else {
12575 $result = $this->delete($user); // @phpstan-ignore-line
12576 if ($result < 0) {
12577 $error++;
12578 $this->errors[] = $this->error;
12579 } else {
12580 $deleted++;
12581 }
12582 }
12583 }
12584 }
12585
12586 if (empty($error)) {
12587 $this->db->commit();
12588 return $deleted;
12589 } else {
12590 $this->error = implode(', ', $this->errors);
12591 $this->db->rollback();
12592 return $error * -1;
12593 }
12594 }
12595
12596 return $deleted;
12597 }
12598
12606 public function isLineOfObject($lineid)
12607 {
12608 if (!($this->id > 0) || empty($this->table_element_line) || empty($this->fk_element)) {
12609 return true;
12610 }
12611
12612 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
12613 $sql .= " WHERE rowid = ".((int) $lineid)." AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
12614 $resql = $this->db->query($sql);
12615
12616 return ($resql && $this->db->num_rows($resql) > 0);
12617 }
12618
12627 public function deleteLineCommon(User $user, $idline, $notrigger = 0)
12628 {
12629 $error = 0;
12630
12631 $tmpforobjectclass = get_class($this);
12632 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
12633
12634 if ($this->id > 0 && !empty($this->fk_element)) {
12635 // The line must belong to this object
12636 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
12637 $sql .= " WHERE rowid = ".((int) $idline)." AND ".$this->db->sanitize($this->fk_element)." = ".((int) $this->id);
12638 $resql = $this->db->query($sql);
12639 if (!$resql || !$this->db->num_rows($resql)) {
12640 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
12641 return -1;
12642 }
12643 }
12644
12645 $this->db->begin();
12646
12647 // Call trigger
12648 $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
12649 if ($result < 0) {
12650 $error++;
12651 }
12652 // End call triggers
12653
12654 if (empty($error)) {
12655 $sql = "DELETE FROM ".$this->db->prefix().$this->db->sanitize($this->table_element_line);
12656 $sql .= " WHERE rowid = ".((int) $idline);
12657
12658 $resql = $this->db->query($sql);
12659 if (!$resql) {
12660 $this->error = "Error ".$this->db->lasterror();
12661 $error++;
12662 }
12663 }
12664
12665 if (empty($error)) {
12666 // Remove extrafields
12667 $tmpobjectline = new $tmpforobjectlineclass($this->db);
12668 '@phan-var-force CommonObjectLine $tmpobjectline';
12669 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
12670 $tmpobjectline->id = $idline;
12671 $result = $tmpobjectline->deleteExtraFields();
12672 if ($result < 0) {
12673 $error++;
12674 $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
12675 }
12676 }
12677 }
12678
12679 if (empty($error)) {
12680 $this->db->commit();
12681 return 1;
12682 } else {
12683 dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
12684 $this->db->rollback();
12685 return -1;
12686 }
12687 }
12688
12689
12700 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
12701 {
12702 $error = 0;
12703
12704 $this->db->begin();
12705
12706 $statusfield = 'status';
12707 if (in_array($this->element, array('don', 'donation', 'shipping', 'project_task'))) {
12708 $statusfield = 'fk_statut';
12709 }
12710
12711 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($this->table_element);
12712 $sql .= " SET ".$this->db->sanitize($statusfield)." = ".((int) $status);
12713 $sql .= " WHERE rowid = ".((int) $this->id);
12714
12715 if ($this->db->query($sql)) {
12716 if (!$error) {
12717 $this->oldcopy = clone $this;
12718 }
12719
12720 if (!$error && !$notrigger) {
12721 // Call trigger
12722 $result = $this->call_trigger($triggercode, $user);
12723 if ($result < 0) {
12724 $error++;
12725 }
12726 }
12727
12728 if (!$error) {
12729 $this->status = $status;
12730 if (property_exists($this, 'statut')) { // For backward compatibility
12731 $this->statut = $status;
12732 }
12733 $this->db->commit();
12734 return 1;
12735 } else {
12736 $this->db->rollback();
12737 return -1;
12738 }
12739 } else {
12740 $this->error = $this->db->error();
12741 $this->db->rollback();
12742 return -1;
12743 }
12744 }
12745
12752 public function initAsSpecimenCommon()
12753 {
12754 global $user;
12755
12756 $this->id = 0;
12757 $this->specimen = 1;
12758 $fields = array(
12759 'label' => 'This is label',
12760 'ref' => 'ABCD1234',
12761 'description' => 'This is a description',
12762 'qty' => 123.12,
12763 'note_public' => 'Public note',
12764 'note_private' => 'Private note',
12765 'date_creation' => (dol_now() - 3600 * 48),
12766 'date_modification' => (dol_now() - 3600 * 24),
12767 'fk_user_creat' => $user->id,
12768 'fk_user_modif' => $user->id,
12769 'date' => dol_now(),
12770 );
12771 foreach ($fields as $key => $value) {
12772 if (array_key_exists($key, $this->fields)) {
12773 $this->{$key} = $value; // @phpstan-ignore-line
12774 }
12775 }
12776
12777 // Force values to default values when known
12778 if (property_exists($this, 'fields')) {
12779 foreach ($this->fields as $key => $value) {
12780 // If fields are already set, do nothing
12781 if (array_key_exists($key, $fields)) {
12782 continue;
12783 }
12784
12785 if (!empty($value['default'])) {
12786 $this->$key = $value['default'];
12787 }
12788 }
12789 }
12790
12791 return 1;
12792 }
12793
12794
12795 /* Part for comments */
12796
12802 public function fetchComments()
12803 {
12804 require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
12805
12806 $comment = new Comment($this->db);
12807 $result = $comment->fetchAllFor($this->element, $this->id);
12808 if ($result < 0) {
12809 $this->setErrorsFromObject($comment);
12810 return -1;
12811 } else {
12812 $this->comments = $comment->comments;
12813 }
12814 return count($this->comments);
12815 }
12816
12822 public function getNbComments()
12823 {
12824 return count($this->comments);
12825 }
12826
12833 public function trimParameters($parameters)
12834 {
12835 if (!is_array($parameters)) {
12836 return;
12837 }
12838 foreach ($parameters as $parameter) {
12839 if (isset($this->$parameter)) {
12840 $this->$parameter = trim($this->$parameter);
12841 }
12842 }
12843 }
12844
12845 /* Part for categories/tags */
12846
12857 public function getCategoriesCommon($type_categ)
12858 {
12859 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
12860
12861 // Get current categories
12862 $c = new Categorie($this->db);
12863 $existing = $c->containing($this->id, $type_categ, 'id');
12864
12865 return $existing;
12866 }
12867
12880 public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
12881 {
12882 // Handle single category
12883 if (!is_array($categories)) {
12884 $categories = array($categories);
12885 }
12886
12887 dol_syslog(get_class($this)."::setCategoriesCommon Object Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
12888
12889 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
12890
12891 if (empty($type_categ)) {
12892 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
12893 return -1;
12894 }
12895
12896 // Get current categories
12897 $c = new Categorie($this->db);
12898 $existing = $c->containing($this->id, $type_categ, 'id');
12899 // containing() returns an integer < 0 on error (e.g. when the categorie_xxx table does not exist).
12900 // Normalize to an empty array to avoid array_diff()/foreach() warnings below.
12901 if (!is_array($existing)) {
12902 $existing = array();
12903 }
12904 if ($remove_existing) {
12905 // Diff
12906 $to_del = array_diff($existing, $categories);
12907 $to_add = array_diff($categories, $existing);
12908 } else {
12909 $to_del = array(); // Nothing to delete
12910 $to_add = array_diff($categories, $existing);
12911 }
12912
12913 $error = 0;
12914 $ok = 0;
12915
12916 // Process
12917 foreach ($to_del as $del) {
12918 if ($c->fetch($del) > 0) {
12919 $result = $c->del_type($this, $type_categ);
12920 if ($result < 0) {
12921 $error++;
12922 $this->error = $c->error;
12923 $this->errors = $c->errors;
12924 break;
12925 } else {
12926 $ok += $result;
12927 }
12928 }
12929 }
12930 foreach ($to_add as $add) {
12931 if ($c->fetch($add) > 0) {
12932 $result = $c->add_type($this, $type_categ);
12933 if ($result < 0) {
12934 $error++;
12935 $this->error = $c->error;
12936 $this->errors = $c->errors;
12937 break;
12938 } else {
12939 $ok += $result;
12940 }
12941 }
12942 }
12943
12944 return $error ? (-1 * $error) : $ok;
12945 }
12946
12955 public function cloneCategories($fromId, $toId, $type = '')
12956 {
12957 $this->db->begin();
12958
12959 if (empty($type)) {
12960 $type = $this->table_element;
12961 }
12962
12963 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
12964 $categorystatic = new Categorie($this->db);
12965
12966 $tablename = $this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
12967 $fkname = 'fk_' . (empty($categorystatic->MAP_CAT_FK[$type]) ? $type : $categorystatic->MAP_CAT_FK[$type]);
12968
12969 $sql = "INSERT INTO ".$this->db->sanitize($tablename)." (fk_categorie, ".$this->db->sanitize($fkname).")";
12970 $sql .= " SELECT fk_categorie, ".((int) $toId)." FROM ".$this->db->sanitize($tablename);
12971 $sql .= " WHERE ".$this->db->sanitize($fkname)." = ".((int) $fromId);
12972
12973 if (!$this->db->query($sql)) {
12974 $this->error = $this->db->lasterror();
12975 $this->db->rollback();
12976 return -1;
12977 }
12978
12979 $this->db->commit();
12980 return 1;
12981 }
12982
12989 public function deleteEcmFiles($mode = 0)
12990 {
12991 global $conf;
12992
12993 $this->db->begin();
12994
12995 // Delete in database with mode 0
12996 if ($mode == 0) {
12997 switch ($this->element) {
12998 case 'propal':
12999 $element = 'propale';
13000 break;
13001 case 'product':
13002 $element = 'produit';
13003 break;
13004 case 'order_supplier':
13005 $element = 'fournisseur/commande';
13006 break;
13007 case 'invoice_supplier':
13008 // Special cases that need to use get_exdir to get real dir of object
13009 // In future, all object should use this to define path of documents.
13010 $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
13011 break;
13012 case 'shipping':
13013 $element = 'expedition/sending';
13014 break;
13015 case 'task':
13016 case 'project_task':
13017 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
13018
13019 $project_result = $this->fetchProject();
13020 if ($project_result >= 0) {
13021 $element = 'projet/'.dol_sanitizeFileName($this->project->ref).'/';
13022 }
13023 // no break
13024 case 'contrat':
13025 $element = 'contract';
13026 break;
13027 default:
13028 $element = $this->element;
13029 }
13030 '@phan-var-force string $element';
13031
13032 // Delete ecm_files_extrafields with mode 0 (using name)
13033 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
13034 $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
13035 $sql .= " AND filepath = '".$this->db->escape($element."/".$this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
13036 $sql .= ")";
13037
13038 if (!$this->db->query($sql)) {
13039 $this->error = $this->db->lasterror();
13040 $this->db->rollback();
13041 return false;
13042 }
13043
13044 // Delete ecm_files with mode 0 (using name)
13045 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
13046 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
13047 $sql .= " AND filepath = '".$this->db->escape($element."/".$this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
13048
13049 if (!$this->db->query($sql)) {
13050 $this->error = $this->db->lasterror();
13051 $this->db->rollback();
13052 return false;
13053 }
13054 }
13055
13056 // Delete in database with mode 1
13057 if ($mode == 1) {
13058 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
13059 $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).")";
13060 $resql = $this->db->query($sql);
13061 if (!$resql) {
13062 $this->error = $this->db->lasterror();
13063 $this->db->rollback();
13064 return false;
13065 }
13066
13067 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
13068 $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
13069 $resql = $this->db->query($sql);
13070 if (!$resql) {
13071 $this->error = $this->db->lasterror();
13072 $this->db->rollback();
13073 return false;
13074 }
13075 }
13076
13077 $this->db->commit();
13078 return true;
13079 }
13080
13089 public function checkActiveProductInLines($status = 'onsale')
13090 {
13091 global $langs;
13092
13093 if (isModEnabled('product') || isModEnabled('service')) {
13094 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
13095
13096 $ret = true;
13097 $tmpproduct = new Product($this->db);
13098 foreach ($this->lines as $line) {
13099 if ($line->fk_product > 0) {
13100 $tmpproduct->fetch($line->fk_product);
13101 $statustotest = ($status == 'onsale' ? 'status' : 'status_buy');
13102 if (!$tmpproduct->$statustotest) {
13103 $langs->load('products');
13104 $statuskey4lang = ($status == 'onsale' ? 'ProductStatusNotOnSell' : 'ProductStatusNotOnBuy');
13105 $ret = false;
13106 $this->errors[] = $langs->trans('ProductRef').' '.$tmpproduct->ref.' '.$langs->trans($statuskey4lang);
13107 break;
13108 }
13109 }
13110 }
13111 if (!$ret) {
13112 $this->error = 'ErrorOneLineContainsADisactivatedProduct';
13113 }
13114 return $ret;
13115 } else {
13116 return true;
13117 }
13118 }
13119
13126 public function setErrorWithoutLog($message)
13127 {
13128 $this->error = $message;
13129 $this->errors[] = $message;
13130 }
13131
13139 public function setErrorWithLog($message, $loglevel = LOG_ERR)
13140 {
13141 global $dolibarr_main_document_root;
13142
13143 $this->setErrorWithoutLog($message);
13144 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
13145 $file = str_replace($dolibarr_main_document_root, '', $trace[0]['file'] ?? 'file unknown');
13146 $line = $trace[0]['line'] ?? 'line unknown';
13147 $syslogMessage = sprintf('%s:%s %s', $file, $line, $message);
13148 dol_syslog($syslogMessage, $loglevel);
13149 }
13150
13159 public function showLastFilePreview($rootdir = '', $relativepath = '')
13160 {
13161 global $conf, $formfile, $langs;
13162
13163 require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
13164
13165 // Clean and check root path
13166 if (empty($rootdir)) {
13167 $element = $this->element;
13168 $rootdir = $conf->$element->multidir_output[$this->entity];
13169 }
13170 if (!empty($rootdir)) {
13171 $rootdir = rtrim($rootdir, '/') . '/';
13172 }
13173 if (empty($rootdir) || !file_exists($rootdir) || !dol_is_dir($rootdir)) {
13174 return '';
13175 }
13176
13177 // Clean relative path
13178 if (empty($relativepath)) {
13179 $relativepath = dol_sanitizeFileName($this->ref);
13180 }
13181 if (!empty($relativepath)) {
13182 $relativepath = rtrim($relativepath, '/') . '/';
13183 }
13184
13185 // Set, clean and check file directory
13186 $filedir = $rootdir . $relativepath;
13187 if (!empty($filedir)) {
13188 $filedir = rtrim($filedir, '/') . '/';
13189 }
13190 if (empty($filedir) || !file_exists($filedir) || !dol_is_dir($filedir)) {
13191 return '';
13192 }
13193
13194 $found = false;
13195 $file = array();
13196 $relativefilepath = '';
13197
13198 // Search with last_main_doc
13199 if (!empty($this->last_main_doc) && dolIsAllowedForPreview($this->last_main_doc)) {
13200 $filename = basename($this->last_main_doc);
13201 $filepath = $filedir . $filename;
13202 if (file_exists($filepath) && dol_is_file($filepath)) {
13203 $relativefilepath = $relativepath . $filename;
13204 $found = true;
13205 }
13206 }
13207
13208 // Search with *<ref>*.pdf
13209 if (!$found) {
13210 $filelist = dol_dir_list($filedir, 'files', 0, dol_sanitizeFileName($this->ref) . '.*\.pdf$', '(\.meta|_preview.*.*\.png)$', 'date', SORT_DESC);
13211 if (is_array($filelist) && !empty($filelist)) {
13212 // Defined relative dir to DOL_DATA_ROOT
13213 $relativedir = '';
13214 if ($filedir) {
13215 $relativedir = preg_replace('/^' . preg_quote(DOL_DATA_ROOT, '/') . '/', '', $filedir);
13216 $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
13217 }
13218 // Get list of files stored into database for same relative directory
13219 if ($relativedir) {
13220 completeFileArrayWithDatabaseInfo($filelist, $relativedir);
13221 '@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}> $filelist';
13222
13223 //var_dump($sortfield.' - '.$sortorder);
13224 if (!empty($sortfield) && !empty($sortorder)) { // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
13225 $filelist = dol_sort_array($filelist, $sortfield, $sortorder);
13226 }
13227 }
13228 $filename = $filelist[0]['name'];
13229 $filepath = $filedir . $filename;
13230 if (file_exists($filepath) && dol_is_file($filepath) && dolIsAllowedForPreview($filename)) {
13231 $file = $filelist[0];
13232 $relativefilepath = $relativepath . $filename;
13233 $found = true;
13234 }
13235 }
13236 }
13237
13238 // Print preview link
13239 if ($found) {
13240 if (!is_object($formfile)) {
13241 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
13242 $formfile = new FormFile($this->db);
13243 }
13244 return $formfile->showPreview($file, $this->element, $relativefilepath, 0, 'entity=' . $this->entity);
13245 }
13246
13247 return '';
13248 }
13249}
$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
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
$c
Definition line.php:353
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage members of a foundation.
Class to manage categories.
Class to manage customers orders.
Class to manage comment.
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...
fetchWarehouse($force_warehouse_id=0)
Load the warehouse of object, from id $this->warehouse_id or $this->fk_warehouse, into this->warehous...
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.
updateFieldFromUi(User $user, $field, $value)
Update a field from the user interface (ajax edition of cards...) and save it into database.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
onFieldValueChanged($fieldKey, $value)
Hook called by setFieldValue() after a field has been successfully assigned.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
getRightsForUser(User $user)
Returns the rights used for this class for a specific user.
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.
hasUserPermission(User $user, $mode='write')
Check if user has a permission on this type of object.
deleteEcmFiles($mode=0)
Delete related files of object in database.
isFieldReadableFromUi(User $user, $field)
Check whether the value of a field can be read from the user interface with generic tools (ajax refre...
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
setFieldValue(User $user, $fieldKey, $value, $byPassUserPermission=false)
Set a value for a dynamic field on the current object.
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.
showLastFilePreview($rootdir='', $relativepath='')
Show preview link of the element (last generate or *<ref>*.pdf) if found and authorized to show the p...
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.
getObjectLineHtml($lineid, $action='')
Return the HTML of a line as printed in the card by printObjectLines(), hooks printObjectLine and pri...
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
printObjectLineWithHooks($action, $line, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir)
Print a line of the lines table: hooks printObjectLine or printObjectSubLine, then printObjectLine() ...
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.
isFieldDefined($field)
Check if the field is defined in the object's field metadata.
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.
isFieldValidationRequired($field)
Check if the field requires validation.
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...
hasUserPermissionOnField(User $user, $field, $mode='write')
Check if user has a permission on a field of this object.
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.
persistFieldValue(User $user, $field)
Save into database the current value of one field, called by updateFieldFromUi().
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
isFieldMarkedNotEditable($field)
Check if the field is explicitly marked as not editable.
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).
getLinkedBuyPriceDocuments($user, $lineid, $oldbuyprice=null)
Return the linked proposals, orders and invoices having, for the product of a line of this object,...
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
initObjectLinesDisplay()
Init the display of the lines: set the global variables used by the line templates (objectline_xxx....
updateLineUp($rowid, $rang)
Update position of line up (rang)
updateLinkedBuyPrice($user, $lineid, $elements)
Apply the cost price of a line of this object to the lines of the same product of some linked documen...
fetch_user($userid)
Load the user with id $userid into this->user.
ajaxOutputField($field)
Return the output html of a field for the user interface (ajax edition of fields).
errorsToString()
Method to output saved errors.
isFieldDisabled($field)
Check if the field is explicitly marked as disabled.
ajaxInputField($field)
Return the input html of a field for the user interface (ajax edition of fields).
getFieldPropertyName($field)
Return the name of the property of the object holding the value of a field of $fields.
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.
hasUserWritePermissionOnField(User $user, $field)
Check if user has write permission on a field of this object.
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.
isFieldBlockedByObjectState($field)
Check if the field is blocked by the current object state.
fetchComments()
Load comments linked with current task.
isFieldEditAllowed(User $user, $field, $byPassUserPermission=false)
Check whether a given field is allowed to be edited on the current object.
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.
isFieldEditableFromUi(User $user, $field)
Check whether a field can be edited from the user interface with generic tools (ajax edition of cards...
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.
isFieldEnabled($field)
Check if the field is enabled.
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 ...
getFieldValueFromAjaxPost($field)
Return the value of a field posted by the user interface (ajax edition of fields).
fetch_origin()
Read linked origin object.
prepareObjectLinesDisplay()
Prepare the display of the lines: global $usemargins and line extrafields used by the line templates ...
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.
getObjectLinesDisplayContext()
Return the display context of the lines, as defined by the card of the object before printObjectLines...
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.
static commonReplaceContact(DoliDB $dbs, $origin_id, $dest_id, array $tables, $fieldname='fk_socpeople', $ignoreerrors=0)
Function used to replace a contact id with another one.
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...
getFieldUiValue($field)
Return the value of a field of $fields, read in the property holding it (see getFieldPropertyName()).
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
sanitize($stringtosanitize, $allowsimplequote=0, $allowsequals=0, $allowsspace=0, $allowschars=1)
Sanitize a string for SQL forging.
Class to manage donations.
Definition don.class.php:42
Class to manage ECM files.
Class to manage warehouses.
Class to manage standard extra fields.
static isEmptyValue($v, string $type)
Return if a value is "empty" for a mandatory vision.
Class to manage invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice templates.
Class to offer components to list and upload files.
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 proposals.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage price ask supplier.
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
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
$context
@method int call_trigger(string $triggerName, ?User $user)
Definition command.php:209
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.
global $mysoc
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
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:66
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_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
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.
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.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
GETPOSTDATE($prefix, $hourTime='', $gm='auto', $saverestore='')
Helper function that combines values of a dolibarr DatePicker (such as Form\selectDate) for year,...
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.
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.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
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.
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.
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.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
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_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.
getPictoForType($key, $morecss='')
Return the picto for a data type.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $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:166
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
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.