dolibarr 21.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-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
11 * Copyright (C) 2016 Bahfir abbes <bafbes@gmail.com>
12 * Copyright (C) 2017 ATM Consulting <support@atm-consulting.fr>
13 * Copyright (C) 2017-2019 Nicolas ZABOURI <info@inovea-conseil.com>
14 * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
15 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2018 Josep Lluís Amador <joseplluis@lliuretic.cat>
17 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
18 * Copyright (C) 2021 Grégory Blémand <gregory.blemand@atm-consulting.fr>
19 * Copyright (C) 2023 Lenin Rivas <lenin.rivas777@gmail.com>
20 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
21 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
22 *
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 3 of the License, or
26 * (at your option) any later version.
27 *
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <https://www.gnu.org/licenses/>.
35 */
36
43require_once DOL_DOCUMENT_ROOT.'/core/class/doldeprecationhandler.class.php';
44
50abstract class CommonObject
51{
52 use DolDeprecationHandler;
53
54 const TRIGGER_PREFIX = ''; // to be overridden in child class implementations, i.e. 'BILL', 'TASK', 'PROPAL', etc.
55
59 public $module;
60
64 public $db;
65
69 public $id;
70
74 public $entity;
75
80 public $error;
81
85 public $errorhidden;
86
90 public $errors = array();
91
95 private $validateFieldsErrors = array();
96
100 public $element;
101
106 public $fk_element;
107
113 public $element_for_permission;
114
118 public $table_element;
119
123 public $table_element_line = '';
124
129 public $ismultientitymanaged;
130
134 public $import_key;
135
139 public $array_options = array();
140
141
145 public $fields = array();
146
152 public $array_languages = null; // Value is array() when load already tried
153
157 public $contacts_ids;
158
162 public $linked_objects;
163
167 public $linkedObjectsIds;
168
172 public $linkedObjects;
173
177 private $linkedObjectsFullLoaded = array();
178
182 public $oldcopy;
183
187 public $oldref;
188
192 protected $table_ref_field = '';
193
197 public $restrictiononfksoc = 0;
198
199
200 // The following vars are used by some objects only.
201 // We keep these properties in CommonObject in order to provide common methods using them.
202
206 public $context = array();
207
211 public $actionmsg;
215 public $actionmsg2;
216
220 public $canvas;
221
226 public $project;
227
232 public $fk_project;
233
239 private $projet;
240
246 public $fk_projet;
247
252 public $contact;
253
258 public $contact_id;
259
264 public $thirdparty;
265
270 public $user;
271
276 public $origin_type;
277
282 public $origin_id;
283
288
294 public $origin;
295
304 private $expedition;
305
311 private $livraison;
312
318 private $commandeFournisseur;
319
320
324 public $ref;
325
329 public $ref_ext;
330
334 public $ref_previous;
335
339 public $ref_next;
340
344 public $newref;
345
352 public $statut;
353
361 public $status;
362
363
368 public $country;
369
374 public $country_id;
375
380 public $country_code;
381
386 public $state;
387
392 public $state_id;
393
398 public $fk_departement;
399
404 public $state_code;
405
410 public $region_id;
411
416 public $region_code;
417
422 public $region;
423
424
429 public $barcode_type;
430
435 public $barcode_type_code;
436
441 public $barcode_type_label;
442
447 public $barcode_type_coder;
448
453 public $mode_reglement_id;
454
459 public $cond_reglement_id;
460
464 public $demand_reason_id;
465
470 public $transport_mode_id;
471
479 private $cond_reglement; // Private to call DolDeprecationHandler
483 protected $depr_cond_reglement; // Internal value for deprecation
484
490 public $fk_delivery_address;
491
496 public $shipping_method_id;
497
502 public $shipping_method;
503
504 // Multicurrency
508 public $fk_multicurrency;
509
514 public $multicurrency_code;
515
520 public $multicurrency_tx;
521
525 public $multicurrency_total_ht;
526
530 public $multicurrency_total_tva;
531
535 public $multicurrency_total_ttc;
536
540 public $multicurrency_total_localtax1; // not in database
541
545 public $multicurrency_total_localtax2; // not in database
546
551 public $model_pdf;
552
557 public $last_main_doc;
558
564 public $fk_bank;
565
570 public $fk_account;
571
576 public $note_public;
577
582 public $note_private;
583
589 public $note;
590
595 public $total_ht;
596
601 public $total_tva;
602
607 public $total_localtax1;
608
613 public $total_localtax2;
614
619 public $total_ttc;
620
621
625 public $lines;
626
630 public $actiontypecode;
631
636 public $comments = array();
637
641 public $name;
642
646 public $lastname;
647
651 public $firstname;
652
656 public $civility_id;
657
658 // Dates
662 public $date_creation;
663
667 public $date_validation;
668
672 public $date_modification;
673
679 public $tms;
680
686 private $date_update;
687
691 public $date_cloture;
692
697 public $user_author;
698
703 public $user_creation;
704
708 public $user_creation_id;
709
714 public $user_valid;
715
720 public $user_validation;
721
725 public $user_validation_id;
726
730 public $user_closing_id;
731
736 public $user_modification;
737
741 public $user_modification_id;
742
747 public $fk_user_creat;
748
753 public $fk_user_modif;
754
755
759 public $next_prev_filter;
760
764 public $specimen = 0;
765
769 public $sendtoid;
770
775 public $alreadypaid;
776
781 public $totalpaid;
782
786 public $labelStatus = array();
787
791 public $labelStatusShort = array();
792
796 public $tpl;
797
798
802 public $showphoto_on_popup;
803
807 public $nb = array();
808
812 public $nbphoto;
813
817 public $output;
818
822 public $extraparams = array();
823
827 protected $childtables = array();
828
834 protected $childtablesoncascade = array();
835
839 public $product;
840
844 public $cond_reglement_supplier_id;
845
851 public $deposit_percent;
852
853
857 public $retained_warranty_fk_cond_reglement;
858
862 public $warehouse_id;
863
867 public $isextrafieldmanaged = 0;
868
869
870 // No constructor as it is an abstract class
871
877 protected function deprecatedProperties()
878 {
879 return array(
880 'alreadypaid' => 'totalpaid',
881 'cond_reglement' => 'depr_cond_reglement',
882 //'note' => 'note_private', // Some classes needs ->note and others need ->note_public/private so we can't manage deprecation for this field with dolDeprecationHandler
883 'commandeFournisseur' => 'origin_object',
884 'expedition' => 'origin_object',
885 'fk_project' => 'fk_project',
886 'livraison' => 'origin_object',
887 'projet' => 'project',
888 'statut' => 'status',
889 );
890 }
891
892
903 public static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
904 {
905 global $db, $conf;
906
907 $sql = "SELECT rowid, ref, ref_ext";
908 $sql .= " FROM ".$db->prefix().$element;
909 $sql .= " WHERE entity IN (".getEntity($element).")";
910
911 if ($id > 0) {
912 $sql .= " AND rowid = ".((int) $id);
913 } elseif ($ref) {
914 $sql .= " AND ref = '".$db->escape($ref)."'";
915 } elseif ($ref_ext) {
916 $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
917 } else {
918 $error = 'ErrorWrongParameters';
919 dol_syslog(get_class()."::isExistingObject ".$error, LOG_ERR);
920 return -1;
921 }
922 if ($ref || $ref_ext) { // Because the same ref can exists in 2 different entities, we force the current one in priority
923 $sql .= " AND entity = ".((int) $conf->entity);
924 }
925
926 dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
927 $resql = $db->query($sql);
928 if ($resql) {
929 $num = $db->num_rows($resql);
930 if ($num > 0) {
931 return 1;
932 } else {
933 return 0;
934 }
935 }
936 return -1;
937 }
938
944 public function isEmpty()
945 {
946 return (empty($this->id));
947 }
948
956 {
957 if (!empty($object->error)) {
958 $this->error = $object->error;
959 }
960 if (!empty($object->errors)) {
961 $this->errors = array_merge($this->errors, $object->errors);
962 }
963 }
964
972 public function getTooltipContentArray($params)
973 {
974 return [];
975 }
976
984 public function getTooltipContent($params)
985 {
986 global $action, $extrafields, $langs, $hookmanager;
987
988 // If there is too much extrafields, we do not include them into tooltip
989 $MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP = getDolGlobalInt('MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP', 3);
990
991 $data = $this->getTooltipContentArray($params);
992 $count = 0;
993
994 // Add extrafields
995 if (!empty($extrafields->attributes[$this->table_element]['label'])) {
996 $data['opendivextra'] = '<div class="centpercent wordbreak divtooltipextra">';
997 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
998 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
999 continue;
1000 }
1001 if ($count >= abs($MAX_EXTRAFIELDS_TO_SHOW_IN_TOOLTIP)) {
1002 $data['more_extrafields'] = '<br>...';
1003 break;
1004 }
1005 $enabled = 1;
1006 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
1007 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
1008 }
1009 if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) {
1010 $enabled = (int) dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
1011 }
1012 $perms = 1;
1013 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
1014 $perms = (int) dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
1015 }
1016 if (empty($enabled)) {
1017 continue; // 0 = Never visible field
1018 }
1019 if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) {
1020 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation
1021 }
1022 if (empty($perms)) {
1023 continue; // 0 = Not visible
1024 }
1025 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
1026 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
1027 }
1028 $labelextra = $langs->trans((string) $extrafields->attributes[$this->table_element]['label'][$key]);
1029 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
1030 $data[$key] = '<br><b><u>'. $labelextra . '</u></b>';
1031 } else {
1032 $value = (empty($this->array_options['options_' . $key]) ? '' : $this->array_options['options_' . $key]);
1033 $data[$key] = '<br><b>'. $labelextra . ':</b> ' . $extrafields->showOutputField($key, $value, '', $this->table_element);
1034 $count++;
1035 }
1036 }
1037 $data['closedivextra'] = '</div>';
1038 }
1039
1040 $hookmanager->initHooks(array($this->element . 'dao'));
1041 $parameters = array(
1042 'tooltipcontentarray' => &$data,
1043 'params' => $params,
1044 );
1045 // Note that $action and $object may have been modified by some hooks
1046 $hookmanager->executeHooks('getTooltipContent', $parameters, $this, $action);
1047
1048 //var_dump($data);
1049 $label = implode($data);
1050
1051 return $label;
1052 }
1053
1054
1060 public function errorsToString()
1061 {
1062 return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').implode(', ', $this->errors)) : '');
1063 }
1064
1065
1072 public function getFormatedCustomerRef($objref)
1073 {
1074 global $hookmanager;
1075
1076 $parameters = array('objref' => $objref);
1077 $action = '';
1078 $reshook = $hookmanager->executeHooks('getFormatedCustomerRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1079 if ($reshook > 0) {
1080 return $hookmanager->resArray['objref'];
1081 }
1082 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1083 }
1084
1091 public function getFormatedSupplierRef($objref)
1092 {
1093 global $hookmanager;
1094
1095 $parameters = array('objref' => $objref);
1096 $action = '';
1097 $reshook = $hookmanager->executeHooks('getFormatedSupplierRef', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1098 if ($reshook > 0) {
1099 return $hookmanager->resArray['objref'];
1100 }
1101 return $objref.(isset($hookmanager->resArray['objref']) ? $hookmanager->resArray['objref'] : '');
1102 }
1103
1113 public function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0, $extralangcode = '')
1114 {
1115 if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) {
1116 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1117 $tmparray = getCountry($this->country_id, 'all');
1118 $this->country_code = $tmparray['code'];
1119 $this->country = $tmparray['label'];
1120 }
1121
1122 if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_code))) {
1123 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
1124 $tmparray = getState($this->state_id, 'all', null, 1);
1125 $this->state_code = $tmparray['code'];
1126 $this->state = $tmparray['label'];
1127 $this->region_code = $tmparray['region_code'];
1128 $this->region = $tmparray['region'];
1129 }
1130
1131 return dol_format_address($this, $withcountry, $sep, null, 0, $extralangcode);
1132 }
1133
1134
1143 public function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
1144 {
1145 global $user, $dolibarr_main_url_root;
1146
1147 if (empty($this->last_main_doc)) {
1148 return ''; // No way to known which document name to use
1149 }
1150
1151 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
1152 $ecmfile = new EcmFiles($this->db);
1153 $result = $ecmfile->fetch(0, '', $this->last_main_doc);
1154 if ($result < 0) {
1155 $this->error = $ecmfile->error;
1156 $this->errors = $ecmfile->errors;
1157 return -1;
1158 }
1159
1160 if (empty($ecmfile->id)) { // No entry into file index already exists, we should initialize the shared key manually.
1161 // Add entry into index
1162 if ($initsharekey) {
1163 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1164
1165 // 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
1166 /*
1167 $ecmfile->filepath = $rel_dir;
1168 $ecmfile->filename = $filename;
1169 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
1170 $ecmfile->fullpath_orig = '';
1171 $ecmfile->gen_or_uploaded = 'generated';
1172 $ecmfile->description = ''; // indexed content
1173 $ecmfile->keywords = ''; // keyword content
1174 $ecmfile->share = getRandomPassword(true);
1175 $result = $ecmfile->create($user);
1176 if ($result < 0)
1177 {
1178 $this->error = $ecmfile->error;
1179 $this->errors = $ecmfile->errors;
1180 }
1181 */
1182 } else {
1183 return '';
1184 }
1185 } elseif (empty($ecmfile->share)) { // Entry into file index already exists but no share key is defined.
1186 // Add entry into index
1187 if ($initsharekey) {
1188 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1189 $ecmfile->share = getRandomPassword(true);
1190 $ecmfile->update($user);
1191 } else {
1192 return '';
1193 }
1194 }
1195 // Define $urlwithroot
1196 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1197 // This is to use external domain name found into config file
1198 //if (DOL_URL_ROOT && ! preg_match('/\/$/', $urlwithouturlroot) && ! preg_match('/^\//', DOL_URL_ROOT)) $urlwithroot=$urlwithouturlroot.'/'.DOL_URL_ROOT;
1199 //else
1200 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
1201 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1202
1203 $forcedownload = 0;
1204
1205 $paramlink = '';
1206 //if (!empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart; // For sharing with hash (so public files), modulepart is not required.
1207 //if (!empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; // For sharing with hash (so public files), entity is not required.
1208 //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath); // No need of name of file for public link, we will use the hash
1209 if (!empty($ecmfile->share)) {
1210 $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
1211 }
1212 if ($forcedownload) {
1213 $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1214 }
1215
1216 if ($relativelink) {
1217 $linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
1218 } else {
1219 $linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1220 }
1221
1222 // Here $ecmfile->share is defined
1223 return $linktoreturn;
1224 }
1225
1226
1227 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1237 public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
1238 {
1239 // phpcs:enable
1240 global $user, $langs;
1241
1242
1243 dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
1244
1245 // Check parameters
1246 if ($fk_socpeople <= 0) {
1247 $langs->load("errors");
1248 $this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
1249 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1250 return -1;
1251 }
1252 if (!$type_contact) {
1253 $langs->load("errors");
1254 $this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
1255 dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
1256 return -2;
1257 }
1258
1259 $id_type_contact = 0;
1260 if (is_numeric($type_contact)) {
1261 $id_type_contact = $type_contact;
1262 } else {
1263 // We look for id type_contact
1264 $sql = "SELECT tc.rowid";
1265 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1266 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1267 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1268 $sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
1269 //print $sql;
1270 $resql = $this->db->query($sql);
1271 if ($resql) {
1272 $obj = $this->db->fetch_object($resql);
1273 if ($obj) {
1274 $id_type_contact = $obj->rowid;
1275 }
1276 }
1277 }
1278
1279 if ($id_type_contact == 0) {
1280 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");
1281 return 0;
1282 }
1283
1284 $datecreate = dol_now();
1285
1286 // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
1287 $TListeContacts = $this->liste_contact(-1, $source);
1288 $already_added = false;
1289 if (is_array($TListeContacts) && !empty($TListeContacts)) {
1290 foreach ($TListeContacts as $array_contact) {
1291 if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
1292 $already_added = true;
1293 break;
1294 }
1295 }
1296 }
1297
1298 if (!$already_added) {
1299 $this->db->begin();
1300
1301 // Insert into database
1302 $sql = "INSERT INTO ".$this->db->prefix()."element_contact";
1303 $sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
1304 $sql .= " VALUES (".$this->id.", ".((int) $fk_socpeople)." , ";
1305 $sql .= "'".$this->db->idate($datecreate)."'";
1306 $sql .= ", 4, ".((int) $id_type_contact);
1307 $sql .= ")";
1308
1309 $resql = $this->db->query($sql);
1310 if ($resql) {
1311 if (!$notrigger) {
1312 $result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
1313 if ($result < 0) {
1314 $this->db->rollback();
1315 return -1;
1316 }
1317 }
1318
1319 $this->db->commit();
1320 return 1;
1321 } else {
1322 if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1323 $this->error = $this->db->errno();
1324 $this->db->rollback();
1325 return -2;
1326 } else {
1327 $this->error = $this->db->lasterror();
1328 $this->db->rollback();
1329 return -1;
1330 }
1331 }
1332 } else {
1333 return 0;
1334 }
1335 }
1336
1337 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1345 public function copy_linked_contact($objFrom, $source = 'internal')
1346 {
1347 // phpcs:enable
1348 $contacts = $objFrom->liste_contact(-1, $source);
1349 foreach ($contacts as $contact) {
1350 if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) {
1351 return -1;
1352 }
1353 }
1354 return 1;
1355 }
1356
1357 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1367 public function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
1368 {
1369 // phpcs:enable
1370 // Insert into database
1371 $sql = "UPDATE ".$this->db->prefix()."element_contact set";
1372 $sql .= " statut = ".((int) $statut);
1373 if ($type_contact_id) {
1374 $sql .= ", fk_c_type_contact = ".((int) $type_contact_id);
1375 }
1376 if ($fk_socpeople) {
1377 $sql .= ", fk_socpeople = ".((int) $fk_socpeople);
1378 }
1379 $sql .= " where rowid = ".((int) $rowid);
1380
1381 $resql = $this->db->query($sql);
1382 if ($resql) {
1383 return 0;
1384 } else {
1385 $this->error = $this->db->lasterror();
1386 return -1;
1387 }
1388 }
1389
1390 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1398 public function delete_contact($rowid, $notrigger = 0)
1399 {
1400 // phpcs:enable
1401 global $user;
1402
1403 $error = 0;
1404
1405 $this->db->begin();
1406
1407 if (!$error && empty($notrigger)) {
1408 // Call trigger
1409 $this->context['contact_id'] = ((int) $rowid);
1410 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1411 if ($result < 0) {
1412 $error++;
1413 }
1414 // End call triggers
1415 }
1416
1417 if (!$error) {
1418 dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1419
1420 $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1421 $sql .= " WHERE rowid = ".((int) $rowid);
1422
1423 $result = $this->db->query($sql);
1424 if (!$result) {
1425 $error++;
1426 $this->errors[] = $this->db->lasterror();
1427 }
1428 }
1429
1430 if (!$error) {
1431 $this->db->commit();
1432 return 1;
1433 } else {
1434 $this->error = $this->db->lasterror();
1435 $this->db->rollback();
1436 return -1;
1437 }
1438 }
1439
1440 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1448 public function delete_linked_contact($source = '', $code = '')
1449 {
1450 // phpcs:enable
1451 $listId = '';
1452 $temp = array();
1453 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1454
1455 if (!empty($typeContact)) {
1456 foreach ($typeContact as $key => $value) {
1457 array_push($temp, $key);
1458 }
1459 $listId = implode(",", $temp);
1460 }
1461
1462 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1463 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1464 if (empty($listId)) {
1465 return 0;
1466 }
1467
1468 $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1469 $sql .= " WHERE element_id = ".((int) $this->id);
1470 $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1471
1472 dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1473 if ($this->db->query($sql)) {
1474 return 1;
1475 } else {
1476 $this->error = $this->db->lasterror();
1477 return -1;
1478 }
1479 }
1480
1481 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1493 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1494 {
1495 // phpcs:enable
1496 global $langs;
1497
1498 $tab = array();
1499
1500 $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
1501 if ($source == 'internal') {
1502 $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender";
1503 }
1504 if ($source == 'external' || $source == 'thirdparty') {
1505 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1506 }
1507 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1508 if (empty($arrayoftcids)) {
1509 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
1510 }
1511 $sql .= " FROM";
1512 if (empty($arrayoftcids)) {
1513 $sql .= " ".$this->db->prefix()."c_type_contact as tc,";
1514 }
1515 $sql .= " ".$this->db->prefix()."element_contact as ec";
1516 if ($source == 'internal') { // internal contact (user)
1517 $sql .= " LEFT JOIN ".$this->db->prefix()."user as t on ec.fk_socpeople = t.rowid";
1518 }
1519 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1520 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople as t on ec.fk_socpeople = t.rowid";
1521 }
1522 $sql .= " WHERE ec.element_id = ".((int) $this->id);
1523 if (empty($arrayoftcids)) {
1524 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1525 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1526 if ($code) {
1527 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1528 }
1529 if ($source == 'internal') {
1530 $sql .= " AND tc.source = 'internal'";
1531 }
1532 if ($source == 'external' || $source == 'thirdparty') {
1533 $sql .= " AND tc.source = 'external'";
1534 }
1535 $sql .= " AND tc.active = 1";
1536 } else {
1537 $sql .= " AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', $arrayoftcids)).")";
1538 }
1539 if ($status >= 0) {
1540 $sql .= " AND t.statut = ".((int) $status); // t is llx_user or llx_socpeople
1541 }
1542 if ($statusoflink >= 0) {
1543 $sql .= " AND ec.statut = ".((int) $statusoflink);
1544 }
1545 $sql .= " ORDER BY t.lastname ASC";
1546
1547 dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1548 $resql = $this->db->query($sql);
1549 if ($resql) {
1550 $num = $this->db->num_rows($resql);
1551 $i = 0;
1552 while ($i < $num) {
1553 $obj = $this->db->fetch_object($resql);
1554
1555 if (!$list) {
1556 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1557 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1558 $tab[$i] = array(
1559 'parentId' => $this->id,
1560 'source' => $obj->source,
1561 'socid' => $obj->socid,
1562 'id' => $obj->id,
1563 'nom' => $obj->lastname, // For backward compatibility
1564 'civility' => $obj->civility,
1565 'lastname' => $obj->lastname,
1566 'firstname' => $obj->firstname,
1567 'email' => $obj->email,
1568 'login' => (empty($obj->login) ? '' : $obj->login),
1569 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1570 'gender' => (empty($obj->gender) ? '' : $obj->gender),
1571 'statuscontact' => $obj->statuscontact,
1572 'rowid' => $obj->rowid,
1573 'code' => $obj->code,
1574 'libelle' => $libelle_type,
1575 'status' => $obj->statuslink,
1576 'fk_c_type_contact' => $obj->fk_c_type_contact
1577 );
1578 } else {
1579 $tab[$i] = $obj->id;
1580 }
1581
1582 $i++;
1583 }
1584
1585 return $tab;
1586 } else {
1587 $this->error = $this->db->lasterror();
1588 dol_print_error($this->db);
1589 return -1;
1590 }
1591 }
1592
1593
1600 public function swapContactStatus($rowid)
1601 {
1602 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1603 $sql .= " tc.code, tc.libelle as type_label";
1604 $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1605 $sql .= " WHERE ec.rowid =".((int) $rowid);
1606 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1607 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1608
1609 dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1610 $resql = $this->db->query($sql);
1611 if ($resql) {
1612 $obj = $this->db->fetch_object($resql);
1613 $newstatut = ($obj->statut == 4) ? 5 : 4;
1614 $result = $this->update_contact($rowid, $newstatut);
1615 $this->db->free($resql);
1616 return $result;
1617 } else {
1618 $this->error = $this->db->error();
1619 dol_print_error($this->db);
1620 return -1;
1621 }
1622 }
1623
1624 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1635 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1636 {
1637 // phpcs:enable
1638 global $langs;
1639
1640 if (empty($order)) {
1641 $order = 'position';
1642 }
1643 if ($order == 'position') {
1644 $order .= ',code';
1645 }
1646
1647 $tab = array();
1648 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1649 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1650 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1651 if ($activeonly == 1) {
1652 $sql .= " AND tc.active=1"; // only the active types
1653 }
1654 if (!empty($source) && $source != 'all') {
1655 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1656 }
1657 if (!empty($code)) {
1658 $sql .= " AND tc.code='".$this->db->escape($code)."'";
1659 }
1660 $sql .= $this->db->order($order, 'ASC');
1661
1662 //print "sql=".$sql;
1663 $resql = $this->db->query($sql);
1664 if ($resql) {
1665 $num = $this->db->num_rows($resql);
1666 $i = 0;
1667 while ($i < $num) {
1668 $obj = $this->db->fetch_object($resql);
1669
1670 $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1671 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1672 if (empty($option)) {
1673 $tab[$obj->rowid] = $libelle_type;
1674 } else {
1675 $tab[$obj->code] = $libelle_type;
1676 }
1677 $i++;
1678 }
1679 return $tab;
1680 } else {
1681 $this->error = $this->db->lasterror();
1682 //dol_print_error($this->db);
1683 return null;
1684 }
1685 }
1686
1698 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1699 {
1700 global $langs, $conf;
1701
1702 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1703
1704 $tab = array();
1705
1706 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element";
1707 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1708
1709 $sqlWhere = array();
1710 if (!empty($element)) {
1711 $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1712 }
1713 if (!empty($excludeelement)) {
1714 $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1715 }
1716
1717 if ($activeonly == 1) {
1718 $sqlWhere[] = " tc.active=1"; // only the active types
1719 }
1720
1721 if (!empty($source) && $source != 'all') {
1722 $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1723 }
1724
1725 if (!empty($code)) {
1726 $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1727 }
1728
1729 if (count($sqlWhere) > 0) {
1730 $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1731 }
1732
1733 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1734
1735 dol_syslog(__METHOD__, LOG_DEBUG);
1736 $resql = $this->db->query($sql);
1737 if ($resql) {
1738 $num = $this->db->num_rows($resql);
1739 if ($num > 0) {
1740 $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1741
1742 while ($obj = $this->db->fetch_object($resql)) {
1743 $modulename = $obj->element;
1744 if (strpos($obj->element, 'project') !== false) {
1745 $modulename = 'projet';
1746 } elseif ($obj->element == 'contrat') {
1747 $element = 'contract';
1748 } elseif ($obj->element == 'action') {
1749 $modulename = 'agenda';
1750 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1751 $modulename = 'fournisseur';
1752 }
1753 if (isModEnabled($modulename)) {
1754 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1755 $tmpelement = $obj->element;
1756 $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1757 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1758 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1759 }
1760 }
1761 }
1762 return $tab;
1763 } else {
1764 $this->error = $this->db->lasterror();
1765 return null;
1766 }
1767 }
1768
1780 public function getIdContact($source, $code, $status = 0)
1781 {
1782 global $conf;
1783
1784 $result = array();
1785 $i = 0;
1786 // Particular case for shipping
1787 if ($this->element == 'shipping' && $this->origin_id != 0) {
1788 $id = $this->origin_id;
1789 $element = 'commande';
1790 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1791 $id = $this->origin_id;
1792 $element = 'order_supplier';
1793 } else {
1794 $id = $this->id;
1795 $element = $this->element;
1796 }
1797
1798 $sql = "SELECT ec.fk_socpeople";
1799 $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1800 if ($source == 'internal') {
1801 $sql .= " ".$this->db->prefix()."user as c,";
1802 }
1803 if ($source == 'external') {
1804 $sql .= " ".$this->db->prefix()."socpeople as c,";
1805 }
1806 $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1807 $sql .= " WHERE ec.element_id = ".((int) $id);
1808 $sql .= " AND ec.fk_socpeople = c.rowid";
1809 if ($source == 'internal') {
1810 $sql .= " AND c.entity IN (".getEntity('user').")";
1811 }
1812 if ($source == 'external') {
1813 $sql .= " AND c.entity IN (".getEntity('societe').")";
1814 }
1815 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1816 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1817 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1818 if ($code) {
1819 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1820 }
1821 $sql .= " AND tc.active = 1";
1822 if ($status) {
1823 $sql .= " AND ec.statut = ".((int) $status);
1824 }
1825
1826 dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1827 $resql = $this->db->query($sql);
1828 if ($resql) {
1829 while ($obj = $this->db->fetch_object($resql)) {
1830 $result[$i] = $obj->fk_socpeople;
1831 $i++;
1832 }
1833 } else {
1834 $this->error = $this->db->error();
1835 return null;
1836 }
1837
1838 return $result;
1839 }
1840
1841 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1848 public function fetch_contact($contactid = null)
1849 {
1850 // phpcs:enable
1851 if (empty($contactid)) {
1852 $contactid = $this->contact_id;
1853 }
1854
1855 if (empty($contactid)) {
1856 return 0;
1857 }
1858
1859 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1860 $contact = new Contact($this->db);
1861 $result = $contact->fetch($contactid);
1862 $this->contact = $contact;
1863 return $result;
1864 }
1865
1866 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1874 public function fetch_thirdparty($force_thirdparty_id = 0)
1875 {
1876 // phpcs:enable
1877 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1878 return 0;
1879 }
1880
1881 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1882
1883 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1884 if ($force_thirdparty_id) {
1885 $idtofetch = $force_thirdparty_id;
1886 }
1887
1888 if ($idtofetch) {
1889 $thirdparty = new Societe($this->db);
1890 $result = $thirdparty->fetch($idtofetch);
1891 if ($result < 0) {
1892 $this->errors = array_merge($this->errors, $thirdparty->errors);
1893 }
1894 $this->thirdparty = $thirdparty;
1895
1896 // Use first price level if level not defined for third party
1897 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->thirdparty->price_level)) {
1898 $this->thirdparty->price_level = 1;
1899 }
1900
1901 return $result;
1902 } else {
1903 return -1;
1904 }
1905 }
1906
1907
1915 public function fetchOneLike($ref)
1916 {
1917 if (!$this->table_ref_field) {
1918 return 0;
1919 }
1920
1921 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1922 $sql .= " WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."'"; // no escapeforlike here
1923 $sql .= " LIMIT 1";
1924
1925 $query = $this->db->query($sql);
1926
1927 if (!$this->db->num_rows($query)) {
1928 return 0;
1929 }
1930
1931 $result = $this->db->fetch_object($query);
1932
1933 if (method_exists($this, 'fetch')) {
1934 return $this->fetch($result->rowid);
1935 } else {
1936 $this->error = 'Fetch method not implemented on '.get_class($this);
1937 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
1938 array_push($this->errors, $this->error);
1939 return -1;
1940 }
1941 }
1942
1943 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1951 public function fetch_barcode()
1952 {
1953 // phpcs:enable
1954 global $conf;
1955
1956 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1957
1958 $idtype = $this->barcode_type;
1959 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
1960 if ($this->element == 'product' && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) {
1961 $idtype = getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE');
1962 } elseif ($this->element == 'societe') {
1963 $idtype = getDolGlobalString('GENBARCODE_BARCODETYPE_THIRDPARTY');
1964 } else {
1965 dol_syslog('Call fetch_barcode with barcode_type not defined and cannot be guessed', LOG_WARNING);
1966 }
1967 }
1968
1969 if ($idtype > 0) {
1970 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
1971 $sql = "SELECT rowid, code, libelle as label, coder";
1972 $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1973 $sql .= " WHERE rowid = ".((int) $idtype);
1974 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1975 $resql = $this->db->query($sql);
1976 if ($resql) {
1977 $obj = $this->db->fetch_object($resql);
1978 $this->barcode_type = $obj->rowid;
1979 $this->barcode_type_code = $obj->code;
1980 $this->barcode_type_label = $obj->label;
1981 $this->barcode_type_coder = $obj->coder;
1982 return 1;
1983 } else {
1984 dol_print_error($this->db);
1985 return -1;
1986 }
1987 }
1988 }
1989 return 0;
1990 }
1991
1997 public function fetchProject()
1998 {
1999 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
2000
2001 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2002 $this->fk_project = $this->fk_projet; // For backward compatibility
2003 }
2004 if (empty($this->fk_project)) {
2005 return 0;
2006 }
2007
2008 $project = new Project($this->db);
2009 $result = $project->fetch($this->fk_project);
2010
2011 $this->projet = $project; // deprecated
2012 $this->project = $project;
2013
2014 return $result;
2015 }
2016
2017 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2025 public function fetch_project()
2026 {
2027 // phpcs:enable
2028 return $this->fetchProject();
2029 }
2030
2031 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2039 public function fetch_projet()
2040 {
2041 // phpcs:enable
2042 return $this->fetchProject();
2043 }
2044
2045 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2051 public function fetch_product()
2052 {
2053 // phpcs:enable
2054 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2055
2056 // @phan-suppress-next-line PhanUndeclaredProperty
2057 if (empty($this->fk_product)) {
2058 return 0;
2059 }
2060
2061 $product = new Product($this->db);
2062 // @phan-suppress-next-line PhanUndeclaredProperty
2063 $result = $product->fetch($this->fk_product);
2064
2065 $this->product = $product;
2066 return $result;
2067 }
2068
2069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2076 public function fetch_user($userid)
2077 {
2078 // phpcs:enable
2079 $user = new User($this->db);
2080 $result = $user->fetch($userid);
2081 $this->user = $user;
2082 return $result;
2083 }
2084
2085 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2092 public function fetch_origin()
2093 {
2094 // phpcs:enable
2095 $origin = $this->origin ? $this->origin : $this->origin_type;
2096
2097 // Manage classes with non standard name
2098 if ($origin == 'shipping') {
2099 $origin = 'expedition';
2100 }
2101 if ($origin == 'delivery') {
2102 $origin = 'livraison';
2103 }
2104 if ($origin == 'order_supplier' || $origin == 'supplier_order') {
2105 $origin = 'commandeFournisseur';
2106 }
2107
2108 $classname = ucfirst($origin);
2109 $this->origin_object = new $classname($this->db);
2110 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
2111 $this->origin_object->fetch($this->origin_id);
2112 }
2113
2123 public function fetchObjectFrom($table, $field, $key, $element = null)
2124 {
2125 global $conf;
2126
2127 $result = false;
2128
2129 $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
2130 $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
2131 if (!empty($element)) {
2132 $sql .= " AND entity IN (".getEntity($element).")";
2133 } else {
2134 $sql .= " AND entity = ".((int) $conf->entity);
2135 }
2136
2137 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
2138 $resql = $this->db->query($sql);
2139 if ($resql) {
2140 $obj = $this->db->fetch_object($resql);
2141 // Test for avoid error -1
2142 if ($obj) {
2143 if (method_exists($this, 'fetch')) {
2144 $result = $this->fetch($obj->rowid);
2145 } else {
2146 $this->error = 'fetch() method not implemented on '.get_class($this);
2147 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2148 array_push($this->errors, $this->error);
2149 $result = -1;
2150 }
2151 }
2152 }
2153
2154 return $result;
2155 }
2156
2165 public function getValueFrom($table, $id, $field)
2166 {
2167 $result = false;
2168 if (!empty($id) && !empty($field) && !empty($table)) {
2169 $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
2170 $sql .= " WHERE rowid = ".((int) $id);
2171
2172 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2173 $resql = $this->db->query($sql);
2174 if ($resql) {
2175 $row = $this->db->fetch_row($resql);
2176 $result = $row[0];
2177 }
2178 }
2179 return $result;
2180 }
2181
2198 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2199 {
2200 global $user;
2201
2202 if (empty($table)) {
2203 $table = $this->table_element;
2204 }
2205 if (empty($id)) {
2206 $id = $this->id;
2207 }
2208 if (empty($format)) {
2209 $format = 'text';
2210 }
2211 if (empty($id_field)) {
2212 $id_field = 'rowid';
2213 }
2214
2215 // Special case
2216 if ($table == 'product' && $field == 'note_private') {
2217 $field = 'note';
2218 }
2219
2220 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2221 $fk_user_field = 'fk_user_mod';
2222 }
2223 if (in_array($table, array('prelevement_bons'))) { // TODO Add a field fk_user_modif into llx_prelevement_bons
2224 $fk_user_field = '';
2225 }
2226
2227 $oldvalue = null;
2228 if ($trigkey) {
2229 $sql = "SELECT " . $field;
2230 $sql .= " FROM " . MAIN_DB_PREFIX . $table;
2231 $sql .= " WHERE " . $id_field . " = " . ((int) $id);
2232
2233 $resql = $this->db->query($sql);
2234 if ($resql) {
2235 if ($obj = $this->db->fetch_object($resql)) {
2236 if ($format == 'date') {
2237 $oldvalue = $this->db->jdate($obj->$field);
2238 } else {
2239 $oldvalue = $obj->$field;
2240 }
2241 }
2242 } else {
2243 $this->error = $this->db->lasterror();
2244 return -1;
2245 }
2246 }
2247
2248 $error = 0;
2249
2250 dol_syslog(__METHOD__, LOG_DEBUG);
2251
2252 $this->db->begin();
2253
2254 $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2255
2256 if ($format == 'text') {
2257 $sql .= $field." = '".$this->db->escape($value)."'";
2258 } elseif ($format == 'int') {
2259 $sql .= $field." = ".((int) $value);
2260 } elseif ($format == 'date') {
2261 $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2262 } elseif ($format == 'dategmt') {
2263 $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
2264 }
2265
2266 if ($fk_user_field) {
2267 if (!empty($fuser) && is_object($fuser)) {
2268 $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2269 } elseif (empty($fuser) || $fuser != 'none') {
2270 $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2271 }
2272 }
2273
2274 $sql .= " WHERE ".$id_field." = ".((int) $id);
2275
2276 $resql = $this->db->query($sql);
2277 if ($resql) {
2278 if ($trigkey) {
2279 // call trigger with updated object values
2280 if (method_exists($this, 'fetch')) {
2281 $result = $this->fetch($id);
2282 } else {
2283 $result = $this->fetchCommon($id);
2284 }
2285 $this->oldcopy = clone $this;
2286 if (property_exists($this->oldcopy, $field)) {
2287 $this->oldcopy->$field = $oldvalue;
2288 }
2289
2290 if ($result >= 0) {
2291 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2292 }
2293 if ($result < 0) {
2294 $error++;
2295 }
2296 }
2297
2298 if (!$error) {
2299 if (property_exists($this, $field)) {
2300 $this->$field = $value;
2301 }
2302 $this->db->commit();
2303 return 1;
2304 } else {
2305 $this->db->rollback();
2306 return -2;
2307 }
2308 } else {
2309 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2310 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2311 } else {
2312 $this->error = $this->db->lasterror();
2313 }
2314 $this->db->rollback();
2315 return -1;
2316 }
2317 }
2318
2319 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2330 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2331 {
2332 // phpcs:enable
2333 global $conf, $user;
2334
2335 if (!$this->table_element) {
2336 dol_print_error(null, get_class($this)."::load_previous_next_ref was called on object with property table_element not defined");
2337 return -1;
2338 }
2339 if ($fieldid == 'none') {
2340 return 1;
2341 }
2342
2343 // For backward compatibility
2344 if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2345 $fieldid = 'titre';
2346 }
2347
2348 // Security on socid
2349 $socid = 0;
2350 if ($user->socid > 0) {
2351 $socid = $user->socid;
2352 }
2353
2354 // this->ismultientitymanaged contains
2355 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2356 $aliastablesociete = 's';
2357 if ($this->element == 'societe') {
2358 $aliastablesociete = 'te'; // te as table_element
2359 }
2360 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2361 $sql = "SELECT MAX(te.".$fieldid.")";
2362 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2363 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2364 $tmparray = explode('@', $this->ismultientitymanaged);
2365 $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2366 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2367 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2368 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2369 $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
2370 }
2371 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2372 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2373 }
2374 if ($fieldid == 'rowid') {
2375 $sql .= " WHERE te.".$fieldid." < ".((int) $this->id);
2376 } else {
2377 $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2378 }
2379 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2380 $sql .= " AND sc.fk_user = ".((int) $user->id);
2381 }
2382 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2383 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2384 }
2385
2386 $filtermax = $filter;
2387
2388 // Manage filter
2389 $errormessage = '';
2390 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermax, $errormessage);
2391 if ($errormessage) {
2392 if (!preg_match('/^\s*AND/i', $filtermax)) {
2393 $sql .= " AND ";
2394 }
2395 $sql .= $filtermax;
2396 } else {
2397 $sql .= $tmpsql;
2398 }
2399
2400 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2401 $tmparray = explode('@', $this->ismultientitymanaged);
2402 $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2403 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2404 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2405 }
2406 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2407 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2408 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2409 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2410 } else {
2411 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2412 }
2413 } else {
2414 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2415 }
2416 }
2417 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2418 $tmparray = explode('@', $this->ismultientitymanaged);
2419 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2420 }
2421 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2422 $sql .= ' AND te.fk_soc = '.((int) $socid);
2423 }
2424 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2425 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2426 }
2427 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2428 $sql .= ' AND te.rowid = '.((int) $socid);
2429 }
2430 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2431
2432 $result = $this->db->query($sql);
2433 if (!$result) {
2434 $this->error = $this->db->lasterror();
2435 return -1;
2436 }
2437 $row = $this->db->fetch_row($result);
2438 $this->ref_previous = $row[0];
2439
2440 $sql = "SELECT MIN(te.".$fieldid.")";
2441 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2442 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2443 $tmparray = explode('@', $this->ismultientitymanaged);
2444 $sql .= ", ".$this->db->prefix().$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity
2445 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2446 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2447 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2448 $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
2449 }
2450 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2451 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2452 }
2453 if ($fieldid == 'rowid') {
2454 $sql .= " WHERE te.".$fieldid." > ".((int) $this->id);
2455 } else {
2456 $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2457 }
2458 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2459 $sql .= " AND (sc.fk_user = ".((int) $user->id);
2460 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
2461 $userschilds = $user->getAllChildIds();
2462 $sql .= " OR sc.fk_user IN (".$this->db->sanitize(implode(',', $userschilds)).")";
2463 }
2464 $sql .= ')';
2465 }
2466 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2467 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2468 }
2469
2470 $filtermin = $filter;
2471
2472 // Manage filter
2473 $errormessage = '';
2474 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermin, $errormessage);
2475 if ($errormessage) {
2476 if (!preg_match('/^\s*AND/i', $filtermin)) {
2477 $sql .= " AND ";
2478 }
2479 $sql .= $filtermin;
2480
2481 $filtermin = '';
2482 } else {
2483 $sql .= $tmpsql;
2484 }
2485
2486 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2487 $tmparray = explode('@', $this->ismultientitymanaged);
2488 $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2489 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2490 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2491 }
2492 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2493 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2494 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2495 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2496 } else {
2497 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2498 }
2499 } else {
2500 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2501 }
2502 }
2503 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2504 $tmparray = explode('@', $this->ismultientitymanaged);
2505 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2506 }
2507 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2508 $sql .= ' AND te.fk_soc = '.((int) $socid);
2509 }
2510 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2511 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2512 }
2513 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2514 $sql .= ' AND te.rowid = '.((int) $socid);
2515 }
2516 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2517 // 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
2518
2519 $result = $this->db->query($sql);
2520 if (!$result) {
2521 $this->error = $this->db->lasterror();
2522 return -2;
2523 }
2524 $row = $this->db->fetch_row($result);
2525 $this->ref_next = $row[0];
2526
2527 return 1;
2528 }
2529
2530
2538 public function getListContactId($source = 'external')
2539 {
2540 $contactAlreadySelected = array();
2541 $tab = $this->liste_contact(-1, $source);
2542 $num = count($tab);
2543 $i = 0;
2544 while ($i < $num) {
2545 if ($source == 'thirdparty') {
2546 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2547 } else {
2548 $contactAlreadySelected[$i] = $tab[$i]['id'];
2549 }
2550 $i++;
2551 }
2552 return $contactAlreadySelected;
2553 }
2554
2555
2563 public function setProject($projectid, $notrigger = 0)
2564 {
2565 global $user;
2566 $error = 0;
2567
2568 if (!$this->table_element) {
2569 dol_syslog(get_class($this)."::setProject was called on object with property table_element not defined", LOG_ERR);
2570 return -1;
2571 }
2572
2573 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2574 // @phan-suppress-next-line PhanTypeMismatchProperty
2575 if (!empty($this->fields['fk_project'])) { // Common case
2576 if ($projectid) {
2577 $sql .= " SET fk_project = ".((int) $projectid);
2578 } else {
2579 $sql .= " SET fk_project = NULL";
2580 }
2581 $sql .= ' WHERE rowid = '.((int) $this->id);
2582 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2583 if ($projectid) {
2584 $sql .= " SET fk_project = ".((int) $projectid);
2585 } else {
2586 $sql .= " SET fk_project = NULL";
2587 }
2588 $sql .= ' WHERE id = '.((int) $this->id);
2589 } else { // Special case for old architecture objects
2590 if ($projectid) {
2591 $sql .= ' SET fk_projet = '.((int) $projectid);
2592 } else {
2593 $sql .= ' SET fk_projet = NULL';
2594 }
2595 $sql .= " WHERE rowid = ".((int) $this->id);
2596 }
2597
2598 $this->db->begin();
2599
2600 dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2601 if ($this->db->query($sql)) {
2602 $this->fk_project = ((int) $projectid);
2603 } else {
2604 dol_print_error($this->db);
2605 $error++;
2606 }
2607
2608 // Triggers
2609 if (!$error && !$notrigger) {
2610 // Call triggers
2611 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2612 if ($result < 0) {
2613 $error++;
2614 } //Do also here what you must do to rollback action if trigger fail
2615 // End call triggers
2616 }
2617
2618 // Commit or rollback
2619 if ($error) {
2620 $this->db->rollback();
2621 return -1;
2622 } else {
2623 $this->db->commit();
2624 return 1;
2625 }
2626 }
2627
2634 public function setPaymentMethods($id)
2635 {
2636 global $user;
2637
2638 $error = 0;
2639 $notrigger = 0;
2640
2641 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2642
2643 if ($this->status >= 0 || $this->element == 'societe') {
2644 // TODO uniformize field name
2645 $fieldname = 'fk_mode_reglement';
2646 if ($this->element == 'societe') {
2647 $fieldname = 'mode_reglement';
2648 }
2649 if (get_class($this) == 'Fournisseur') {
2650 $fieldname = 'mode_reglement_supplier';
2651 }
2652 if (get_class($this) == 'Tva') {
2653 $fieldname = 'fk_typepayment';
2654 }
2655 if (get_class($this) == 'Salary') {
2656 $fieldname = 'fk_typepayment';
2657 }
2658
2659 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2660 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2661 $sql .= ' WHERE rowid='.((int) $this->id);
2662
2663 if ($this->db->query($sql)) {
2664 $this->mode_reglement_id = $id;
2665 // for supplier
2666 if (get_class($this) == 'Fournisseur') {
2667 $this->mode_reglement_supplier_id = $id;
2668 }
2669 // Triggers
2670 if (!$error && !$notrigger) {
2671 // Call triggers
2672 if (get_class($this) == 'Commande') {
2673 $result = $this->call_trigger('ORDER_MODIFY', $user);
2674 } else {
2675 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2676 }
2677 if ($result < 0) {
2678 $error++;
2679 }
2680 // End call triggers
2681 }
2682 return 1;
2683 } else {
2684 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2685 $this->error = $this->db->error();
2686 return -1;
2687 }
2688 } else {
2689 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2690 $this->error = 'Status of the object is incompatible '.$this->status;
2691 return -2;
2692 }
2693 }
2694
2701 public function setMulticurrencyCode($code)
2702 {
2703 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2704 if ($this->status >= 0 || $this->element == 'societe') {
2705 $fieldname = 'multicurrency_code';
2706
2707 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2708 $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2709 $sql .= ' WHERE rowid='.((int) $this->id);
2710
2711 if ($this->db->query($sql)) {
2712 $this->multicurrency_code = $code;
2713
2714 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2715 if ($rate) {
2716 $this->setMulticurrencyRate($rate, 2);
2717 }
2718
2719 return 1;
2720 } else {
2721 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2722 $this->error = $this->db->error();
2723 return -1;
2724 }
2725 } else {
2726 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2727 $this->error = 'Status of the object is incompatible '.$this->status;
2728 return -2;
2729 }
2730 }
2731
2739 public function setMulticurrencyRate($rate, $mode = 1)
2740 {
2741 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.', '.$mode.')');
2742 if ($this->status >= 0 || $this->element == 'societe') {
2743 $fieldname = 'multicurrency_tx';
2744
2745 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2746 $sql .= " SET ".$fieldname." = ".((float) $rate);
2747 $sql .= ' WHERE rowid='.((int) $this->id);
2748
2749 if ($this->db->query($sql)) {
2750 $this->multicurrency_tx = $rate;
2751
2752 // Update line price
2753 if (!empty($this->lines)) {
2754 foreach ($this->lines as &$line) {
2755 // Amounts in company currency will be recalculated
2756 if ($mode == 1) {
2757 $line->subprice = 0;
2758 }
2759
2760 // Amounts in foreign currency will be recalculated
2761 if ($mode == 2) {
2762 $line->multicurrency_subprice = 0;
2763 }
2764
2765 switch ($this->element) {
2766 case 'propal':
2769 '@phan-var-force Propal $this';
2770 '@phan-var-force PropaleLigne $line';
2771 $this->updateline(
2772 $line->id,
2773 $line->subprice,
2774 $line->qty,
2775 $line->remise_percent,
2776 $line->tva_tx,
2777 $line->localtax1_tx,
2778 $line->localtax2_tx,
2779 ($line->description ? $line->description : $line->desc),
2780 'HT',
2781 $line->info_bits,
2782 $line->special_code,
2783 $line->fk_parent_line,
2784 $line->skip_update_total,
2785 $line->fk_fournprice,
2786 $line->pa_ht,
2787 $line->label,
2788 $line->product_type,
2789 $line->date_start,
2790 $line->date_end,
2791 $line->array_options,
2792 $line->fk_unit,
2793 $line->multicurrency_subprice
2794 );
2795 break;
2796 case 'commande':
2799 '@phan-var-force Commande $this';
2800 '@phan-var-force OrderLine $line';
2801 $this->updateline(
2802 $line->id,
2803 ($line->description ? $line->description : $line->desc),
2804 $line->subprice,
2805 $line->qty,
2806 $line->remise_percent,
2807 $line->tva_tx,
2808 $line->localtax1_tx,
2809 $line->localtax2_tx,
2810 'HT',
2811 $line->info_bits,
2812 $line->date_start,
2813 $line->date_end,
2814 $line->product_type,
2815 $line->fk_parent_line,
2816 $line->skip_update_total,
2817 $line->fk_fournprice,
2818 $line->pa_ht,
2819 $line->label,
2820 $line->special_code,
2821 $line->array_options,
2822 $line->fk_unit,
2823 $line->multicurrency_subprice
2824 );
2825 break;
2826 case 'facture':
2829 '@phan-var-force Facture $this';
2830 '@phan-var-force FactureLigne $line';
2831 $this->updateline(
2832 $line->id,
2833 ($line->description ? $line->description : $line->desc),
2834 $line->subprice,
2835 $line->qty,
2836 $line->remise_percent,
2837 $line->date_start,
2838 $line->date_end,
2839 $line->tva_tx,
2840 $line->localtax1_tx,
2841 $line->localtax2_tx,
2842 'HT',
2843 $line->info_bits,
2844 $line->product_type,
2845 $line->fk_parent_line,
2846 $line->skip_update_total,
2847 $line->fk_fournprice,
2848 $line->pa_ht,
2849 $line->label,
2850 $line->special_code,
2851 $line->array_options,
2852 $line->situation_percent,
2853 $line->fk_unit,
2854 $line->multicurrency_subprice
2855 );
2856 break;
2857 case 'supplier_proposal':
2860 '@phan-var-force SupplierProposal $this';
2861 '@phan-var-force SupplierProposalLine $line';
2862 $this->updateline(
2863 $line->id,
2864 $line->subprice,
2865 $line->qty,
2866 $line->remise_percent,
2867 $line->tva_tx,
2868 $line->localtax1_tx,
2869 $line->localtax2_tx,
2870 ($line->description ? $line->description : $line->desc),
2871 'HT',
2872 $line->info_bits,
2873 $line->special_code,
2874 $line->fk_parent_line,
2875 $line->skip_update_total,
2876 $line->fk_fournprice,
2877 $line->pa_ht,
2878 $line->label,
2879 $line->product_type,
2880 $line->array_options,
2881 $line->ref_fourn,
2882 $line->multicurrency_subprice
2883 );
2884 break;
2885 case 'order_supplier':
2888 '@phan-var-force CommandeFournisseur $this';
2889 '@phan-var-force CommandeFournisseurLigne $line';
2890 $this->updateline(
2891 $line->id,
2892 ($line->description ? $line->description : $line->desc),
2893 $line->subprice,
2894 $line->qty,
2895 $line->remise_percent,
2896 $line->tva_tx,
2897 $line->localtax1_tx,
2898 $line->localtax2_tx,
2899 'HT',
2900 $line->info_bits,
2901 $line->product_type,
2902 0,
2903 $line->date_start,
2904 $line->date_end,
2905 $line->array_options,
2906 $line->fk_unit,
2907 $line->multicurrency_subprice,
2908 $line->ref_supplier
2909 );
2910 break;
2911 case 'invoice_supplier':
2914 '@phan-var-force FactureFournisseur $this';
2915 '@phan-var-force SupplierInvoiceLIne $line';
2916 $this->updateline(
2917 $line->id,
2918 ($line->description ? $line->description : $line->desc),
2919 $line->subprice,
2920 $line->tva_tx,
2921 $line->localtax1_tx,
2922 $line->localtax2_tx,
2923 $line->qty,
2924 0,
2925 'HT',
2926 $line->info_bits,
2927 $line->product_type,
2928 $line->remise_percent,
2929 0,
2930 $line->date_start,
2931 $line->date_end,
2932 $line->array_options,
2933 $line->fk_unit,
2934 $line->multicurrency_subprice,
2935 $line->ref_supplier
2936 );
2937 break;
2938 default:
2939 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2940 break;
2941 }
2942 }
2943 }
2944
2945 return 1;
2946 } else {
2947 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2948 $this->error = $this->db->error();
2949 return -1;
2950 }
2951 } else {
2952 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2953 $this->error = 'Status of the object is incompatible '.$this->status;
2954 return -2;
2955 }
2956 }
2957
2965 public function setPaymentTerms($id, $deposit_percent = null)
2966 {
2967 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2968 if ($this->status >= 0 || $this->element == 'societe') {
2969 // TODO uniformize field name
2970 $fieldname = 'fk_cond_reglement';
2971 if ($this->element == 'societe') {
2972 $fieldname = 'cond_reglement';
2973 }
2974 if (get_class($this) == 'Fournisseur') {
2975 $fieldname = 'cond_reglement_supplier';
2976 }
2977
2978 if (empty($deposit_percent) || $deposit_percent < 0) {
2979 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2980 }
2981
2982 if ($deposit_percent > 100) {
2983 $deposit_percent = 100;
2984 }
2985
2986 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2987 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2988 if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
2989 $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2990 }
2991 $sql .= ' WHERE rowid='.((int) $this->id);
2992
2993 if ($this->db->query($sql)) {
2994 $this->cond_reglement_id = $id;
2995 // for supplier
2996 if (get_class($this) == 'Fournisseur') {
2997 $this->cond_reglement_supplier_id = $id;
2998 }
2999 $this->cond_reglement = $id; // for compatibility
3000 $this->deposit_percent = $deposit_percent;
3001 return 1;
3002 } else {
3003 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
3004 $this->error = $this->db->error();
3005 return -1;
3006 }
3007 } else {
3008 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
3009 $this->error = 'Status of the object is incompatible '.$this->status;
3010 return -2;
3011 }
3012 }
3013
3020 public function setTransportMode($id)
3021 {
3022 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
3023 if ($this->status >= 0 || $this->element == 'societe') {
3024 $fieldname = 'fk_transport_mode';
3025 if ($this->element == 'societe') {
3026 $fieldname = 'transport_mode';
3027 }
3028 if (get_class($this) == 'Fournisseur') {
3029 $fieldname = 'transport_mode_supplier';
3030 }
3031
3032 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3033 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3034 $sql .= ' WHERE rowid='.((int) $this->id);
3035
3036 if ($this->db->query($sql)) {
3037 $this->transport_mode_id = $id;
3038 // for supplier
3039 if (get_class($this) == 'Fournisseur') {
3040 $this->transport_mode_supplier_id = $id;
3041 }
3042 return 1;
3043 } else {
3044 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
3045 $this->error = $this->db->error();
3046 return -1;
3047 }
3048 } else {
3049 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
3050 $this->error = 'Status of the object is incompatible '.$this->status;
3051 return -2;
3052 }
3053 }
3054
3062 {
3063 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
3064 if ($this->status >= 0 || $this->element == 'societe') {
3065 $fieldname = 'retained_warranty_fk_cond_reglement';
3066
3067 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3068 $sql .= " SET ".$fieldname." = ".((int) $id);
3069 $sql .= ' WHERE rowid='.((int) $this->id);
3070
3071 if ($this->db->query($sql)) {
3072 $this->retained_warranty_fk_cond_reglement = $id;
3073 return 1;
3074 } else {
3075 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
3076 $this->error = $this->db->error();
3077 return -1;
3078 }
3079 } else {
3080 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3081 $this->error = 'Status of the object is incompatible '.$this->status;
3082 return -2;
3083 }
3084 }
3085
3093 public function setDeliveryAddress($id)
3094 {
3095 $fieldname = 'fk_delivery_address';
3096 if ($this->element == 'delivery' || $this->element == 'shipping') {
3097 $fieldname = 'fk_address';
3098 }
3099
3100 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
3101 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
3102
3103 if ($this->db->query($sql)) {
3104 $this->fk_delivery_address = $id;
3105 return 1;
3106 } else {
3107 $this->error = $this->db->error();
3108 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
3109 return -1;
3110 }
3111 }
3112
3113
3122 public function setShippingMethod($shipping_method_id, $notrigger = 0, $userused = null)
3123 {
3124 global $user;
3125
3126 if (empty($userused)) {
3127 $userused = $user;
3128 }
3129
3130 $error = 0;
3131
3132 if (!$this->table_element) {
3133 dol_syslog(get_class($this)."::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3134 return -1;
3135 }
3136
3137 $this->db->begin();
3138
3139 if ($shipping_method_id < 0) {
3140 $shipping_method_id = 'NULL';
3141 }
3142 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
3143
3144 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3145 $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
3146 $sql .= " WHERE rowid=".((int) $this->id);
3147 $resql = $this->db->query($sql);
3148 if (!$resql) {
3149 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
3150 $this->error = $this->db->lasterror();
3151 $error++;
3152 } else {
3153 if (!$notrigger) {
3154 // Call trigger
3155 $this->context = array('shippingmethodupdate' => 1);
3156 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3157 if ($result < 0) {
3158 $error++;
3159 }
3160 // End call trigger
3161 }
3162 }
3163 if ($error) {
3164 $this->db->rollback();
3165 return -1;
3166 } else {
3167 $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id;
3168 $this->db->commit();
3169 return 1;
3170 }
3171 }
3172
3173
3180 public function setWarehouse($warehouse_id)
3181 {
3182 if (!$this->table_element) {
3183 dol_syslog(get_class($this)."::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3184 return -1;
3185 }
3186 if ($warehouse_id < 0) {
3187 $warehouse_id = 'NULL';
3188 }
3189 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
3190
3191 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3192 $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
3193 $sql .= " WHERE rowid=".((int) $this->id);
3194
3195 if ($this->db->query($sql)) {
3196 $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id;
3197 return 1;
3198 } else {
3199 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
3200 $this->error = $this->db->error();
3201 return 0;
3202 }
3203 }
3204
3205
3213 public function setDocModel($user, $modelpdf)
3214 {
3215 if (!$this->table_element) {
3216 dol_syslog(get_class($this)."::setDocModel was called on object with property table_element not defined", LOG_ERR);
3217 return -1;
3218 }
3219
3220 $newmodelpdf = dol_trunc($modelpdf, 255);
3221
3222 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3223 $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
3224 $sql .= " WHERE rowid = ".((int) $this->id);
3225
3226 dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
3227 $resql = $this->db->query($sql);
3228 if ($resql) {
3229 $this->model_pdf = $modelpdf;
3230 return 1;
3231 } else {
3232 dol_print_error($this->db);
3233 return 0;
3234 }
3235 }
3236
3237
3246 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
3247 {
3248 global $user;
3249
3250 if (empty($userused)) {
3251 $userused = $user;
3252 }
3253
3254 $error = 0;
3255
3256 if (!$this->table_element) {
3257 dol_syslog(get_class($this)."::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3258 return -1;
3259 }
3260 $this->db->begin();
3261
3262 if ($fk_account < 0) {
3263 $fk_account = 'NULL';
3264 }
3265 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3266
3267 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3268 $sql .= " SET fk_account = ".((int) $fk_account);
3269 $sql .= " WHERE rowid=".((int) $this->id);
3270
3271 $resql = $this->db->query($sql);
3272 if (!$resql) {
3273 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3274 $this->error = $this->db->lasterror();
3275 $error++;
3276 } else {
3277 if (!$notrigger) {
3278 // Call trigger
3279 $this->context['bankaccountupdate'] = 1;
3280 $triggerName = strtoupper(get_class($this)).'_MODIFY';
3281 // Special cases
3282 if ($triggerName == 'FACTUREREC_MODIFY') {
3283 $triggerName = 'BILLREC_MODIFY';
3284 }
3285 $result = $this->call_trigger($triggerName, $userused);
3286 if ($result < 0) {
3287 $error++;
3288 }
3289 // End call trigger
3290 }
3291 }
3292 if ($error) {
3293 $this->db->rollback();
3294 return -1;
3295 } else {
3296 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
3297 $this->db->commit();
3298 return 1;
3299 }
3300 }
3301
3302
3303 // TODO: Move line related operations to CommonObjectLine?
3304
3305 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3315 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3316 {
3317 // phpcs:enable
3318 if (!$this->table_element_line) {
3319 dol_syslog(get_class($this)."::line_order was called on object with property table_element_line not defined", LOG_ERR);
3320 return -1;
3321 }
3322 if (!$this->fk_element) {
3323 dol_syslog(get_class($this)."::line_order was called on object with property fk_element not defined", LOG_ERR);
3324 return -1;
3325 }
3326
3327 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3328 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3329 $fieldposition = 'position';
3330 }
3331
3332 // Count number of lines to reorder (according to choice $renum)
3333 $nl = 0;
3334 $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3335 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3336 if (!$renum) {
3337 $sql .= " AND " . $fieldposition . " = 0";
3338 }
3339 if ($renum) {
3340 $sql .= " AND " . $fieldposition . " <> 0";
3341 }
3342
3343 dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3344 $resql = $this->db->query($sql);
3345 if ($resql) {
3346 $row = $this->db->fetch_row($resql);
3347 $nl = $row[0];
3348 } else {
3349 dol_print_error($this->db);
3350 }
3351 if ($nl > 0) {
3352 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3353 $rows = array();
3354
3355 // We first search all lines that are parent lines (for multilevel details lines)
3356 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3357 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3358 if ($fk_parent_line) {
3359 $sql .= ' AND fk_parent_line IS NULL';
3360 }
3361 $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3362
3363 dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3364 $resql = $this->db->query($sql);
3365 if ($resql) {
3366 $i = 0;
3367 $num = $this->db->num_rows($resql);
3368 $grandchild = getDolGlobalInt('MAIN_CARE_GRANDCHILD');
3369 while ($i < $num) {
3370 $row = $this->db->fetch_row($resql);
3371 $rows[] = $row[0]; // Add parent line into array rows
3372 $children = $this->getChildrenOfLine($row[0], $grandchild);
3373 if (!empty($children)) {
3374 foreach ($children as $child) {
3375 array_push($rows, $child);
3376 }
3377 }
3378 $i++;
3379 }
3380
3381 // Now we set a new number for each lines (parent and children with children included into parent tree)
3382 if (!empty($rows)) {
3383 foreach ($rows as $key => $row) {
3384 $this->updateRangOfLine($row, ($key + 1));
3385 }
3386 }
3387 } else {
3388 dol_print_error($this->db);
3389 }
3390 }
3391 return 1;
3392 }
3393
3401 public function getChildrenOfLine($id, $includealltree = 0)
3402 {
3403 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3404 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3405 $fieldposition = 'position';
3406 }
3407
3408 $rows = array();
3409
3410 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3411 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3412 $sql .= ' AND fk_parent_line = '.((int) $id);
3413 $sql .= " ORDER BY " . $fieldposition . " ASC";
3414
3415 dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3416
3417 $resql = $this->db->query($sql);
3418 if ($resql) {
3419 if ($this->db->num_rows($resql) > 0) {
3420 while ($row = $this->db->fetch_row($resql)) {
3421 $rows[] = $row[0];
3422 if (!empty($includealltree) && $includealltree <= 1000) { // Test <= 1000 is a protection in depth of recursive call to avoid infinite loop
3423 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree + 1));
3424 }
3425 }
3426 }
3427 }
3428 return $rows;
3429 }
3430
3431 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3439 public function line_up($rowid, $fk_parent_line = true)
3440 {
3441 // phpcs:enable
3442 $this->line_order(false, 'ASC', $fk_parent_line);
3443
3444 // Get rang of line
3445 $rang = $this->getRangOfLine($rowid);
3446
3447 // Update position of line
3448 $this->updateLineUp($rowid, $rang);
3449 }
3450
3451 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3459 public function line_down($rowid, $fk_parent_line = true)
3460 {
3461 // phpcs:enable
3462 $this->line_order(false, 'ASC', $fk_parent_line);
3463
3464 // Get rang of line
3465 $rang = $this->getRangOfLine($rowid);
3466
3467 // Get max value for rang
3468 $max = $this->line_max();
3469
3470 // Update position of line
3471 $this->updateLineDown($rowid, $rang, $max);
3472 }
3473
3481 public function updateRangOfLine($rowid, $rang)
3482 {
3483 global $hookmanager;
3484 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3485 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3486 $fieldposition = 'position';
3487 }
3488
3489 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3490 $sql .= ' WHERE rowid = '.((int) $rowid);
3491
3492 dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3493 if (!$this->db->query($sql)) {
3494 dol_print_error($this->db);
3495 return -1;
3496 } else {
3497 $parameters = array('rowid' => $rowid, 'rang' => $rang, 'fieldposition' => $fieldposition);
3498 $action = '';
3499 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3500 return 1;
3501 }
3502 }
3503
3504 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3511 public function line_ajaxorder($rows)
3512 {
3513 // phpcs:enable
3514 $num = count($rows);
3515 for ($i = 0; $i < $num; $i++) {
3516 $this->updateRangOfLine($rows[$i], ($i + 1));
3517 }
3518 }
3519
3527 public function updateLineUp($rowid, $rang)
3528 {
3529 if ($rang > 1) {
3530 $fieldposition = 'rang';
3531 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3532 $fieldposition = 'position';
3533 }
3534
3535 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3536 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3537 $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3538 if ($this->db->query($sql)) {
3539 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3540 $sql .= ' WHERE rowid = '.((int) $rowid);
3541 if (!$this->db->query($sql)) {
3542 dol_print_error($this->db);
3543 }
3544 } else {
3545 dol_print_error($this->db);
3546 }
3547 }
3548 }
3549
3558 public function updateLineDown($rowid, $rang, $max)
3559 {
3560 if ($rang < $max) {
3561 $fieldposition = 'rang';
3562 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3563 $fieldposition = 'position';
3564 }
3565
3566 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3567 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3568 $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3569 if ($this->db->query($sql)) {
3570 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3571 $sql .= ' WHERE rowid = '.((int) $rowid);
3572 if (!$this->db->query($sql)) {
3573 dol_print_error($this->db);
3574 }
3575 } else {
3576 dol_print_error($this->db);
3577 }
3578 }
3579 }
3580
3587 public function getRangOfLine($rowid)
3588 {
3589 $fieldposition = 'rang';
3590 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3591 $fieldposition = 'position';
3592 }
3593
3594 $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3595 $sql .= " WHERE rowid = ".((int) $rowid);
3596
3597 dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3598 $resql = $this->db->query($sql);
3599 if ($resql) {
3600 $row = $this->db->fetch_row($resql);
3601 return $row[0];
3602 }
3603
3604 return 0;
3605 }
3606
3613 public function getIdOfLine($rang)
3614 {
3615 $fieldposition = 'rang';
3616 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3617 $fieldposition = 'position';
3618 }
3619
3620 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3621 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3622 $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3623 $resql = $this->db->query($sql);
3624 if ($resql) {
3625 $row = $this->db->fetch_row($resql);
3626 return $row[0];
3627 }
3628
3629 return 0;
3630 }
3631
3632 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3639 public function line_max($fk_parent_line = 0)
3640 {
3641 // phpcs:enable
3642 $positionfield = 'rang';
3643 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3644 $positionfield = 'position';
3645 }
3646
3647 // Search the last rang with fk_parent_line
3648 if ($fk_parent_line) {
3649 $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3650 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3651 $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3652
3653 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3654 $resql = $this->db->query($sql);
3655 if ($resql) {
3656 $row = $this->db->fetch_row($resql);
3657 if (!empty($row[0])) {
3658 return $row[0];
3659 } else {
3660 return $this->getRangOfLine($fk_parent_line);
3661 }
3662 }
3663 } else {
3664 // If not, search the last rang of element
3665 $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3666 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3667
3668 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3669 $resql = $this->db->query($sql);
3670 if ($resql) {
3671 $row = $this->db->fetch_row($resql);
3672 return $row[0];
3673 }
3674 }
3675
3676 return 0;
3677 }
3678
3679 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3686 public function update_ref_ext($ref_ext)
3687 {
3688 // phpcs:enable
3689 if (!$this->table_element) {
3690 dol_syslog(get_class($this)."::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3691 return -1;
3692 }
3693
3694 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3695 $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3696 // @phan-suppress-next-line PhanUndeclaredProperty
3697 $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3698
3699 dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3700 if ($this->db->query($sql)) {
3701 $this->ref_ext = $ref_ext;
3702 return 1;
3703 } else {
3704 $this->error = $this->db->error();
3705 return -1;
3706 }
3707 }
3708
3709 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3718 public function update_note($note, $suffix = '', $notrigger = 0)
3719 {
3720 // phpcs:enable
3721 global $user;
3722
3723 if (!$this->table_element) {
3724 $this->error = 'update_note was called on object with property table_element not defined';
3725 dol_syslog(get_class($this)."::update_note was called on object with property table_element not defined", LOG_ERR);
3726 return -1;
3727 }
3728 if (!in_array($suffix, array('', '_public', '_private'))) {
3729 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3730 dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3731 return -2;
3732 }
3733
3734 $newsuffix = $suffix;
3735
3736 // Special case
3737 if ($this->table_element == 'product' && $newsuffix == '_private') {
3738 $newsuffix = '';
3739 }
3740 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3741 $fieldusermod = "fk_user_mod";
3742 } elseif ($this->table_element == 'ecm_files') {
3743 $fieldusermod = "fk_user_m";
3744 } else {
3745 $fieldusermod = "fk_user_modif";
3746 }
3747 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3748 $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3749 $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3750 $sql .= " WHERE rowid = ".((int) $this->id);
3751
3752 dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3753 if ($this->db->query($sql)) {
3754 if ($suffix == '_public') {
3755 $this->note_public = $note;
3756 } elseif ($suffix == '_private') {
3757 $this->note_private = $note;
3758 } else {
3759 $this->note = $note; // deprecated
3760 $this->note_private = $note;
3761 }
3762 if (empty($notrigger)) {
3763 switch ($this->element) {
3764 case 'societe':
3765 $trigger_name = 'COMPANY_MODIFY';
3766 break;
3767 case 'commande':
3768 $trigger_name = 'ORDER_MODIFY';
3769 break;
3770 case 'facture':
3771 $trigger_name = 'BILL_MODIFY';
3772 break;
3773 case 'invoice_supplier':
3774 $trigger_name = 'BILL_SUPPLIER_MODIFY';
3775 break;
3776 case 'facturerec':
3777 $trigger_name = 'BILLREC_MODIFIY';
3778 break;
3779 case 'expensereport':
3780 $trigger_name = 'EXPENSE_REPORT_MODIFY';
3781 break;
3782 default:
3783 $trigger_name = strtoupper($this->element) . '_MODIFY';
3784 }
3785 $ret = $this->call_trigger($trigger_name, $user);
3786 if ($ret < 0) {
3787 return -1;
3788 }
3789 }
3790 return 1;
3791 } else {
3792 $this->error = $this->db->lasterror();
3793 return -1;
3794 }
3795 }
3796
3797 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3806 public function update_note_public($note)
3807 {
3808 // phpcs:enable
3809 return $this->update_note($note, '_public');
3810 }
3811
3812 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3823 public function update_price($exclspec = 0, $roundingadjust = 'auto', $nodatabaseupdate = 0, $seller = null)
3824 {
3825 // phpcs:enable
3826 global $conf, $hookmanager, $action;
3827
3828 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3829 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3830 if ($reshook > 0) {
3831 return 1; // replacement code
3832 } elseif ($reshook < 0) {
3833 return -1; // failure
3834 } // reshook = 0 => execute normal code
3835
3836 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3837 $isElementForSupplier = false;
3838 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND'; // const for customer by default
3839 $MODULE = "";
3840 if ($this->element == 'propal') {
3841 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3842 } elseif ($this->element == 'commande' || $this->element == 'order') {
3843 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3844 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3845 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3846 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3847 $isElementForSupplier = true;
3848 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3849 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3850 $isElementForSupplier = true;
3851 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3852 } elseif ($this->element == 'supplier_proposal') {
3853 $isElementForSupplier = true;
3854 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3855 }
3856 if ($isElementForSupplier) {
3857 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER'; // const for supplier
3858 }
3859
3860 if (!empty($MODULE)) {
3861 if (getDolGlobalString($MODULE)) {
3862 $modsactivated = explode(',', getDolGlobalString($MODULE));
3863 foreach ($modsactivated as $mod) {
3864 if (isModEnabled($mod)) {
3865 return 1; // update was disabled by specific setup
3866 }
3867 }
3868 }
3869 }
3870
3871 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3872
3873 $forcedroundingmode = $roundingadjust;
3874 if ($forcedroundingmode == 'auto' && isset($conf->global->{$roundTotalConstName})) {
3875 $forcedroundingmode = getDolGlobalString($roundTotalConstName);
3876 } elseif ($forcedroundingmode == 'auto') {
3877 $forcedroundingmode = '0';
3878 }
3879
3880 $error = 0;
3881
3882 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3883
3884 // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3885 $fieldtva = 'total_tva';
3886 $fieldlocaltax1 = 'total_localtax1';
3887 $fieldlocaltax2 = 'total_localtax2';
3888 $fieldup = 'subprice';
3889 $base_price_type = 'HT';
3890 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3891 $fieldtva = 'tva';
3892 $fieldup = 'pu_ht';
3893 }
3894 if ($this->element == 'invoice_supplier_rec') {
3895 $fieldup = 'pu_ht';
3896 }
3897 if ($this->element == 'expensereport') {
3898 // Force rounding mode to '0', otherwise when you set MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND to 1, you may have lines with different totals.
3899 // 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
3900 // and 5,16 on HT total and 1,04 on VAT total to get 6,20 on TTT total on second line (see #30051).
3901 $forcedroundingmode = '0';
3902 $fieldup = 'value_unit';
3903 $base_price_type = 'TTC';
3904 }
3905
3906 $sql = "SELECT rowid, qty, ".$fieldup." as up, remise_percent, total_ht, ".$fieldtva." as total_tva, total_ttc, ".$fieldlocaltax1." as total_localtax1, ".$fieldlocaltax2." as total_localtax2,";
3907 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3908 if ($this->table_element_line == 'facturedet') {
3909 $sql .= ', situation_percent';
3910 }
3911 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3912 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3913 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3914 if ($exclspec) {
3915 $product_field = 'product_type';
3916 if ($this->table_element_line == 'contratdet') {
3917 $product_field = ''; // contratdet table has no product_type field
3918 }
3919 if ($product_field) {
3920 $sql .= " AND ".$product_field." <> 9";
3921 }
3922 }
3923 $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
3924
3925 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3926
3927 $resql = $this->db->query($sql);
3928 if ($resql) {
3929 $this->total_ht = 0;
3930 $this->total_tva = 0;
3931 $this->total_localtax1 = 0;
3932 $this->total_localtax2 = 0;
3933 $this->total_ttc = 0;
3934 $total_ht_by_vats = array();
3935 $total_tva_by_vats = array();
3936 $total_ttc_by_vats = array();
3937 $this->multicurrency_total_ht = 0;
3938 $this->multicurrency_total_tva = 0;
3939 $this->multicurrency_total_ttc = 0;
3940
3941 $this->db->begin();
3942
3943 $num = $this->db->num_rows($resql);
3944 $i = 0;
3945 while ($i < $num) {
3946 $obj = $this->db->fetch_object($resql);
3947
3948 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = '0'
3949 $parameters = array('fk_element' => $obj->rowid);
3950 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3951
3952 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'
3953 // This part of code is to fix data. We should not call it too often.
3954 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3955 $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);
3956
3957 $diff_when_using_price_ht = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1); // If price was set with tax price and unit price HT has a low number of digits, then we may have a diff on recalculation from unit price HT.
3958 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3959 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3960 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3961
3962 if ($diff_on_current_total) {
3963 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3964 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
3965 dol_syslog('We found inconsistent data into detailed line (diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (ht=".$obj->total_ht." vat=".$obj->total_tva." tax1=".$obj->total_localtax1." tax2=".$obj->total_localtax2." ttc=".$obj->total_ttc."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix, LOG_WARNING);
3966 $resqlfix = $this->db->query($sqlfix);
3967 if (!$resqlfix) {
3968 dol_print_error($this->db, 'Failed to update line');
3969 }
3970 $obj->total_tva = $tmpcal[1];
3971 $obj->total_ttc = $tmpcal[2];
3972 } elseif ($diff_when_using_price_ht) {
3973 // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3974 // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3975 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num((float) $tmpcal[1]).", total_ttc = ".price2num((float) $tmpcal[2])." WHERE rowid = ".((int) $obj->rowid);
3976 dol_syslog('We found a line with different rounding data into detailed line (diff_when_using_price_ht = '.$diff_when_using_price_ht.' and diff_on_current_total = '.$diff_on_current_total.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
3977 $resqlfix = $this->db->query($sqlfix);
3978 if (!$resqlfix) {
3979 dol_print_error($this->db, 'Failed to update line');
3980 }
3981 $obj->total_tva = $tmpcal[1];
3982 $obj->total_ttc = $tmpcal[2];
3983 }
3984 }
3985
3986 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3987 $this->total_tva += $obj->total_tva;
3988 $this->total_localtax1 += $obj->total_localtax1;
3989 $this->total_localtax2 += $obj->total_localtax2;
3990 $this->total_ttc += $obj->total_ttc;
3991 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3992 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3993 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3994
3995 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3996 $total_ht_by_vats[$obj->vatrate] = 0;
3997 }
3998 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3999 $total_tva_by_vats[$obj->vatrate] = 0;
4000 }
4001 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
4002 $total_ttc_by_vats[$obj->vatrate] = 0;
4003 }
4004 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
4005 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
4006 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
4007
4008 if ($forcedroundingmode == '1') { // Check if we need adjustment onto line for vat. TODO This works on the company currency but not on foreign currency
4009 if ($base_price_type == 'TTC') {
4010 $tmpvat = price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate), 'MT', 1);
4011 } else {
4012 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
4013 }
4014 $diff = price2num($total_tva_by_vats[$obj->vatrate] - (float) $tmpvat, 'MT', 1);
4015 //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";
4016 if ($diff) {
4017 $maxdiff = (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)));
4018 if (abs((float) $diff) > $maxdiff) {
4019 // If error is more than 10 times the accuracy of rounding. This should not happen.
4020 $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.';
4021 dol_syslog($errmsg, LOG_WARNING);
4022 $this->error = $errmsg;
4023 $error++;
4024 break;
4025 }
4026
4027 if ($base_price_type == 'TTC') {
4028 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - (float) $diff).", total_ht = ".price2num($obj->total_ht + (float) $diff)." WHERE rowid = ".((int) $obj->rowid);
4029 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);
4030 } else {
4031 $sqlfix = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldtva." = ".price2num($obj->total_tva - (float) $diff).", total_ttc = ".price2num($obj->total_ttc - (float) $diff)." WHERE rowid = ".((int) $obj->rowid);
4032 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);
4033 }
4034
4035 $resqlfix = $this->db->query($sqlfix);
4036
4037 if (!$resqlfix) {
4038 dol_print_error($this->db, 'Failed to update line');
4039 }
4040
4041 $this->total_tva = (float) price2num($this->total_tva - (float) $diff, '', 1);
4042 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4043 if ($base_price_type == 'TTC') {
4044 $this->total_ht = (float) price2num($this->total_ht + (float) $diff, '', 1);
4045 $total_ht_by_vats[$obj->vatrate] = (float) price2num($total_ht_by_vats[$obj->vatrate] + (float) $diff, '', 1);
4046 } else {
4047 $this->total_ttc = (float) price2num($this->total_ttc - (float) $diff, '', 1);
4048 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4049 }
4050 }
4051 }
4052
4053 $i++;
4054 }
4055
4056 // Add revenue stamp to total
4057 // @phan-suppress-next-line PhanUndeclaredProperty
4058 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4059 // @phan-suppress-next-line PhanUndeclaredProperty
4060 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4061
4062 // Situations totals
4063 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
4064 '@phan-var-force Facture $this';
4065 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
4066 if ($this->type != Facture::TYPE_CREDIT_NOTE) { // @phpstan-ignore-line
4067 if (getDolGlobalInt('INVOICE_USE_SITUATION') != 2) {
4068 $prev_sits = $this->get_prev_sits();
4069
4070 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
4071 $this->total_ht -= $sit->total_ht;
4072 $this->total_tva -= $sit->total_tva;
4073 $this->total_localtax1 -= $sit->total_localtax1;
4074 $this->total_localtax2 -= $sit->total_localtax2;
4075 $this->total_ttc -= $sit->total_ttc;
4076 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4077 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4078 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4079 }
4080 }
4081 }
4082 }
4083
4084 // Clean total
4085 $this->total_ht = (float) price2num($this->total_ht);
4086 $this->total_tva = (float) price2num($this->total_tva);
4087 $this->total_localtax1 = (float) price2num($this->total_localtax1);
4088 $this->total_localtax2 = (float) price2num($this->total_localtax2);
4089 $this->total_ttc = (float) price2num($this->total_ttc);
4090
4091 $this->db->free($resql);
4092
4093 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
4094 $fieldht = 'total_ht';
4095 $fieldtva = 'tva';
4096 $fieldlocaltax1 = 'localtax1';
4097 $fieldlocaltax2 = 'localtax2';
4098 $fieldttc = 'total_ttc';
4099 // Specific code for backward compatibility with old field names
4100 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
4101 $fieldtva = 'total_tva';
4102 }
4103
4104 if (!$error && empty($nodatabaseupdate)) {
4105 $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
4106 $sql .= " ".$this->db->sanitize($fieldht)." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
4107 $sql .= " ".$this->db->sanitize($fieldtva)." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
4108 $sql .= " ".$this->db->sanitize($fieldlocaltax1)." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
4109 $sql .= " ".$this->db->sanitize($fieldlocaltax2)." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
4110 $sql .= " ".$this->db->sanitize($fieldttc)." = ".((float) price2num($this->total_ttc, 'MT', 1));
4111 $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
4112 $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
4113 $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
4114 $sql .= " WHERE rowid = ".((int) $this->id);
4115
4116 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4117 $resql = $this->db->query($sql);
4118
4119 if (!$resql) {
4120 $error++;
4121 $this->error = $this->db->lasterror();
4122 $this->errors[] = $this->db->lasterror();
4123 }
4124 }
4125
4126 if (!$error) {
4127 $this->db->commit();
4128 return 1;
4129 } else {
4130 $this->db->rollback();
4131 return -1;
4132 }
4133 } else {
4134 dol_print_error($this->db, 'Bad request in update_price');
4135 return -1;
4136 }
4137 }
4138
4139 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4150 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
4151 {
4152 // phpcs:enable
4153 global $user, $hookmanager, $action;
4154 $origin = (!empty($origin) ? $origin : $this->origin);
4155 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4156 $f_user = isset($f_user) ? $f_user : $user;
4157
4158 // Special case
4159 if ($origin == 'order') {
4160 $origin = 'commande';
4161 }
4162 if ($origin == 'invoice') {
4163 $origin = 'facture';
4164 }
4165 if ($origin == 'invoice_template') {
4166 $origin = 'facturerec';
4167 }
4168 if ($origin == 'supplierorder') {
4169 $origin = 'order_supplier';
4170 }
4171
4172 // Add module part to target type
4173 $targettype = $this->getElementType();
4174
4175 $parameters = array('targettype' => $targettype);
4176 // Hook for explicitly set the targettype if it must be different than $this->element
4177 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4178 if ($reshook > 0) {
4179 if (!empty($hookmanager->resArray['targettype'])) {
4180 $targettype = $hookmanager->resArray['targettype'];
4181 }
4182 }
4183
4184 $this->db->begin();
4185 $error = 0;
4186
4187 $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
4188 $sql .= "fk_source";
4189 $sql .= ", sourcetype";
4190 $sql .= ", fk_target";
4191 $sql .= ", targettype";
4192 $sql .= ") VALUES (";
4193 $sql .= ((int) $origin_id);
4194 $sql .= ", '" . $this->db->escape($origin) . "'";
4195 $sql .= ", " . ((int) $this->id);
4196 $sql .= ", '" . $this->db->escape($targettype) . "'";
4197 $sql .= ")";
4198
4199 dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
4200 if ($this->db->query($sql)) {
4201 if (!$notrigger) {
4202 // Call trigger
4203 $this->context['link_origin'] = $origin;
4204 $this->context['link_origin_id'] = $origin_id;
4205 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
4206 if ($result < 0) {
4207 $error++;
4208 }
4209 // End call triggers
4210 }
4211 } else {
4212 $this->error = $this->db->lasterror();
4213 $error++;
4214 }
4215
4216 if (!$error) {
4217 $this->db->commit();
4218 return 1;
4219 } else {
4220 $this->db->rollback();
4221 return 0;
4222 }
4223 }
4224
4230 public function getElementType()
4231 {
4232 // 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.
4233 // 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).
4234 $coreModule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
4235 // Add module part to target type if object has $module property and isn't in core modules.
4236 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.'_' : '').$this->element;
4237 }
4238
4239
4262 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
4263 {
4264 global $conf, $hookmanager, $action;
4265
4266 // Important for pdf generation time reduction
4267 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
4268 // If you need to force the reload, you can call clearObjectLinkedCache() before calling fetchObjectLinked()
4269 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4270 return 1;
4271 }
4272
4273 $this->linkedObjectsIds = array();
4274 $this->linkedObjects = array();
4275
4276 $justsource = false;
4277 $justtarget = false;
4278 $withtargettype = false;
4279 $withsourcetype = false;
4280
4281 $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
4282 // Hook for explicitly set the targettype if it must be differtent than $this->element
4283 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4284 if ($reshook > 0) {
4285 if (!empty($hookmanager->resArray['sourcetype'])) {
4286 $sourcetype = $hookmanager->resArray['sourcetype'];
4287 }
4288 if (!empty($hookmanager->resArray['sourceid'])) {
4289 $sourceid = $hookmanager->resArray['sourceid'];
4290 }
4291 if (!empty($hookmanager->resArray['targettype'])) {
4292 $targettype = $hookmanager->resArray['targettype'];
4293 }
4294 if (!empty($hookmanager->resArray['targetid'])) {
4295 $targetid = $hookmanager->resArray['targetid'];
4296 }
4297 }
4298
4299 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4300 $justsource = true; // the source (id and type) is a search criteria
4301 if (!empty($targettype)) {
4302 $withtargettype = true;
4303 }
4304 }
4305 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4306 $justtarget = true; // the target (id and type) is a search criteria
4307 if (!empty($sourcetype)) {
4308 $withsourcetype = true;
4309 }
4310 }
4311
4312 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4313 $targetid = (!empty($targetid) ? $targetid : $this->id);
4314 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4315 $targettype = (!empty($targettype) ? $targettype : $this->element);
4316
4317 /*if (empty($sourceid) && empty($targetid))
4318 {
4319 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
4320 return -1;
4321 }*/
4322
4323 // Links between objects are stored in table element_element
4324 $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4325 $sql .= " FROM ".$this->db->prefix()."element_element";
4326 $sql .= " WHERE ";
4327 if ($justsource || $justtarget) {
4328 if ($justsource) {
4329 $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
4330 if ($withtargettype) {
4331 $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
4332 }
4333 } elseif ($justtarget) {
4334 $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
4335 if ($withsourcetype) {
4336 $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
4337 }
4338 }
4339 } else {
4340 $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
4341 $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
4342 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
4343 $this->linkedObjectsFullLoaded[$this->id] = true;
4344 }
4345 }
4346 $sql .= " ORDER BY ".$orderby;
4347
4348 dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
4349 $resql = $this->db->query($sql);
4350 if ($resql) {
4351 $num = $this->db->num_rows($resql);
4352 $i = 0;
4353 while ($i < $num) {
4354 $obj = $this->db->fetch_object($resql);
4355 if ($justsource || $justtarget) {
4356 if ($justsource) {
4357 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4358 } elseif ($justtarget) {
4359 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4360 }
4361 } else {
4362 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4363 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4364 }
4365 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4366 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4367 }
4368 }
4369 $i++;
4370 }
4371
4372 if (!empty($this->linkedObjectsIds)) {
4373 $tmparray = $this->linkedObjectsIds;
4374 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4375 $element_properties = getElementProperties($objecttype);
4376 $element = $element_properties['element'];
4377 $classPath = $element_properties['classpath'];
4378 $classFile = $element_properties['classfile'];
4379 $className = $element_properties['classname'];
4380 $module = $element_properties['module'];
4381
4382 // Here $module, $classFile and $className are set, we can use them.
4383 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4384 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4385 dol_include_once('/'.$classPath.'/'.$classFile.'.class.php');
4386 if (class_exists($className)) {
4387 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4388 $object = new $className($this->db);
4389 '@phan-var-force CommonObject $object';
4390 $ret = $object->fetch($objectid);
4391 if ($ret >= 0) {
4392 $this->linkedObjects[$objecttype][$i] = $object;
4393 }
4394 }
4395 }
4396 }
4397 } else {
4398 unset($this->linkedObjectsIds[$objecttype]);
4399 }
4400 }
4401 }
4402 return 1;
4403 } else {
4404 dol_print_error($this->db);
4405 return -1;
4406 }
4407 }
4408
4415 public function clearObjectLinkedCache()
4416 {
4417 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4418 unset($this->linkedObjectsFullLoaded[$this->id]);
4419 }
4420
4421 return 1;
4422 }
4423
4436 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4437 {
4438 global $user;
4439 $updatesource = false;
4440 $updatetarget = false;
4441 $f_user = isset($f_user) ? $f_user : $user;
4442
4443 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4444 $updatesource = true;
4445 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4446 $updatetarget = true;
4447 }
4448
4449 $this->db->begin();
4450 $error = 0;
4451
4452 $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4453 if ($updatesource) {
4454 $sql .= "fk_source = " . ((int) $sourceid);
4455 $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4456 $sql .= " WHERE fk_target = " . ((int) $this->id);
4457 $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4458 } elseif ($updatetarget) {
4459 $sql .= "fk_target = " . ((int) $targetid);
4460 $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4461 $sql .= " WHERE fk_source = " . ((int) $this->id);
4462 $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4463 }
4464
4465 dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4466 if ($this->db->query($sql)) {
4467 if (!$notrigger) {
4468 // Call trigger
4469 $this->context['link_source_id'] = $sourceid;
4470 $this->context['link_source_type'] = $sourcetype;
4471 $this->context['link_target_id'] = $targetid;
4472 $this->context['link_target_type'] = $targettype;
4473 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4474 if ($result < 0) {
4475 $error++;
4476 }
4477 // End call triggers
4478 }
4479 } else {
4480 $this->error = $this->db->lasterror();
4481 $error++;
4482 }
4483
4484 if (!$error) {
4485 $this->db->commit();
4486 return 1;
4487 } else {
4488 $this->db->rollback();
4489 return -1;
4490 }
4491 }
4492
4506 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0)
4507 {
4508 global $user;
4509 $deletesource = false;
4510 $deletetarget = false;
4511 $f_user = isset($f_user) ? $f_user : $user;
4512
4513 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4514 $deletesource = true;
4515 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4516 $deletetarget = true;
4517 }
4518
4519 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4520 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4521 $targetid = (!empty($targetid) ? $targetid : $this->id);
4522 $targettype = (!empty($targettype) ? $targettype : $this->element);
4523 $this->db->begin();
4524 $error = 0;
4525
4526 if (!$notrigger) {
4527 // Call trigger
4528 $this->context['link_id'] = $rowid;
4529 $this->context['link_source_id'] = $sourceid;
4530 $this->context['link_source_type'] = $sourcetype;
4531 $this->context['link_target_id'] = $targetid;
4532 $this->context['link_target_type'] = $targettype;
4533 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4534 if ($result < 0) {
4535 $error++;
4536 }
4537 // End call triggers
4538 }
4539
4540 if (!$error) {
4541 $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4542 $sql .= " WHERE";
4543 if ($rowid > 0) {
4544 $sql .= " rowid = " . ((int) $rowid);
4545 } else {
4546 if ($deletesource) {
4547 $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4548 $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4549 } elseif ($deletetarget) {
4550 $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4551 $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4552 } else {
4553 $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4554 $sql .= " OR";
4555 $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4556 }
4557 }
4558
4559 dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4560 if (!$this->db->query($sql)) {
4561 $this->error = $this->db->lasterror();
4562 $this->errors[] = $this->error;
4563 $error++;
4564 }
4565 }
4566
4567 if (!$error) {
4568 $this->db->commit();
4569 return 1;
4570 } else {
4571 $this->db->rollback();
4572 return 0;
4573 }
4574 }
4575
4585 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4586 {
4587 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4588 return -1;
4589 }
4590 if (!preg_match('/^[_a-zA-Z0-9]+$/', $field_select)) {
4591 dol_syslog('Invalid value $field_select for parameter '.$field_select.' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4592 }
4593
4594 global $db;
4595
4596 $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4597 $resql = $db->query($sql);
4598
4599 $TRes = array();
4600 if (!empty($resql)) {
4601 while ($res = $db->fetch_object($resql)) {
4602 $TRes[] = $res->{$field_select};
4603 }
4604 }
4605
4606 return $TRes;
4607 }
4608
4617 public static function getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4618 {
4619 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4620 return -1;
4621 }
4622
4623 global $db;
4624
4625 $sql = "SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4626 $resql = $db->query($sql);
4627 $n = 0;
4628 if ($resql) {
4629 $res = $db->fetch_object($resql);
4630 if ($res) {
4631 $n = $res->nb;
4632 }
4633 }
4634
4635 return $n;
4636 }
4637
4646 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4647 {
4648 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4649 return -1;
4650 }
4651
4652 global $db;
4653
4654 $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4655 $resql = $db->query($sql);
4656
4657 if (empty($resql)) {
4658 return 0;
4659 }
4660
4661 return 1;
4662 }
4663
4674 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4675 {
4676 global $user;
4677
4678 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4679
4680 $elementId = (!empty($elementId) ? $elementId : $this->id);
4681 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4682
4683 $this->db->begin();
4684
4685 if ($elementTable == 'facture_rec') {
4686 $fieldstatus = "suspended";
4687 }
4688 if ($elementTable == 'mailing') {
4689 $fieldstatus = "statut";
4690 }
4691 if ($elementTable == 'cronjob') {
4692 $fieldstatus = "status";
4693 }
4694 if ($elementTable == 'user') {
4695 $fieldstatus = "statut";
4696 }
4697 if ($elementTable == 'expensereport') {
4698 $fieldstatus = "fk_statut";
4699 }
4700 if ($elementTable == 'receptiondet_batch') {
4701 $fieldstatus = "status";
4702 }
4703 if ($elementTable == 'prelevement_bons') {
4704 $fieldstatus = "statut";
4705 }
4706 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4707 $fieldstatus = 'status';
4708 }
4709
4710 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4711 $sql .= " SET ".$this->db->sanitize($fieldstatus)." = ".((int) $status);
4712 // If status = 1 = validated, update also fk_user_valid
4713 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4714 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4715 $sql .= ", fk_user_valid = ".((int) $user->id);
4716 }
4717 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4718 $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4719 }
4720 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4721 $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4722 }
4723 $sql .= " WHERE rowid = ".((int) $elementId);
4724 $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4725
4726 dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4727 $resql = $this->db->query($sql);
4728 if ($resql) {
4729 $error = 0;
4730
4731 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4732
4733 if ($nb_rows_affected > 0) {
4734 if (empty($trigkey)) {
4735 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4736 if ($this->element == 'supplier_proposal' && $status == 2) {
4737 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4738 }
4739 if ($this->element == 'supplier_proposal' && $status == 3) {
4740 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4741 }
4742 if ($this->element == 'supplier_proposal' && $status == 4) {
4743 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4744 }
4745 if ($this->element == 'fichinter' && $status == 3) {
4746 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4747 }
4748 if ($this->element == 'fichinter' && $status == 2) {
4749 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4750 }
4751 if ($this->element == 'fichinter' && $status == 1) {
4752 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4753 }
4754 }
4755
4756 $this->context = array_merge($this->context, array('newstatus' => $status));
4757
4758 if ($trigkey) {
4759 // Call trigger
4760 $result = $this->call_trigger($trigkey, $user);
4761 if ($result < 0) {
4762 $error++;
4763 }
4764 // End call triggers
4765 }
4766 } else {
4767 // The status was probably already good. We do nothing more, no triggers.
4768 }
4769
4770 if (!$error) {
4771 $this->db->commit();
4772
4773 if (empty($savElementId)) {
4774 // If the element we update is $this (so $elementId was provided as null)
4775 if ($fieldstatus == 'tosell') {
4776 $this->status = $status;
4777 } elseif ($fieldstatus == 'tobuy') {
4778 $this->status_buy = $status; // @phpstan-ignore-line
4779 } else {
4780 $this->status = $status;
4781 }
4782 }
4783
4784 return 1;
4785 } else {
4786 $this->db->rollback();
4787 dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4788 return -1;
4789 }
4790 } else {
4791 $this->error = $this->db->lasterror();
4792 $this->db->rollback();
4793 return -1;
4794 }
4795 }
4796
4797
4805 public function getCanvas($id = 0, $ref = '')
4806 {
4807 global $conf;
4808
4809 if (empty($id) && empty($ref)) {
4810 return 0;
4811 }
4812 if (getDolGlobalString('MAIN_DISABLE_CANVAS')) {
4813 return 0; // To increase speed. Not enabled by default.
4814 }
4815
4816 // Clean parameters
4817 $ref = trim($ref);
4818
4819 $sql = "SELECT rowid, canvas";
4820 $sql .= " FROM ".$this->db->prefix().$this->table_element;
4821 $sql .= " WHERE entity IN (".getEntity($this->element).")";
4822 if (!empty($id)) {
4823 $sql .= " AND rowid = ".((int) $id);
4824 }
4825 if (!empty($ref)) {
4826 $sql .= " AND ref = '".$this->db->escape($ref)."'";
4827 }
4828
4829 $resql = $this->db->query($sql);
4830 if ($resql) {
4831 $obj = $this->db->fetch_object($resql);
4832 if ($obj) {
4833 $this->canvas = $obj->canvas;
4834 return 1;
4835 } else {
4836 return 0;
4837 }
4838 } else {
4839 dol_print_error($this->db);
4840 return -1;
4841 }
4842 }
4843
4844
4851 public function getSpecialCode($lineid)
4852 {
4853 $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4854 $sql .= " WHERE rowid = ".((int) $lineid);
4855 $resql = $this->db->query($sql);
4856 if ($resql) {
4857 $row = $this->db->fetch_row($resql);
4858 return (!empty($row[0]) ? $row[0] : 0);
4859 }
4860
4861 return 0;
4862 }
4863
4872 public function isObjectUsed($id = 0, $entity = 0)
4873 {
4874 global $langs;
4875
4876 if (empty($id)) {
4877 $id = $this->id;
4878 }
4879
4880 // Check parameters
4881 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4882 dol_print_error(null, 'Called isObjectUsed on a class with property this->childtables not defined');
4883 return -1;
4884 }
4885
4886 $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
4887 // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
4888 $tmparray = array_keys($this->childtables);
4889 if (is_numeric($tmparray[0])) {
4890 $arraytoscan = array_flip($this->childtables);
4891 }
4892
4893 // Test if child exists
4894 $haschild = 0;
4895 foreach ($arraytoscan as $table => $element) {
4896 //print $id.'-'.$table.'-'.$elementname.'<br>';
4897 // Check if element can be deleted
4898 $sql = "SELECT COUNT(*) as nb";
4899 $sql .= " FROM ".$this->db->prefix().$table." as c";
4900 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4901 $sql .= ", ".$this->db->prefix().$element['parent']." as p";
4902 }
4903 if (!empty($element['fk_element'])) {
4904 $sql .= " WHERE c.".$element['fk_element']." = ".((int) $id);
4905 } else {
4906 $sql .= " WHERE c.".$this->fk_element." = ".((int) $id);
4907 }
4908 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4909 $sql .= " AND c.".$element['parentkey']." = p.rowid";
4910 }
4911 if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
4912 $sql .= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'";
4913 }
4914 if (!empty($entity)) {
4915 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4916 $sql .= " AND p.entity = ".((int) $entity);
4917 } else {
4918 $sql .= " AND c.entity = ".((int) $entity);
4919 }
4920 }
4921
4922 $resql = $this->db->query($sql);
4923 if ($resql) {
4924 $obj = $this->db->fetch_object($resql);
4925 if ($obj->nb > 0) {
4926 $langs->load("errors");
4927 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4928 $haschild += $obj->nb;
4929 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4930 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4931 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4932 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4933 } else { // new usage: $element['name']=Translation key
4934 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4935 }
4936 break; // We found at least one, we stop here
4937 }
4938 } else {
4939 $this->errors[] = $this->db->lasterror();
4940 return -1;
4941 }
4942 }
4943 if ($haschild > 0) {
4944 $this->errors[] = "ErrorRecordHasChildren";
4945 return $haschild;
4946 } else {
4947 return 0;
4948 }
4949 }
4950
4957 public function hasProductsOrServices($predefined = -1)
4958 {
4959 $nb = 0;
4960
4961 foreach ($this->lines as $key => $val) {
4962 $qualified = 0;
4963 if ($predefined == -1) {
4964 $qualified = 1;
4965 }
4966 if ($predefined == 1 && $val->fk_product > 0) {
4967 $qualified = 1;
4968 }
4969 if ($predefined == 0 && $val->fk_product <= 0) {
4970 $qualified = 1;
4971 }
4972 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4973 $qualified = 1;
4974 }
4975 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4976 $qualified = 1;
4977 }
4978 if ($qualified) {
4979 $nb++;
4980 }
4981 }
4982 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4983 return $nb;
4984 }
4985
4991 public function getTotalDiscount()
4992 {
4993 if (!empty($this->table_element_line)) {
4994 $total_discount = 0.00;
4995
4996 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4997 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4998 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4999
5000 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
5001 $resql = $this->db->query($sql);
5002 if ($resql) {
5003 $num = $this->db->num_rows($resql);
5004 $i = 0;
5005 while ($i < $num) {
5006 $obj = $this->db->fetch_object($resql);
5007
5008 $pu_ht = $obj->pu_ht;
5009 $qty = $obj->qty;
5010 $total_ht = $obj->total_ht;
5011
5012 $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT');
5013 $total_discount += $total_discount_line;
5014
5015 $i++;
5016 }
5017 }
5018
5019 //print $total_discount; exit;
5020 return (float) price2num($total_discount);
5021 }
5022
5023 return null;
5024 }
5025
5026
5033 public function getTotalWeightVolume()
5034 {
5035 $totalWeight = 0;
5036 $totalVolume = 0;
5037 // defined for shipment only
5038 $totalOrdered = 0;
5039 // defined for shipment only
5040 $totalToShip = 0;
5041
5042 if (empty($this->lines)) {
5043 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5044 }
5045
5046 foreach ($this->lines as $line) {
5047 if (isset($line->qty_asked)) {
5048 $totalOrdered += $line->qty_asked; // defined for shipment only
5049 }
5050 if (isset($line->qty_shipped)) {
5051 $totalToShip += $line->qty_shipped; // defined for shipment only
5052 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
5053 if (empty($totalToShip)) {
5054 $totalToShip = 0;
5055 }
5056 $totalToShip += $line->qty; // defined for reception only
5057 }
5058
5059 // Define qty, weight, volume, weight_units, volume_units
5060 if ($this->element == 'shipping') {
5061 // for shipments
5062 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5063 } else {
5064 $qty = $line->qty ? $line->qty : 0;
5065 }
5066
5067 $weight = !empty($line->weight) ? $line->weight : 0;
5068 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5069 $volume = !empty($line->volume) ? $line->volume : 0;
5070 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5071
5072 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5073 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5074 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5075 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5076
5077 $weightUnit = 0;
5078 $volumeUnit = 0;
5079 if (!empty($weight_units)) {
5080 $weightUnit = $weight_units;
5081 }
5082 if (!empty($volume_units)) {
5083 $volumeUnit = $volume_units;
5084 }
5085
5086 if (empty($totalWeight)) {
5087 $totalWeight = 0; // Avoid warning because $totalWeight is ''
5088 }
5089 if (empty($totalVolume)) {
5090 $totalVolume = 0; // Avoid warning because $totalVolume is ''
5091 }
5092
5093 //var_dump($line->volume_units);
5094 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5095 $trueWeightUnit = pow(10, $weightUnit);
5096 $totalWeight += $weight * $qty * $trueWeightUnit;
5097 } else {
5098 if ($weight_units == 99) {
5099 // conversion 1 Pound = 0.45359237 KG
5100 $trueWeightUnit = 0.45359237;
5101 $totalWeight += $weight * $qty * $trueWeightUnit;
5102 } elseif ($weight_units == 98) {
5103 // conversion 1 Ounce = 0.0283495 KG
5104 $trueWeightUnit = 0.0283495;
5105 $totalWeight += $weight * $qty * $trueWeightUnit;
5106 } else {
5107 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
5108 }
5109 }
5110 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5111 //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
5112 $trueVolumeUnit = pow(10, $volumeUnit);
5113 //print $line->volume;
5114 $totalVolume += $volume * $qty * $trueVolumeUnit;
5115 } else {
5116 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
5117 }
5118 }
5119
5120 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5121 }
5122
5123
5129 public function setExtraParameters()
5130 {
5131 $this->db->begin();
5132
5133 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
5134
5135 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
5136 $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
5137 $sql .= " WHERE rowid = ".((int) $this->id);
5138
5139 dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
5140 $resql = $this->db->query($sql);
5141 if (!$resql) {
5142 $this->error = $this->db->lasterror();
5143 $this->db->rollback();
5144 return -1;
5145 } else {
5146 $this->db->commit();
5147 return 1;
5148 }
5149 }
5150
5151
5152 // --------------------
5153 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
5154 // --------------------
5155
5156 /* This is to show add lines */
5157
5167 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
5168 {
5169 global $conf, $user, $langs, $object, $hookmanager, $extrafields, $form;
5170
5171 // Line extrafield
5172 if (!is_object($extrafields)) {
5173 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5174 $extrafields = new ExtraFields($this->db);
5175 }
5176 $extrafields->fetch_name_optionals_label($this->table_element_line);
5177
5178 // Output template part (modules that overwrite templates must declare this into descriptor)
5179 // Use global variables + $dateSelector + $seller and $buyer
5180 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
5181 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5182 foreach ($dirtpls as $module => $reldir) {
5183 if (!empty($module)) {
5184 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
5185 } else {
5186 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
5187 }
5188
5189 if (empty($conf->file->strict_mode)) {
5190 $res = @include $tpl;
5191 } else {
5192 $res = include $tpl; // for debug
5193 }
5194 if ($res) {
5195 break;
5196 }
5197 }
5198 }
5199
5200
5201
5202 /* This is to show array of line of details */
5203
5204
5219 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
5220 {
5221 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
5222 // TODO We should not use global var for this
5223 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5224
5225 // Define $usemargins (used by objectline_xxx.tpl.php files)
5226 $usemargins = 0;
5227 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
5228 $usemargins = 1;
5229 }
5230
5231 $num = count($this->lines);
5232
5233 // Line extrafield
5234 if (!is_object($extrafields)) {
5235 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5236 $extrafields = new ExtraFields($this->db);
5237 }
5238 $extrafields->fetch_name_optionals_label($this->table_element_line);
5239
5240 if (method_exists($this, 'loadExpeditions')) {
5241 $this->loadExpeditions();
5242 }
5243
5244 $parameters = array('num' => $num, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
5245 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5246 if (empty($reshook)) {
5247 // Output template part (modules that overwrite templates must declare this into descriptor)
5248 // Use global variables + $dateSelector + $seller and $buyer
5249 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
5250 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5251 foreach ($dirtpls as $module => $reldir) {
5252 $res = 0;
5253 if (!empty($module)) {
5254 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
5255 } else {
5256 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
5257 }
5258 if (file_exists($tpl)) {
5259 if (empty($conf->file->strict_mode)) {
5260 $res = @include $tpl;
5261 } else {
5262 $res = include $tpl; // for debug
5263 }
5264 }
5265 if ($res) {
5266 break;
5267 }
5268 }
5269 }
5270
5271 $i = 0;
5272
5273 print "<!-- begin printObjectLines() -->\n";
5274 foreach ($this->lines as $line) {
5275 //Line extrafield
5276 $line->fetch_optionals();
5277
5278 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
5279 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5280 if (empty($line->fk_parent_line)) {
5281 $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element, 'defaulttpldir' => $defaulttpldir);
5282 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5283 } else {
5284 $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element, 'fk_parent_line' => $line->fk_parent_line, 'defaulttpldir' => $defaulttpldir);
5285 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5286 }
5287 }
5288 if (empty($reshook)) {
5289 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5290 }
5291
5292 $i++;
5293 }
5294 print "<!-- end printObjectLines() -->\n";
5295 }
5296
5314 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
5315 {
5316 global $conf, $langs, $user, $object, $hookmanager;
5317 global $form;
5318 global $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
5319
5320 // var used into tpl
5321 $text = '';
5322 $description = '';
5323
5324 // Line in view mode
5325 if ($action != 'editline' || $selected != $line->id) {
5326 // Product
5327 if (!empty($line->fk_product) && $line->fk_product > 0) {
5328 $product_static = new Product($this->db);
5329 $product_static->fetch($line->fk_product);
5330
5331 $product_static->ref = $line->ref; //can change ref in hook
5332 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5333
5334 $text = $product_static->getNomUrl(1);
5335
5336 // Define output language and label
5337 if (getDolGlobalInt('MAIN_MULTILANGS')) {
5338 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5339 dol_print_error(null, 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5340 return;
5341 }
5342
5343 $prod = new Product($this->db);
5344 $prod->fetch($line->fk_product);
5345
5346 $outputlangs = $langs;
5347 $newlang = '';
5348 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5349 $newlang = GETPOST('lang_id', 'aZ09');
5350 }
5351 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5352 $newlang = $this->thirdparty->default_lang; // To use language of customer
5353 }
5354 if (!empty($newlang)) {
5355 $outputlangs = new Translate("", $conf);
5356 $outputlangs->setDefaultLang($newlang);
5357 }
5358
5359 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5360 } else {
5361 $label = $line->product_label;
5362 }
5363
5364 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5365 $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.
5366 }
5367
5368 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5369
5370 // Output template part (modules that overwrite templates must declare this into descriptor)
5371 // Use global variables + $dateSelector + $seller and $buyer
5372 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5373
5374 $qty_shipped = 0;
5375 if (isset($this->expeditions[$line->id])) {
5376 $qty_shipped = $this->expeditions[$line->id];
5377 }
5378 $disableedit = $qty_shipped >= $line->qty;
5379
5380 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5381 foreach ($dirtpls as $module => $reldir) {
5382 $res = 0;
5383 if (!empty($module)) {
5384 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5385 } else {
5386 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5387 }
5388 //var_dump($tpl);
5389 if (file_exists($tpl)) {
5390 if (empty($conf->file->strict_mode)) {
5391 $res = @include $tpl;
5392 } else {
5393 $res = include $tpl; // for debug
5394 }
5395 }
5396 if ($res) {
5397 break;
5398 }
5399 }
5400 }
5401
5402 // Line in update mode
5403 if ($this->status == 0 && $action == 'editline' && $selected == $line->id) {
5404 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5405
5406 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5407
5408 // Output template part (modules that overwrite templates must declare this into descriptor)
5409 // Use global variables + $dateSelector + $seller and $buyer
5410 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5411 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5412 foreach ($dirtpls as $module => $reldir) {
5413 if (!empty($module)) {
5414 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5415 } else {
5416 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5417 }
5418
5419 if (empty($conf->file->strict_mode)) {
5420 $res = @include $tpl;
5421 } else {
5422 $res = include $tpl; // for debug
5423 }
5424 if ($res) {
5425 break;
5426 }
5427 }
5428 }
5429 }
5430
5431
5432 /* This is to show array of line of details of source object */
5433
5434
5445 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5446 {
5447 global $langs, $hookmanager, $form, $action;
5448
5449 print '<tr class="liste_titre">';
5450 print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5451 print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5452 print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5453 print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5454 if (isModEnabled("multicurrency")) {
5455 print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5456 }
5457 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5458 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5459 print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5460 }
5461 print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5462 print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5463 print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5464 print '</tr>';
5465 $i = 0;
5466
5467 if (!empty($this->lines)) {
5468 foreach ($this->lines as $line) {
5469 $reshook = 0;
5470 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5471 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5472 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
5473 if (!empty($line->fk_parent_line)) {
5474 $parameters['fk_parent_line'] = $line->fk_parent_line;
5475 }
5476 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5477 }
5478 if (empty($reshook)) {
5479 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5480 }
5481
5482 $i++;
5483 }
5484 }
5485 }
5486
5500 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5501 {
5502 global $langs, $conf;
5503
5504 //var_dump($line);
5505 if (!empty($line->date_start)) {
5506 // @phan-suppress-next-line PhanUndeclaredProperty
5507 $date_start = $line->date_start;
5508 } else {
5509 $date_start = $line->date_debut_prevue;
5510 if ($line->date_debut_reel) {
5511 $date_start = $line->date_debut_reel;
5512 }
5513 }
5514 if (!empty($line->date_end)) {
5515 // @phan-suppress-next-line PhanUndeclaredProperty
5516 $date_end = $line->date_end;
5517 } else {
5518 $date_end = $line->date_fin_prevue;
5519 if ($line->date_fin_reel) {
5520 $date_end = $line->date_fin_reel;
5521 }
5522 }
5523
5524 $this->tpl['id'] = $line->id;
5525
5526 $this->tpl['label'] = '';
5527 if (!empty($line->fk_parent_line)) {
5528 $this->tpl['label'] .= img_picto('', 'rightarrow');
5529 }
5530
5531 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5532 $discount = new DiscountAbsolute($this->db);
5533 if (property_exists($this, 'socid')) {
5534 $discount->fk_soc = $this->socid;
5535 $discount->socid = $this->socid;
5536 }
5537 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5538 } elseif (!empty($line->fk_product)) {
5539 $productstatic = new Product($this->db);
5540 $productstatic->id = $line->fk_product;
5541 $productstatic->ref = $line->ref;
5542 $productstatic->type = $line->fk_product_type;
5543 if (empty($productstatic->ref)) {
5544 $line->fetch_product();
5545 $productstatic = $line->product;
5546 }
5547
5548 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5549 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5550 // Dates
5551 if ($line->product_type == 1 && ($date_start || $date_end)) {
5552 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5553 }
5554 } else {
5555 $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5556 if (!empty($line->desc)) {
5557 $this->tpl['label'] .= $line->desc;
5558 } else {
5559 $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5560 }
5561
5562 // Dates
5563 if ($line->product_type == 1 && ($date_start || $date_end)) {
5564 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5565 }
5566 }
5567
5568 if (!empty($line->desc)) {
5569 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5570 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5571 $discount = new DiscountAbsolute($this->db);
5572 $discount->fetch($line->fk_remise_except);
5573 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5574 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5575 $discount = new DiscountAbsolute($this->db);
5576 $discount->fetch($line->fk_remise_except);
5577 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5578 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5579 $discount = new DiscountAbsolute($this->db);
5580 $discount->fetch($line->fk_remise_except);
5581 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5582 } elseif ($line->desc == '(EXCESS PAID)') {
5583 $discount = new DiscountAbsolute($this->db);
5584 $discount->fetch($line->fk_remise_except);
5585 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5586 } else {
5587 $this->tpl['description'] = dol_trunc($line->desc, 60);
5588 }
5589 } else {
5590 $this->tpl['description'] = '&nbsp;';
5591 }
5592
5593 // VAT Rate
5594 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5595 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5596 if (!empty($line->vat_src_code) && !preg_match('/\‍(/', $this->tpl['vat_rate'])) {
5597 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5598 }
5599
5600 $this->tpl['price'] = price($line->subprice);
5601 $this->tpl['total_ht'] = price($line->total_ht);
5602 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5603 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5604 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5605 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5606 }
5607 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate((string) $line->remise_percent, true) : '&nbsp;';
5608
5609 // Is the line strike or not
5610 $this->tpl['strike'] = 0;
5611 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5612 $this->tpl['strike'] = 1;
5613 }
5614
5615 // Output template part (modules that overwrite templates must declare this into descriptor)
5616 // Use global variables + $dateSelector + $seller and $buyer
5617 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5618 foreach ($dirtpls as $module => $reldir) {
5619 if (!empty($module)) {
5620 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5621 } else {
5622 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5623 }
5624
5625 if (empty($conf->file->strict_mode)) {
5626 $res = @include $tpl;
5627 } else {
5628 $res = include $tpl; // for debug
5629 }
5630 if ($res) {
5631 break;
5632 }
5633 }
5634 }
5635
5636
5637 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5648 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5649 {
5650 // phpcs:enable
5651 $this->db->begin();
5652
5653 $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5654 $sql .= "resource_id";
5655 $sql .= ", resource_type";
5656 $sql .= ", element_id";
5657 $sql .= ", element_type";
5658 $sql .= ", busy";
5659 $sql .= ", mandatory";
5660 $sql .= ") VALUES (";
5661 $sql .= ((int) $resource_id);
5662 $sql .= ", '".$this->db->escape($resource_type)."'";
5663 $sql .= ", '".$this->db->escape($this->id)."'";
5664 $sql .= ", '".$this->db->escape($this->element)."'";
5665 $sql .= ", '".$this->db->escape($busy)."'";
5666 $sql .= ", '".$this->db->escape($mandatory)."'";
5667 $sql .= ")";
5668
5669 dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5670 if ($this->db->query($sql)) {
5671 $this->db->commit();
5672 return 1;
5673 } else {
5674 $this->error = $this->db->lasterror();
5675 $this->db->rollback();
5676 return 0;
5677 }
5678 }
5679
5680 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5689 public function delete_resource($rowid, $element, $notrigger = 0)
5690 {
5691 // phpcs:enable
5692 global $user;
5693
5694 $this->db->begin();
5695
5696 $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5697 $sql .= " WHERE rowid = ".((int) $rowid);
5698
5699 dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5700
5701 $resql = $this->db->query($sql);
5702 if (!$resql) {
5703 $this->error = $this->db->lasterror();
5704 $this->db->rollback();
5705 return -1;
5706 } else {
5707 if (!$notrigger) {
5708 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5709 if ($result < 0) {
5710 $this->db->rollback();
5711 return -1;
5712 }
5713 }
5714 $this->db->commit();
5715 return 1;
5716 }
5717 }
5718
5719
5725 public function __clone()
5726 {
5727 // Force a copy of this->lines, otherwise it will point to same object.
5728 if (isset($this->lines) && is_array($this->lines)) {
5729 $nboflines = count($this->lines);
5730 for ($i = 0; $i < $nboflines; $i++) {
5731 if (is_object($this->lines[$i])) {
5732 $this->lines[$i] = clone $this->lines[$i];
5733 }
5734 }
5735 }
5736 }
5737
5751 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5752 {
5753 global $conf, $langs, $user, $hookmanager, $action;
5754
5755 $srctemplatepath = '';
5756
5757 $parameters = array('modelspath' => $modelspath, 'modele' => $modele, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'hidedesc' => $hidedesc, 'hideref' => $hideref, 'moreparams' => $moreparams);
5758 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5759
5760 if (!empty($reshook)) {
5761 return $reshook;
5762 }
5763
5764 dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5765
5766 if (empty($modele)) {
5767 $this->error = 'BadValueForParameterModele';
5768 return -1;
5769 }
5770
5771 // Increase limit for PDF build
5772 $err = error_reporting();
5773 error_reporting(0);
5774 @set_time_limit(120);
5775 error_reporting($err);
5776
5777 // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5778 $tmp = explode(':', $modele, 2);
5779 $saved_model = $modele;
5780 if (!empty($tmp[1])) {
5781 $modele = $tmp[0];
5782 $srctemplatepath = $tmp[1];
5783 }
5784
5785 // Search template files
5786 $file = '';
5787 $classname = '';
5788 $filefound = '';
5789 $dirmodels = array('/');
5790 if (is_array($conf->modules_parts['models'])) {
5791 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5792 }
5793 foreach ($dirmodels as $reldir) {
5794 foreach (array('doc', 'pdf') as $prefix) {
5795 if (in_array(get_class($this), array('Adherent'))) {
5796 // Member module use prefix_modele.class.php
5797 $file = $prefix."_".$modele.".class.php";
5798 } else {
5799 // Other module use prefix_modele.modules.php
5800 $file = $prefix."_".$modele.".modules.php";
5801 }
5802
5803 $file = dol_sanitizeFileName($file);
5804
5805 // We check if the file exists
5806 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5807 if (file_exists($file)) {
5808 $filefound = $file;
5809 $classname = $prefix.'_'.$modele;
5810 break;
5811 }
5812 }
5813 if ($filefound) {
5814 break;
5815 }
5816 }
5817
5818 if ($filefound === '' || $classname === '') {
5819 $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5820 $this->errors[] = $this->error;
5821 dol_syslog($this->error, LOG_ERR);
5822 return -1;
5823 }
5824
5825 // Sanitize $filefound
5826 $filefound = dol_sanitizePathName($filefound);
5827
5828 // If generator was found
5829 global $db; // Required to solve a conception error making an include of some code that uses $db instead of $this->db just after.
5830
5831 require_once $filefound;
5832
5833 $obj = new $classname($this->db);
5834
5835 // TODO: Check the following classes that seem possible for $obj, but removed for compatibility:
5836 // ModeleBankAccountDoc|ModeleExpenseReport|ModelePDFBom|ModelePDFCommandes|ModelePDFContract|
5837 // ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|
5838 // ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|
5839 // ModelePDFRecruitmentJobPosition|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|
5840 // ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePdfExpedition|ModelePdfReception|
5841 // ModelePDFStock|ModelePDFStockTransfer|
5842 // ModeleDon|ModelePDFTask|
5843 // ModelePDFAsset|ModelePDFTicket|ModelePDFUserGroup|ModeleThirdPartyDoc|ModelePDFUser
5844 // Has no write_file: ModeleBarCode|ModeleImports|ModeleExports|
5845 '@phan-var-force ModelePDFMember $obj';
5846 // '@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';
5847
5848 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5849 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5850 $varfortemplatedir = $obj->scandir;
5851 if ($varfortemplatedir && getDolGlobalString($varfortemplatedir)) {
5852 $dirtoscan = getDolGlobalString($varfortemplatedir);
5853
5854 $listoffiles = array();
5855
5856 // Now we add first model found in directories scanned
5857 $listofdir = explode(',', $dirtoscan);
5858 foreach ($listofdir as $key => $tmpdir) {
5859 $tmpdir = trim($tmpdir);
5860 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5861 if (!$tmpdir) {
5862 unset($listofdir[$key]);
5863 continue;
5864 }
5865 if (is_dir($tmpdir)) {
5866 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5867 if (count($tmpfiles)) {
5868 $listoffiles = array_merge($listoffiles, $tmpfiles);
5869 }
5870 }
5871 }
5872
5873 if (count($listoffiles)) {
5874 foreach ($listoffiles as $record) {
5875 $srctemplatepath = $record['fullname'];
5876 break;
5877 }
5878 }
5879 }
5880
5881 if (empty($srctemplatepath)) {
5882 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5883 return -1;
5884 }
5885 }
5886
5887 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5888 if (!dol_is_file($srctemplatepath)) {
5889 dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5890 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5891 return -1;
5892 }
5893 }
5894
5895 // We save charset_output to restore it because write_file can change it if needed for
5896 // output format that does not support UTF8.
5897 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5898
5899 // update model_pdf in object
5900 $this->model_pdf = $saved_model;
5901
5902 if ($obj instanceof ModelePDFMember) {
5903 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards');
5904 } else {
5905 // TODO: Try to set type above again
5906 '@phan-var-force 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';
5907 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5908 }
5909 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5910
5911 if ($resultwritefile > 0) {
5912 $outputlangs->charset_output = $sav_charset_output;
5913
5914 // We delete old preview
5915 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5916 dol_delete_preview($this);
5917
5918 // Index file in database
5919 if (!empty($obj->result['fullpath'])) {
5920 $destfull = $obj->result['fullpath'];
5921
5922 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5923 $update_main_doc_field = 0;
5924 if (!empty($obj->update_main_doc_field)) {
5925 $update_main_doc_field = 1;
5926 }
5927
5928 // Check that the file exists, before indexing it.
5929 // Hint: It does not exist, if we create a PDF and auto delete the ODT File
5930 if (dol_is_file($destfull)) {
5931 $this->indexFile($destfull, $update_main_doc_field);
5932 }
5933 } else {
5934 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);
5935 }
5936
5937 // Success in building document. We build meta file.
5938 dol_meta_create($this);
5939
5940 return 1;
5941 } else {
5942 $outputlangs->charset_output = $sav_charset_output;
5943 $this->error = $obj->error;
5944 $this->errors = $obj->errors;
5945 dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5946 return -1;
5947 }
5948 }
5949
5959 public function indexFile($destfull, $update_main_doc_field)
5960 {
5961 global $conf, $user;
5962
5963 $upload_dir = dirname($destfull);
5964 $destfile = basename($destfull);
5965 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5966
5967 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5968 $filename = basename($destfile);
5969 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5970 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5971
5972 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5973 $ecmfile = new EcmFiles($this->db);
5974 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5975
5976 // Set the public "share" key
5977 $setsharekey = false;
5978 if ($this->element == 'propal' || $this->element == 'proposal') {
5979 if (getDolGlobalInt("PROPOSAL_ALLOW_ONLINESIGN")) {
5980 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5981 }
5982 if (getDolGlobalInt("PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
5983 $setsharekey = true;
5984 }
5985 }
5986 if ($this->element == 'commande' && getDolGlobalInt("ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
5987 $setsharekey = true;
5988 }
5989 if ($this->element == 'facture' && getDolGlobalInt("INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
5990 $setsharekey = true;
5991 }
5992 if ($this->element == 'bank_account' && getDolGlobalInt("BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
5993 $setsharekey = true;
5994 }
5995 if ($this->element == 'product' && getDolGlobalInt("PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
5996 $setsharekey = true;
5997 }
5998 if ($this->element == 'contrat' && getDolGlobalInt("CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
5999 $setsharekey = true;
6000 }
6001 if ($this->element == 'fichinter' && getDolGlobalInt("FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
6002 $setsharekey = true;
6003 }
6004 if ($this->element == 'supplier_proposal' && getDolGlobalInt("SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
6005 $setsharekey = true;
6006 }
6007 if ($this->element == 'societe_rib' && getDolGlobalInt("SOCIETE_RIB_ALLOW_ONLINESIGN")) {
6008 $setsharekey = true;
6009 }
6010
6011 if ($setsharekey) {
6012 if (empty($ecmfile->share)) { // Because object not found or share not set yet
6013 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
6014 $ecmfile->share = getRandomPassword(true);
6015 }
6016 }
6017
6018 if ($result > 0) {
6019 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
6020 $ecmfile->fullpath_orig = '';
6021 $ecmfile->gen_or_uploaded = 'generated';
6022 $ecmfile->description = ''; // indexed content
6023 $ecmfile->keywords = ''; // keyword content
6024 $ecmfile->src_object_type = $this->table_element;
6025 $ecmfile->src_object_id = $this->id;
6026 $result = $ecmfile->update($user);
6027 if ($result < 0) {
6028 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
6029 return -1;
6030 }
6031 } else {
6032 $ecmfile->entity = $conf->entity;
6033 $ecmfile->filepath = $rel_dir;
6034 $ecmfile->filename = $filename;
6035 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
6036 $ecmfile->fullpath_orig = '';
6037 $ecmfile->gen_or_uploaded = 'generated';
6038 $ecmfile->description = ''; // indexed content
6039 $ecmfile->keywords = ''; // keyword content
6040 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
6041 $ecmfile->src_object_id = $this->id;
6042
6043 $result = $ecmfile->create($user);
6044 if ($result < 0) {
6045 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
6046 return -1;
6047 }
6048 }
6049
6050 /*$this->result['fullname']=$destfull;
6051 $this->result['filepath']=$ecmfile->filepath;
6052 $this->result['filename']=$ecmfile->filename;*/
6053 //var_dump($obj->update_main_doc_field);exit;
6054
6055 if ($update_main_doc_field && !empty($this->table_element)) {
6056 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
6057 $sql .= " WHERE rowid = ".((int) $this->id);
6058
6059 $resql = $this->db->query($sql);
6060 if (!$resql) {
6061 dol_print_error($this->db);
6062 return -1;
6063 } else {
6064 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
6065 }
6066 }
6067 }
6068
6069 return 1;
6070 }
6071
6079 public function addThumbs($file)
6080 {
6081 $file_osencoded = dol_osencode($file);
6082
6083 if (file_exists($file_osencoded)) {
6084 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6085
6086 $tmparraysize = getDefaultImageSizes();
6087 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
6088 $maxheightsmall = $tmparraysize['maxheightsmall'];
6089 $maxwidthmini = $tmparraysize['maxwidthmini'];
6090 $maxheightmini = $tmparraysize['maxheightmini'];
6091 //$quality = $tmparraysize['quality'];
6092 $quality = 50; // For thumbs, we force quality to 50
6093
6094 // Create small thumbs for company (Ratio is near 16/9)
6095 // Used on logon for example
6096 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
6097
6098 // Create mini thumbs for company (Ratio is near 16/9)
6099 // Used on menu or for setup page for example
6100 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
6101 }
6102 }
6103
6111 public function delThumbs($file)
6112 {
6113 $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
6114 dol_delete_file($imgThumbName);
6115 $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
6116 dol_delete_file($imgThumbName);
6117 }
6118
6119
6120 /* Functions common to commonobject and commonobjectline */
6121
6122 /* For default values */
6123
6137 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
6138 {
6139 // If param here has been posted, we use this value first.
6140 if (GETPOSTISSET($fieldname)) {
6141 return GETPOST($fieldname, $type, 3);
6142 }
6143
6144 if (isset($alternatevalue)) {
6145 return $alternatevalue;
6146 }
6147
6148 $newelement = $this->element;
6149 if ($newelement == 'facture') {
6150 $newelement = 'invoice';
6151 }
6152 if ($newelement == 'commande') {
6153 $newelement = 'order';
6154 }
6155 if (empty($newelement)) {
6156 dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6157 return '';
6158 }
6159
6160 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
6161 //var_dump($keyforfieldname);
6162 if (getDolGlobalString($keyforfieldname)) {
6163 return getDolGlobalString($keyforfieldname);
6164 }
6165
6166 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
6167 // store content into $conf->cache['overwrite_default']
6168
6169 return '';
6170 }
6171
6172
6173 /* For triggers */
6174
6175
6176 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6187 public function call_trigger($triggerName, $user)
6188 {
6189 // phpcs:enable
6190 global $langs, $conf;
6191
6192 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
6193 dol_print_error(null, 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
6194 exit;
6195 }
6196 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers().
6197 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
6198 $langs = new Translate('', $conf);
6199 }
6200
6201 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
6202 $interface = new Interfaces($this->db);
6203 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
6204
6205 if ($result < 0) {
6206 if (!empty($this->errors)) {
6207 $this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
6208 } else {
6209 $this->errors = $interface->errors;
6210 }
6211 }
6212 return $result;
6213 }
6214
6215
6216 /* Functions for data in other language */
6217
6218
6227 {
6228 // To avoid SQL errors. Probably not the better solution though
6229 if (!$this->element) {
6230 return 0;
6231 }
6232 if (!($this->id > 0)) {
6233 return 0;
6234 }
6235 if (is_array($this->array_languages)) {
6236 return 1;
6237 }
6238
6239 $this->array_languages = array();
6240
6241 $element = $this->element;
6242 if ($element == 'categorie') {
6243 $element = 'categories'; // For compatibility
6244 }
6245
6246 // Request to get translation values for object
6247 $sql = "SELECT rowid, property, lang , value";
6248 $sql .= " FROM ".$this->db->prefix()."object_lang";
6249 $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
6250 $sql .= " AND fk_object = ".((int) $this->id);
6251
6252 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6253 $resql = $this->db->query($sql);
6254 if ($resql) {
6255 $numrows = $this->db->num_rows($resql);
6256 if ($numrows) {
6257 $i = 0;
6258 while ($i < $numrows) {
6259 $obj = $this->db->fetch_object($resql);
6260 $key = $obj->property;
6261 $value = $obj->value;
6262 $codelang = $obj->lang;
6263 $type = $this->fields[$key]['type'];
6264
6265 // we can add this attribute to object
6266 if (preg_match('/date/', $type)) {
6267 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6268 } else {
6269 $this->array_languages[$key][$codelang] = $value;
6270 }
6271
6272 $i++;
6273 }
6274 }
6275
6276 $this->db->free($resql);
6277
6278 if ($numrows) {
6279 return $numrows;
6280 } else {
6281 return 0;
6282 }
6283 } else {
6284 dol_print_error($this->db);
6285 return -1;
6286 }
6287 }
6288
6295 public function setValuesForExtraLanguages($onlykey = '')
6296 {
6297 // Get extra fields
6298 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6299 $tmparray = explode('-', $postfieldkey);
6300 if ($tmparray[0] != 'field') {
6301 continue;
6302 }
6303
6304 $element = $tmparray[1];
6305 $key = $tmparray[2];
6306 $codelang = $tmparray[3];
6307 //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
6308
6309 if (!empty($onlykey) && $key != $onlykey) {
6310 continue;
6311 }
6312 if ($element != $this->element) {
6313 continue;
6314 }
6315
6316 $key_type = $this->fields[$key]['type'];
6317
6318 $enabled = 1;
6319 if (isset($this->fields[$key]['enabled'])) {
6320 $enabled = (int) dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
6321 }
6322 /*$perms = 1;
6323 if (isset($this->fields[$key]['perms']))
6324 {
6325 $perms = (int) dol_eval($this->fields[$key]['perms'], 1, 1, '1');
6326 }*/
6327 if (empty($enabled)) {
6328 continue;
6329 }
6330 //if (empty($perms)) continue;
6331
6332 if (in_array($key_type, array('date'))) {
6333 // Clean parameters
6334 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6335 $value_key = dol_mktime(0, 0, 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6336 } elseif (in_array($key_type, array('datetime'))) {
6337 // Clean parameters
6338 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6339 $value_key = dol_mktime(GETPOSTINT($postfieldkey."hour"), GETPOSTINT($postfieldkey."min"), 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6340 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
6341 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
6342 if (!empty($value_arr)) {
6343 $value_key = implode(',', $value_arr);
6344 } else {
6345 $value_key = '';
6346 }
6347 } elseif (in_array($key_type, array('price', 'double'))) {
6348 $value_arr = GETPOST($postfieldkey, 'alpha');
6349 $value_key = price2num($value_arr);
6350 } else {
6351 $value_key = GETPOST($postfieldkey);
6352 if (in_array($key_type, array('link')) && $value_key == '-1') {
6353 $value_key = '';
6354 }
6355 }
6356
6357 $this->array_languages[$key][$codelang] = $value_key;
6358
6359 /*if ($nofillrequired) {
6360 $langs->load('errors');
6361 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
6362 return -1;
6363 }*/
6364 }
6365
6366 return 1;
6367 }
6368
6369
6370 /* Functions for extrafields */
6371
6378 public function fetchNoCompute($id)
6379 {
6380 global $conf;
6381
6382 $savDisableCompute = $conf->disable_compute;
6383 $conf->disable_compute = 1;
6384
6385 $ret = $this->fetch($id); /* @phpstan-ignore-line */
6386
6387 $conf->disable_compute = $savDisableCompute;
6388
6389 return $ret;
6390 }
6391
6392 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6402 public function fetch_optionals($rowid = null, $optionsArray = null)
6403 {
6404 // phpcs:enable
6405 global $conf, $extrafields;
6406
6407 if (empty($rowid)) {
6408 $rowid = $this->id;
6409 }
6410 if (empty($rowid) && isset($this->rowid)) { // @phan-suppress-current-line PhanUndeclaredProperty
6411 $rowid = $this->rowid; // deprecated @phan-suppress-current-line PhanUndeclaredProperty
6412 }
6413
6414 // To avoid SQL errors. Probably not the better solution though
6415 if (!$this->table_element) {
6416 return 0;
6417 }
6418
6419 $this->array_options = array();
6420
6421 if (!is_array($optionsArray)) {
6422 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6423 if (!isset($extrafields) || !is_object($extrafields)) {
6424 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6425 $extrafields = new ExtraFields($this->db);
6426 }
6427
6428 // Load array of extrafields for elementype = $this->table_element
6429 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6430 $extrafields->fetch_name_optionals_label($this->table_element);
6431 }
6432 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6433 } else {
6434 global $extrafields;
6435 dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6436 }
6437
6438 $table_element = $this->table_element;
6439 if ($table_element == 'categorie') {
6440 $table_element = 'categories'; // For compatibility
6441 }
6442
6443 // Request to get complementary values
6444 if (is_array($optionsArray) && count($optionsArray) > 0) {
6445 $sql = "SELECT rowid";
6446 foreach ($optionsArray as $name => $label) {
6447 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || (!in_array($extrafields->attributes[$this->table_element]['type'][$name], ['separate', 'point', 'multipts', 'linestrg','polygon']))) {
6448 $sql .= ", ".$name;
6449 }
6450 // use geo sql fonction to read as text
6451 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'point') {
6452 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6453 }
6454 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'multipts') {
6455 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6456 }
6457 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'linestrg') {
6458 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6459 }
6460 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'polygon') {
6461 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6462 }
6463 }
6464 $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6465 $sql .= " WHERE fk_object = ".((int) $rowid);
6466
6467 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6468 $resql = $this->db->query($sql);
6469 if ($resql) {
6470 $numrows = $this->db->num_rows($resql);
6471 if ($numrows) {
6472 $tab = $this->db->fetch_array($resql);
6473
6474 foreach ($tab as $key => $value) {
6475 // 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)
6476 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6477 // we can add this attribute to object
6478 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6479 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6480 $this->array_options["options_".$key] = $this->db->jdate($value);
6481 } else {
6482 $this->array_options["options_".$key] = $value;
6483 }
6484
6485 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6486 }
6487 if (!empty($extrafields->attributes[$this->table_element]['type'][$key]) && $extrafields->attributes[$this->table_element]['type'][$key] == 'password') {
6488 if (!empty($value) && preg_match('/^dolcrypt:/', $value)) {
6489 $this->array_options["options_".$key] = dolDecrypt($value);
6490 }
6491 }
6492 }
6493 } else {
6498 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6499 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6500 $this->array_options['options_' . $key] = null;
6501 }
6502 }
6503 }
6504
6505 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6506 // in the element's extrafields table)
6507 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6508 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6509 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6510 //var_dump($conf->disable_compute);
6511 if (empty($conf->disable_compute)) {
6512 global $objectoffield; // We set a global variable to $objectoffield so
6513 $objectoffield = $this; // we can use it inside computed formula
6514 $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
6515 }
6516 }
6517 }
6518 }
6519
6520 $this->db->free($resql);
6521
6522 if ($numrows) {
6523 return $numrows;
6524 } else {
6525 return 0;
6526 }
6527 } else {
6528 $this->errors[] = $this->db->lasterror;
6529 return -1;
6530 }
6531 }
6532 return 0;
6533 }
6534
6541 public function deleteExtraFields()
6542 {
6543 global $conf;
6544
6545 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6546 return 0;
6547 }
6548
6549 $this->db->begin();
6550
6551 $table_element = $this->table_element;
6552 if ($table_element == 'categorie') {
6553 $table_element = 'categories'; // For compatibility
6554 }
6555
6556 dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6557
6558 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6559
6560 $resql = $this->db->query($sql_del);
6561 if (!$resql) {
6562 $this->error = $this->db->lasterror();
6563 $this->db->rollback();
6564 return -1;
6565 } else {
6566 $this->db->commit();
6567 return 1;
6568 }
6569 }
6570
6581 public function insertExtraFields($trigger = '', $userused = null)
6582 {
6583 global $conf, $langs, $user;
6584
6585 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6586 return 0;
6587 }
6588
6589 if (empty($userused)) {
6590 $userused = $user;
6591 }
6592
6593 $error = 0;
6594
6595 if (!empty($this->array_options)) {
6596 // Check parameters
6597 $langs->load('admin');
6598 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6599 $extrafields = new ExtraFields($this->db);
6600 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6601
6602 // Eliminate copied source object extra fields that do not exist in target object
6603 $new_array_options = array();
6604 foreach ($this->array_options as $key => $value) {
6605 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6606 $new_array_options[$key] = $value;
6607 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
6608 $new_array_options['options_'.$key] = $value;
6609 }
6610 }
6611
6612 foreach ($new_array_options as $key => $value) {
6613 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6614 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6615 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element]['label'][$attributeKey]);
6616 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6617 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6618 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6619 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6620
6621 // If we clone, we have to clean unique extrafields to prevent duplicates.
6622 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6623 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6624 $new_array_options[$key] = null;
6625 }
6626
6627 // Similar code than into insertExtraFields
6628 if ($attributeRequired) {
6629 $v = $this->array_options[$key];
6630 if (ExtraFields::isEmptyValue($v, $attributeType)) {
6631 $langs->load("errors");
6632 dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6633 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6634 return -1;
6635 }
6636 }
6637
6638 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6639 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6640
6641 if (!empty($attrfieldcomputed)) {
6642 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
6643 $value = dol_eval($attrfieldcomputed, 1, 0, '2');
6644 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
6645 $new_array_options[$key] = $value;
6646 } else {
6647 $new_array_options[$key] = null;
6648 }
6649 }
6650
6651 switch ($attributeType) {
6652 case 'int':
6653 if (!is_numeric($value) && $value != '') {
6654 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6655 return -1;
6656 } elseif ($value == '') {
6657 $new_array_options[$key] = null;
6658 }
6659 break;
6660 case 'price':
6661 case 'double':
6662 $value = price2num($value);
6663 if (!is_numeric($value) && $value != '') {
6664 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6665 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6666 return -1;
6667 } elseif ($value == '') {
6668 $value = null;
6669 }
6670 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6671 $new_array_options[$key] = $value;
6672 break;
6673 /*case 'select': // Not required, we chose value='0' for undefined values
6674 if ($value=='-1')
6675 {
6676 $this->array_options[$key] = null;
6677 }
6678 break;*/
6679 case 'password':
6680 $algo = '';
6681 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6682 // If there is an encryption choice, we use it to encrypt data before insert
6683 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6684 $algo = reset($tmparrays);
6685 if ($algo != '') {
6686 //global $action; // $action may be 'create', 'update', 'update_extras'...
6687 //var_dump($action);
6688 //var_dump($this->oldcopy);exit;
6689 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
6690 //var_dump('algo='.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
6691 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6692 // If old value encrypted in database is same than submitted new value, it means we don't change it, so we don't update.
6693 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
6694 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
6695 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6696 } else {
6697 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6698 }
6699 } else {
6700 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6701 }
6702 } else {
6703 // If value has changed
6704 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
6705 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
6706 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6707 } else {
6708 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6709 }
6710 } else {
6711 $new_array_options[$key] = dol_hash($this->array_options[$key], $algo);
6712 }
6713 }
6714 } else {
6715 //var_dump('jjj'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
6716 // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
6717 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options[$key])) { // dolibarr reversible encryption
6718 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6719 } else {
6720 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6721 }
6722 }
6723 } else {
6724 // No encryption
6725 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6726 }
6727 } else { // Common usage
6728 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6729 }
6730 break;
6731 case 'date':
6732 case 'datetime':
6733 // If data is a string instead of a timestamp, we convert it
6734 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6735 $this->array_options[$key] = strtotime($this->array_options[$key]);
6736 }
6737 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6738 break;
6739 case 'datetimegmt':
6740 // If data is a string instead of a timestamp, we convert it
6741 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6742 $this->array_options[$key] = strtotime($this->array_options[$key]);
6743 }
6744 $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
6745 break;
6746 case 'link':
6747 $param_list = array_keys($attributeParam['options']);
6748 // 0 : ObjectName
6749 // 1 : classPath
6750 $InfoFieldList = explode(":", $param_list[0]);
6751 dol_include_once($InfoFieldList[1]);
6752 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6753 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6754 $new_array_options[$key] = '';
6755 } elseif ($value) {
6756 $object = new $InfoFieldList[0]($this->db);
6757 '@phan-var-force CommonObject $object';
6758 if (is_numeric($value)) {
6759 $res = $object->fetch($value); // Common case
6760 } else {
6761 $res = $object->fetch(0, $value); // For compatibility
6762 }
6763
6764 if ($res > 0) {
6765 $new_array_options[$key] = $object->id;
6766 } else {
6767 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6768 return -1;
6769 }
6770 }
6771 } else {
6772 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6773 }
6774 break;
6775 case 'checkbox':
6776 case 'chkbxlst':
6777 if (is_array($this->array_options[$key])) {
6778 $new_array_options[$key] = implode(',', $this->array_options[$key]);
6779 } else {
6780 $new_array_options[$key] = $this->array_options[$key];
6781 }
6782 break;
6783 }
6784 }
6785
6786 $this->db->begin();
6787
6788 $table_element = $this->table_element;
6789 if ($table_element == 'categorie') {
6790 $table_element = 'categories'; // For compatibility
6791 }
6792
6793 dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6794
6795 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6796 $this->db->query($sql_del);
6797
6798 $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6799 foreach ($new_array_options as $key => $value) {
6800 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6801 // Add field of attribute
6802 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6803 $sql .= ",".$attributeKey;
6804 }
6805 }
6806 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6807 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6808 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6809 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6810 $sql .= ",".$tmpkey;
6811 }
6812 }
6813 }
6814 $sql .= ") VALUES (".$this->id;
6815
6816 foreach ($new_array_options as $key => $value) {
6817 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6818 // Add field of attribute
6819 if (!in_array($extrafields->attributes[$this->table_element]['type'][$attributeKey], ['separate', 'point', 'multipts', 'linestrg', 'polygon'])) { // Only for other type than separator)
6820 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6821 $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6822 } else {
6823 $sql .= ",null";
6824 }
6825 }
6826 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'point') { // for point type
6827 if (!empty($new_array_options[$key])) {
6828 $sql .= ",ST_PointFromText('".$this->db->escape($new_array_options[$key])."')";
6829 } else {
6830 $sql .= ",null";
6831 }
6832 }
6833 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'multipts') { // for point type
6834 if (!empty($new_array_options[$key])) {
6835 $sql .= ",ST_MultiPointFromText('".$this->db->escape($new_array_options[$key])."')";
6836 } else {
6837 $sql .= ",null";
6838 }
6839 }
6840 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'linestrg') { // for linestring type
6841 if (!empty($new_array_options[$key])) {
6842 $sql .= ",ST_LineFromText('".$this->db->escape($new_array_options[$key])."')";
6843 } else {
6844 $sql .= ",null";
6845 }
6846 }
6847 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'polygon') { // for polygon type
6848 if (!empty($new_array_options[$key])) {
6849 $sql .= ",ST_PolyFromText('".$this->db->escape($new_array_options[$key])."')";
6850 } else {
6851 $sql .= ",null";
6852 }
6853 }
6854 }
6855 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6856 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6857 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6858 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6859 if (in_array($tmpval, array('int', 'double', 'price'))) {
6860 $sql .= ", 0";
6861 } else {
6862 $sql .= ", ''";
6863 }
6864 }
6865 }
6866 }
6867
6868 $sql .= ")";
6869
6870 $resql = $this->db->query($sql);
6871 if (!$resql) {
6872 $this->error = $this->db->lasterror();
6873 $error++;
6874 }
6875
6876 if (!$error && $trigger) {
6877 // Call trigger
6878 $this->context = array('extrafieldaddupdate' => 1);
6879 $result = $this->call_trigger($trigger, $userused);
6880 if ($result < 0) {
6881 $error++;
6882 }
6883 // End call trigger
6884 }
6885
6886 if ($error) {
6887 $this->db->rollback();
6888 return -1;
6889 } else {
6890 $this->db->commit();
6891 return 1;
6892 }
6893 } else {
6894 return 0;
6895 }
6896 }
6897
6908 public function insertExtraLanguages($trigger = '', $userused = null)
6909 {
6910 global $conf, $langs, $user;
6911
6912 if (empty($userused)) {
6913 $userused = $user;
6914 }
6915
6916 $error = 0;
6917
6918 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
6919 return 0; // For avoid conflicts if trigger used
6920 }
6921
6922 if (is_array($this->array_languages)) {
6923 $new_array_languages = $this->array_languages;
6924
6925 foreach ($new_array_languages as $key => $value) {
6926 $attributeKey = $key;
6927 $attributeType = $this->fields[$attributeKey]['type'];
6928 $attributeLabel = $this->fields[$attributeKey]['label'];
6929
6930 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6931 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6932
6933 switch ($attributeType) {
6934 case 'int':
6935 if (is_array($value) || (!is_numeric($value) && $value != '')) {
6936 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6937 return -1;
6938 } elseif ($value == '') { // @phan-suppress-current-line PhanTypeComparisonFromArray
6939 $new_array_languages[$key] = null;
6940 }
6941 break;
6942 case 'double':
6943 $value = price2num((string) $value);
6944 if (!is_numeric($value) && $value != '') {
6945 dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6946 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6947 return -1;
6948 } elseif ($value == '') {
6949 $new_array_languages[$key] = null;
6950 } else {
6951 $new_array_languages[$key] = $value;
6952 }
6953 break;
6954 /*case 'select': // Not required, we chose value='0' for undefined values
6955 if ($value=='-1')
6956 {
6957 $this->array_options[$key] = null;
6958 }
6959 break;*/
6960 }
6961 }
6962
6963 $this->db->begin();
6964
6965 $table_element = $this->table_element;
6966 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
6967 $table_element = 'categories'; // For compatibility
6968 }
6969
6970 dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6971
6972 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6973 foreach ($langcodearray as $langcode => $value) {
6974 $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6975 $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6976 $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6977 $this->db->query($sql_del);
6978
6979 if ($value !== '') {
6980 $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6981 $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6982 $sql .= ")";
6983
6984 $resql = $this->db->query($sql);
6985 if (!$resql) {
6986 $this->error = $this->db->lasterror();
6987 $error++;
6988 break;
6989 }
6990 }
6991 }
6992 }
6993
6994 if (!$error && $trigger) {
6995 // Call trigger
6996 $this->context = array('extralanguagesaddupdate' => 1);
6997 $result = $this->call_trigger($trigger, $userused);
6998 if ($result < 0) {
6999 $error++;
7000 }
7001 // End call trigger
7002 }
7003
7004 if ($error) {
7005 $this->db->rollback();
7006 return -1;
7007 } else {
7008 $this->db->commit();
7009 return 1;
7010 }
7011 } else {
7012 return 0;
7013 }
7014 }
7015
7026 public function updateExtraField($key, $trigger = null, $userused = null)
7027 {
7028 global $conf, $langs, $user, $hookmanager;
7029
7030 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
7031 return 0;
7032 }
7033
7034 if (empty($userused)) {
7035 $userused = $user;
7036 }
7037
7038 $error = 0;
7039
7040 if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
7041 // Check parameters
7042 $langs->load('admin');
7043 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
7044 $extrafields = new ExtraFields($this->db);
7045 $extrafields->fetch_name_optionals_label($this->table_element);
7046
7047 $value = $this->array_options["options_".$key];
7048
7049 $attributeKey = $key;
7050 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
7051 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
7052 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
7053 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
7054 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
7055 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
7056
7057 // Similar code than into insertExtraFields
7058 if ($attributeRequired) {
7059 $mandatorypb = false;
7060 if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
7061 $mandatorypb = true;
7062 }
7063 if ($this->array_options["options_".$key] === '') {
7064 $mandatorypb = true;
7065 }
7066 if ($mandatorypb) {
7067 $langs->load("errors");
7068 dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
7069 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
7070 return -1;
7071 }
7072 }
7073
7074 // $new_array_options will be used for direct update, so must contains formatted data for the UPDATE.
7075 $new_array_options = $this->array_options;
7076
7077 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
7078 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
7079 if (!empty($attrfieldcomputed)) {
7080 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
7081 $value = dol_eval($attrfieldcomputed, 1, 0, '2');
7082 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
7083
7084 $new_array_options["options_".$key] = $value;
7085
7086 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7087 } else {
7088 $new_array_options["options_".$key] = null;
7089
7090 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7091 }
7092 }
7093
7094 switch ($attributeType) {
7095 case 'int':
7096 if (!is_numeric($value) && $value != '') {
7097 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7098 return -1;
7099 } elseif ($value === '') {
7100 $new_array_options["options_".$key] = null;
7101
7102 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7103 }
7104 break;
7105 case 'price':
7106 case 'double':
7107 $value = price2num($value);
7108 if (!is_numeric($value) && $value != '') {
7109 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7110 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7111 return -1;
7112 } elseif ($value === '') {
7113 $value = null;
7114 }
7115 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
7116 $new_array_options["options_".$key] = $value;
7117
7118 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7119 break;
7120 /*case 'select': // Not required, we chose value='0' for undefined values
7121 if ($value=='-1')
7122 {
7123 $new_array_options["options_".$key] = $value;
7124
7125 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7126 }
7127 break;*/
7128 case 'password':
7129 $algo = '';
7130 if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
7131 // If there is an encryption choice, we use it to encrypt data before insert
7132 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
7133 $algo = reset($tmparrays);
7134 if ($algo != '') {
7135 //global $action; // $action may be 'create', 'update', 'update_extras'...
7136 //var_dump($action);
7137 //var_dump($this->oldcopy);exit;
7138 //var_dump($key.' '.$this->array_options["options_".$key].' '.$algo);
7139 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
7140 //var_dump($this->oldcopy->array_options["options_".$key]); var_dump($this->array_options["options_".$key]);
7141 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.
7142 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7143 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7144 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7145 } else {
7146 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7147 }
7148 } else {
7149 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7150 }
7151 } else {
7152 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7153 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7154 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]);
7155 } else {
7156 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7157 }
7158 } else {
7159 $new_array_options["options_".$key] = dol_hash($this->array_options["options_".$key], $algo);
7160 }
7161 }
7162 } else {
7163 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { // dolibarr reversible encryption
7164 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7165 } else {
7166 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7167 }
7168 }
7169 } else {
7170 // No encryption
7171 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7172 }
7173 } else { // Common usage
7174 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7175 }
7176
7177 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7178 break;
7179 case 'date':
7180 case 'datetime':
7181 if (empty($this->array_options["options_".$key])) {
7182 $new_array_options["options_".$key] = null;
7183
7184 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7185 } else {
7186 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
7187 }
7188 break;
7189 case 'datetimegmt':
7190 if (empty($this->array_options["options_".$key])) {
7191 $new_array_options["options_".$key] = null;
7192
7193 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7194 } else {
7195 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
7196 }
7197 break;
7198 case 'boolean':
7199 if (empty($this->array_options["options_".$key])) {
7200 $new_array_options["options_".$key] = null;
7201
7202 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7203 }
7204 break;
7205 case 'link':
7206 if ($this->array_options["options_".$key] === '') {
7207 $new_array_options["options_".$key] = null;
7208
7209 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7210 }
7211 break;
7212 /*
7213 case 'link':
7214 $param_list = array_keys($attributeParam['options']);
7215 // 0 : ObjectName
7216 // 1 : classPath
7217 $InfoFieldList = explode(":", $param_list[0]);
7218 dol_include_once($InfoFieldList[1]);
7219 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
7220 {
7221 if ($value == '-1') // -1 is key for no defined in combo list of objects
7222 {
7223 $new_array_options[$key] = '';
7224 } elseif ($value) {
7225 $object = new $InfoFieldList[0]($this->db);
7226 if (is_numeric($value)) $res = $object->fetch($value); // Common case
7227 else $res = $object->fetch(0, $value); // For compatibility
7228
7229 if ($res > 0) $new_array_options[$key] = $object->id;
7230 else {
7231 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
7232 $this->db->rollback();
7233 return -1;
7234 }
7235 }
7236 } else {
7237 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7238 }
7239 break;
7240 */
7241 case 'checkbox':
7242 case 'chkbxlst':
7243 $new_array_options = array();
7244 if (is_array($this->array_options["options_".$key])) {
7245 $new_array_options["options_".$key] = implode(',', $this->array_options["options_".$key]);
7246 } else {
7247 $new_array_options["options_".$key] = $this->array_options["options_".$key];
7248 }
7249
7250 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7251 break;
7252 }
7253
7254 $this->db->begin();
7255
7256 $linealreadyfound = 0;
7257
7258 // 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)
7259 $table_element = $this->table_element;
7260 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
7261 $table_element = 'categories'; // For compatibility
7262 }
7263
7264 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7265 $resql = $this->db->query($sql);
7266 if ($resql) {
7267 $tmpobj = $this->db->fetch_object($resql);
7268 if ($tmpobj) {
7269 $linealreadyfound = $tmpobj->nb;
7270 }
7271 }
7272
7273 //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit;
7274 if ($linealreadyfound) {
7275 if ($this->array_options["options_".$key] === null) {
7276 $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = null";
7277 } else {
7278 $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = '".$this->db->escape($new_array_options["options_".$key])."'";
7279 }
7280 $sql .= " WHERE fk_object = ".((int) $this->id);
7281
7282 $resql = $this->db->query($sql);
7283 if (!$resql) {
7284 $error++;
7285 $this->error = $this->db->lasterror();
7286 }
7287 } else {
7288 $result = $this->insertExtraFields('', $user);
7289 if ($result < 0) {
7290 $error++;
7291 }
7292 }
7293
7294 if (!$error) {
7295 $parameters = array('key' => $key);
7296 global $action;
7297 $reshook = $hookmanager->executeHooks('updateExtraFieldBeforeCommit', $parameters, $this, $action);
7298 if ($reshook < 0) {
7299 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
7300 }
7301 }
7302
7303 if (!$error && $trigger) {
7304 // Call trigger
7305 $this->context = array('extrafieldupdate' => 1);
7306 $result = $this->call_trigger($trigger, $userused);
7307 if ($result < 0) {
7308 $error++;
7309 }
7310 // End call trigger
7311 }
7312
7313 if ($error) {
7314 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7315 $this->db->rollback();
7316 return -1;
7317 } else {
7318 $this->db->commit();
7319 return 1;
7320 }
7321 } else {
7322 return 0;
7323 }
7324 }
7325
7332 public function getExtraField($key)
7333 {
7334 return $this->array_options['options_'.$key] ?? null;
7335 }
7336
7344 public function setExtraField($key, $value)
7345 {
7346 $this->array_options['options_'.$key] = $value;
7347 }
7348
7359 public function updateExtraLanguages($key, $trigger = null, $userused = null)
7360 {
7361 global $conf, $langs, $user;
7362
7363 if (empty($userused)) {
7364 $userused = $user;
7365 }
7366
7367 $error = 0;
7368
7369 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
7370 return 0; // For avoid conflicts if trigger used
7371 }
7372
7373 return 0;
7374 }
7375
7376
7392 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
7393 {
7394 global $conf, $langs, $form;
7395
7396 if (!is_object($form)) {
7397 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7398 $form = new Form($this->db);
7399 }
7400
7401 if (!empty($this->fields)) {
7402 $val = $this->fields[$key];
7403 }
7404
7405 // Validation tests and output
7406 $fieldValidationErrorMsg = '';
7407 $validationClass = '';
7408 $fieldValidationErrorMsg = $this->getFieldError($key);
7409 if (!empty($fieldValidationErrorMsg)) {
7410 $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
7411 } else {
7412 $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
7413 }
7414
7415 $valuemultiselectinput = array();
7416 $out = '';
7417 $type = '';
7418 $isDependList = 0;
7419 $param = array();
7420 $param['options'] = array();
7421 $reg = array();
7422 // @phan-suppress-next-line PhanTypeMismatchProperty
7423 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
7424 // Because we work on extrafields
7425 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7426 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7427 $type = 'link';
7428 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7429 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7430 $type = 'link';
7431 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
7432 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7433 $type = 'link';
7434 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7435 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7436 $type = 'sellist';
7437 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7438 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7439 $type = 'sellist';
7440 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
7441 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7442 $type = 'sellist';
7443 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
7444 $param['options'] = array($reg[1] => 'N');
7445 $type = 'chkbxlst';
7446 } elseif (preg_match('/varchar\‍((\d+)\‍)/', $val['type'], $reg)) {
7447 $param['options'] = array();
7448 $type = 'varchar';
7449 $size = $reg[1];
7450 } elseif (preg_match('/varchar/', $val['type'])) {
7451 $param['options'] = array();
7452 $type = 'varchar';
7453 } elseif (preg_match('/stars\‍((\d+)\‍)/', $val['type'], $reg)) {
7454 $param['options'] = array();
7455 $type = 'stars';
7456 $size = $reg[1];
7457 } else {
7458 $param['options'] = array();
7459 $type = $this->fields[$key]['type'];
7460 }
7461 //var_dump($type); var_dump($param['options']);
7462
7463 // Special case that force options and type ($type can be integer, varchar, ...)
7464 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
7465 $param['options'] = $this->fields[$key]['arrayofkeyval'];
7466 // Special case that prevent to force $type to have multiple input @phan-suppress-next-line PhanTypeMismatchProperty
7467 if (empty($this->fields[$key]['multiinput'])) {
7468 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
7469 }
7470 }
7471
7472 $label = $this->fields[$key]['label'];
7473 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
7474 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7475 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
7476 // @phan-suppress-next-line PhanTypeMismatchProperty
7477 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
7478 // @phan-suppress-next-line PhanTypeMismatchProperty
7479 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
7480 // @phan-suppress-next-line PhanTypeMismatchProperty
7481 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
7482 // @phan-suppress-next-line PhanTypeMismatchProperty
7483 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
7484
7485 // @phan-suppress-next-line PhanTypeMismatchProperty
7486 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
7487 // @phan-suppress-next-line PhanTypeMismatchProperty
7488 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
7489 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
7490
7491 $objectid = $this->id;
7492
7493 if ($computed) {
7494 if (!preg_match('/^search_/', $keyprefix)) {
7495 return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
7496 } else {
7497 return '';
7498 }
7499 }
7500
7501 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
7502 if (empty($morecss) && !empty($val['css'])) {
7503 $morecss = $val['css'];
7504 } elseif (empty($morecss)) {
7505 if ($type == 'date') {
7506 $morecss = 'minwidth100imp';
7507 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
7508 $morecss = 'minwidth200imp';
7509 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
7510 $morecss = 'maxwidth75';
7511 } elseif ($type == 'url') {
7512 $morecss = 'minwidth400';
7513 } elseif ($type == 'boolean') {
7514 $morecss = '';
7515 } else {
7516 if (is_numeric($size) && round((float) $size) < 12) {
7517 $morecss = 'minwidth100';
7518 } elseif (is_numeric($size) && round((float) $size) <= 48) {
7519 $morecss = 'minwidth200';
7520 } else {
7521 $morecss = 'minwidth400';
7522 }
7523 }
7524 }
7525
7526 // Add validation state class
7527 if (!empty($validationClass)) {
7528 $morecss .= $validationClass;
7529 }
7530
7531 if (in_array($type, array('date'))) {
7532 $tmp = explode(',', $size);
7533 $newsize = $tmp[0];
7534 $showtime = 0;
7535
7536 // Do not show current date when field not required (see selectDate() method)
7537 if (!$required && $value == '') {
7538 $value = '-1';
7539 }
7540
7541 // TODO Must also support $moreparam
7542 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
7543 } elseif (in_array($type, array('datetime'))) {
7544 $tmp = explode(',', $size);
7545 $newsize = $tmp[0];
7546 $showtime = 1;
7547
7548 // Do not show current date when field not required (see selectDate() method)
7549 if (!$required && $value == '') {
7550 $value = '-1';
7551 }
7552
7553 // TODO Must also support $moreparam
7554 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
7555 } elseif (in_array($type, array('duration'))) {
7556 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
7557 } elseif (in_array($type, array('int', 'integer'))) {
7558 $tmp = explode(',', $size);
7559 $newsize = $tmp[0];
7560 $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' : '').'>';
7561 } elseif (in_array($type, array('real'))) {
7562 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7563 } elseif (preg_match('/varchar/', (string) $type)) {
7564 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"'.($size > 0 ? ' maxlength="'.$size.'"' : '').' value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7565 } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
7566 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7567 } elseif (preg_match('/^text/', (string) $type)) {
7568 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7569 if (!empty($param['options'])) {
7570 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
7571 //var_dump($param['options']);
7572 $out .= $form->selectarray($keyprefix.$key.$keysuffix."_multiinput", $param['options'], '', 1, 0, 0, "flat maxwidthonphone".$morecss);
7573 $out .= '<input id="'.$keyprefix.$key.$keysuffix.'_multiinputadd" type="button" class="button" value="'.$langs->trans("Add").'">';
7574 $out .= "<script>";
7575 $out .= '
7576 function handlemultiinputdisabling(htmlname){
7577 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7578 multiinput = $("#"+htmlname+"_multiinput");
7579 multiinput.find("option").each(function(){
7580 tmpval = $("#"+htmlname).val();
7581 tmpvalarray = tmpval.split("\n");
7582 valtotest = $(this).val();
7583 if(tmpvalarray.includes(valtotest)){
7584 $(this).prop("disabled",true);
7585 } else {
7586 if($(this).prop("disabled") == true){
7587 console.log(valtotest)
7588 $(this).prop("disabled", false);
7589 }
7590 }
7591 });
7592 }
7593
7594 $(document).ready(function () {
7595 $("#'.$keyprefix.$key.$keysuffix.'_multiinputadd").on("click",function() {
7596 tmpval = $("#'.$keyprefix.$key.$keysuffix.'").val();
7597 tmpvalarray = tmpval.split(",");
7598 valtotest = $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val();
7599 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7600 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.'");
7601 if(tmpval == ""){
7602 tmpval = valtotest;
7603 } else {
7604 tmpval = tmpval + "\n" + valtotest;
7605 }
7606 $("#'.$keyprefix.$key.$keysuffix.'").val(tmpval);
7607 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7608 $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val(-1);
7609 } else {
7610 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.'");
7611 }
7612 });
7613 $("#'.$keyprefix.$key.$keysuffix.'").on("change",function(){
7614 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7615 });
7616 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7617 })';
7618 $out .= "</script>";
7619 $value = str_replace(',', "\n", $value);
7620 }
7621 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7622 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
7623 $out .= (string) $doleditor->Create(1, '', true, '', '', '', $morecss);
7624 } else {
7625 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7626 }
7627 } elseif (preg_match('/^html/', (string) $type)) {
7628 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7629 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7630 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
7631 $out = (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
7632 } else {
7633 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7634 }
7635 } elseif ($type == 'boolean') {
7636 $checked = '';
7637 if (!empty($value)) {
7638 $checked = ' checked value="1" ';
7639 } else {
7640 $checked = ' value="1" ';
7641 }
7642 $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
7643 } elseif ($type == 'price') {
7644 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7645 $value = price($value);
7646 }
7647 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
7648 } elseif ($type == 'stars') {
7649 $out = '<input type="hidden" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7650 $out .= '<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.'_selection">';
7651 $i = 1;
7652 while ($i <= $size) {
7653 $out .= '<span class="star" data-value="'.$i.'">'.img_picto('', 'fontawesome_star_fas').'</span>';
7654 $i++;
7655 }
7656 $out .= '</div>';
7657 $out .= '<script>
7658 jQuery(function($) {
7659 let container = $("#'.$keyprefix.$key.$keysuffix.'_selection");
7660 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.'").val()) || 0;
7661 container.find(".star").each(function() {
7662 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7663 });
7664 container.find(".star").on("mouseover", function() {
7665 let selectedStar = $(this).data("value");
7666 container.find(".star").each(function() {
7667 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
7668 });
7669 });
7670 container.on("mouseout", function() {
7671 container.find(".star").each(function() {
7672 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7673 });
7674 });
7675 container.find(".star").off("click").on("click", function() {
7676 selectedStars = $(this).data("value");
7677 if (selectedStars === 1 && $("#'.$keyprefix.$key.$keysuffix.'").val() == 1) {
7678 selectedStars = 0;
7679 }
7680 $("#'.$keyprefix.$key.$keysuffix.'").val(selectedStars);
7681 container.find(".star").each(function() {
7682 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
7683 });
7684 });
7685 });
7686 </script>';
7687 } elseif (preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
7688 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7689 $value = price($value);
7690 }
7691 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
7692 } elseif ($type == 'select') { // combo list
7693 $out = '';
7694 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7695 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7696 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7697 }
7698
7699 $tmpselect = '';
7700 $nbchoice = 0;
7701 foreach ($param['options'] as $keyb => $valb) {
7702 if ((string) $keyb == '') {
7703 continue;
7704 }
7705 if (strpos($valb, "|") !== false) {
7706 list($valb, $parent) = explode('|', $valb);
7707 }
7708 $nbchoice++;
7709 $tmpselect .= '<option value="'.$keyb.'"';
7710 $tmpselect .= (((string) $value == (string) $keyb) ? ' selected' : '');
7711 if (!empty($parent)) {
7712 $isDependList = 1;
7713 }
7714 $tmpselect .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7715 $tmpselect .= '>'.$langs->trans($valb).'</option>';
7716 }
7717
7718 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7719 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1) || $nbchoice >= 2) {
7720 $out .= '<option value="0">&nbsp;</option>';
7721 }
7722 $out .= $tmpselect;
7723 $out .= '</select>';
7724 } elseif ($type == 'sellist') {
7725 $out = '';
7726 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7727 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7728 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7729 }
7730
7731 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7732 if (is_array($param['options'])) {
7733 $tmpparamoptions = array_keys($param['options']);
7734 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
7735
7736 $InfoFieldList = explode(":", $paramoptions[0], 5);
7737 // 0 : tableName
7738 // 1 : label field name
7739 // 2 : key fields name (if different of rowid)
7740 // optional parameters...
7741 // 3 : key field parent (for dependent lists). How this is used ?
7742 // 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".
7743 // 5 : string category type. This replace the filter.
7744 // 6 : ids categories list separated by comma for category root. This replace the filter.
7745 // 7 : sort field
7746
7747 // If there is filter
7748 if (! empty($InfoFieldList[4])) {
7749 $pos = 0;
7750 $parenthesisopen = 0;
7751 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
7752 if (substr($InfoFieldList[4], $pos, 1) == '(') {
7753 $parenthesisopen++;
7754 }
7755 if (substr($InfoFieldList[4], $pos, 1) == ')') {
7756 $parenthesisopen--;
7757 }
7758 $pos++;
7759 }
7760 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7761 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7762 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
7763 $InfoFieldList[4] = $tmpbefore;
7764 if ($tmpafter !== '') {
7765 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
7766 }
7767 //var_dump($InfoFieldList);
7768
7769 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
7770 $reg = array();
7771 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
7772 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
7773 }
7774
7775 //var_dump($InfoFieldList);
7776 }
7777
7778 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
7779
7780 $parentName = '';
7781 $parentField = '';
7782
7783 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7784
7785 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7786 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7787 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7788 } else {
7789 $keyList = $InfoFieldList[2].' as rowid';
7790 }
7791 }
7792 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7793 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7794 $keyList .= ', '.$parentField;
7795 }
7796
7797 $filter_categorie = false;
7798 if (count($InfoFieldList) > 5) {
7799 if ($InfoFieldList[0] == 'categorie') {
7800 $filter_categorie = true;
7801 }
7802 }
7803
7804 if (!$filter_categorie) {
7805 $fields_label = explode('|', $InfoFieldList[1]);
7806 if (is_array($fields_label)) {
7807 $keyList .= ', ';
7808 $keyList .= implode(', ', $fields_label);
7809 }
7810
7811 $sqlwhere = '';
7812 $sql = "SELECT " . $keyList;
7813 $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
7814
7815 if (!empty($InfoFieldList[4])) {
7816 // can use SELECT request
7817 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7818 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7819 }
7820
7821 // current object id can be use into filter
7822 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7823 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
7824 } else {
7825 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7826 }
7827
7828 // We have to join on extrafield table
7829 $errstr = '';
7830 if (strpos($InfoFieldList[4], 'extra') !== false) {
7831 $sql .= " as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . "_extrafields as extra";
7832 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7833 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
7834 } else {
7835 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
7836 }
7837 } else {
7838 $sqlwhere .= ' WHERE 1=1';
7839 }
7840
7841 // Add Usf filter on second line
7842 /*
7843 if ($Usf) {
7844 $errorstr = '';
7845 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
7846 if (!$errorstr) {
7847 $sqlwhere .= $sqlusf;
7848 } else {
7849 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
7850 }
7851 }
7852 */
7853
7854 // Some tables may have field, some other not. For the moment we disable it.
7855 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7856 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7857 }
7858 $sql .= $sqlwhere;
7859 //print $sql;
7860
7861 // Note: $InfoFieldList can be 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:Sortfield]]]]]]'
7862 if (isset($InfoFieldList[7]) && preg_match('/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
7863 $sql .= " ORDER BY ".$this->db->escape($InfoFieldList[7]);
7864 } else {
7865 $sql .= " ORDER BY ".$this->db->sanitize(implode(', ', $fields_label));
7866 }
7867
7868 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7869 $resql = $this->db->query($sql);
7870 if ($resql) {
7871 $out .= '<option value="0">&nbsp;</option>';
7872 $num = $this->db->num_rows($resql);
7873 $i = 0;
7874 while ($i < $num) {
7875 $labeltoshow = '';
7876 $obj = $this->db->fetch_object($resql);
7877
7878 // Several field into label (eq table:code|libelle:rowid)
7879 $notrans = false;
7880 $fields_label = explode('|', $InfoFieldList[1]);
7881 if (count($fields_label) > 1) {
7882 $notrans = true;
7883 foreach ($fields_label as $field_toshow) {
7884 $labeltoshow .= $obj->$field_toshow . ' ';
7885 }
7886 } else {
7887 $labeltoshow = $obj->{$InfoFieldList[1]};
7888 }
7889 $labeltoshow = dol_trunc($labeltoshow, 45);
7890
7891 if ($value == $obj->rowid) {
7892 foreach ($fields_label as $field_toshow) {
7893 $translabel = $langs->trans($obj->$field_toshow);
7894 if ($translabel != $obj->$field_toshow) {
7895 $labeltoshow = dol_trunc($translabel) . ' ';
7896 } else {
7897 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7898 }
7899 }
7900 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7901 } else {
7902 if (!$notrans) {
7903 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7904 if ($translabel != $obj->{$InfoFieldList[1]}) {
7905 $labeltoshow = dol_trunc($translabel, 18);
7906 } else {
7907 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7908 }
7909 }
7910 if (empty($labeltoshow)) {
7911 $labeltoshow = '(not defined)';
7912 }
7913 if ($value == $obj->rowid) {
7914 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7915 }
7916
7917 if (!empty($InfoFieldList[3]) && $parentField) {
7918 $parent = $parentName . ':' . $obj->{$parentField};
7919 $isDependList = 1;
7920 }
7921
7922 $out .= '<option value="' . $obj->rowid . '"';
7923 $out .= ($value == $obj->rowid ? ' selected' : '');
7924 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7925 $out .= '>' . $labeltoshow . '</option>';
7926 }
7927
7928 $i++;
7929 }
7930 $this->db->free($resql);
7931 } else {
7932 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7933 }
7934 } else {
7935 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7936 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7937 $out .= '<option value="0">&nbsp;</option>';
7938 foreach ($data as $data_key => $data_value) {
7939 $out .= '<option value="' . $data_key . '"';
7940 $out .= ($value == $data_key ? ' selected' : '');
7941 $out .= '>' . $data_value . '</option>';
7942 }
7943 }
7944 }
7945 $out .= '</select>';
7946 } elseif ($type == 'checkbox') {
7947 $value_arr = explode(',', $value);
7948 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, 0, 0, $morecss, 0, '100%');
7949 } elseif ($type == 'radio') {
7950 $out = '';
7951 foreach ($param['options'] as $keyopt => $valopt) {
7952 $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7953 $out .= ' value="'.$keyopt.'"';
7954 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7955 $out .= ($value == $keyopt ? 'checked' : '');
7956 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7957 }
7958 } elseif ($type == 'chkbxlst') {
7959 if (is_array($value)) {
7960 $value_arr = $value;
7961 } else {
7962 $value_arr = explode(',', $value);
7963 }
7964
7965 if (is_array($param['options'])) {
7966 $tmpparamoptions = array_keys($param['options']);
7967 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
7968
7969 $InfoFieldList = explode(":", $paramoptions[0], 5);
7970 // 0 : tableName
7971 // 1 : label field name
7972 // 2 : key fields name (if different of rowid)
7973 // optional parameters...
7974 // 3 : key field parent (for dependent lists). How this is used ?
7975 // 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".
7976 // 5 : string category type. This replace the filter.
7977 // 6 : ids categories list separated by comma for category root. This replace the filter.
7978 // 7 : sort field
7979
7980 // If there is a filter
7981 if (! empty($InfoFieldList[4])) {
7982 $pos = 0;
7983 $parenthesisopen = 0;
7984 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
7985 if (substr($InfoFieldList[4], $pos, 1) == '(') {
7986 $parenthesisopen++;
7987 }
7988 if (substr($InfoFieldList[4], $pos, 1) == ')') {
7989 $parenthesisopen--;
7990 }
7991 $pos++;
7992 }
7993 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7994 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7995 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
7996 $InfoFieldList[4] = $tmpbefore;
7997 if ($tmpafter !== '') {
7998 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
7999 }
8000
8001 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
8002 $reg = array();
8003 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
8004 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
8005 }
8006
8007 //var_dump($InfoFieldList);
8008 }
8009
8010 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
8011
8012 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
8013
8014 $parentName = '';
8015 $parentField = '';
8016
8017 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
8018
8019 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
8020 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
8021 $keyList .= ', '.$parentField;
8022 }
8023 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8024 if (strpos($InfoFieldList[4], 'extra.') !== false) {
8025 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
8026 } else {
8027 $keyList = $InfoFieldList[2].' as rowid';
8028 }
8029 }
8030
8031 $filter_categorie = false;
8032 if (count($InfoFieldList) > 5) {
8033 if ($InfoFieldList[0] == 'categorie') {
8034 $filter_categorie = true;
8035 }
8036 }
8037
8038 // Common filter
8039 if (!$filter_categorie) {
8040 $fields_label = explode('|', $InfoFieldList[1]);
8041 if (is_array($fields_label)) {
8042 $keyList .= ', ';
8043 $keyList .= implode(', ', $fields_label);
8044 }
8045
8046 $sqlwhere = '';
8047 $sql = "SELECT " . $keyList;
8048 $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
8049
8050 if (!empty($InfoFieldList[4])) {
8051 // can use SELECT request
8052 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
8053 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
8054 }
8055
8056 // current object id can be use into filter
8057 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
8058 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
8059 } else {
8060 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
8061 }
8062
8063 // We have to join on extrafield table
8064 $errstr = '';
8065 if (strpos($InfoFieldList[4], 'extra') !== false) {
8066 $sql .= ' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . '_extrafields as extra';
8067 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
8068 $sqlwhere .= " AND " . $InfoFieldList[4];
8069 } else {
8070 $sqlwhere .= " WHERE " . $InfoFieldList[4];
8071 }
8072 } else {
8073 $sqlwhere .= ' WHERE 1=1';
8074 }
8075
8076 // Add Usf filter on second line
8077 /*
8078 if ($Usf) {
8079 $errorstr = '';
8080 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
8081 if (!$errorstr) {
8082 $sqlwhere .= $sqlusf;
8083 } else {
8084 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
8085 }
8086 }
8087 */
8088
8089 // Some tables may have field, some other not. For the moment we disable it.
8090 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
8091 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
8092 }
8093 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
8094 // print $sql;
8095
8096 $sql .= $sqlwhere;
8097
8098 dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
8099
8100 $resql = $this->db->query($sql);
8101 if ($resql) {
8102 $num = $this->db->num_rows($resql);
8103 $i = 0;
8104
8105 $data = array();
8106
8107 while ($i < $num) {
8108 $labeltoshow = '';
8109 $obj = $this->db->fetch_object($resql);
8110
8111 $notrans = false;
8112 // Several field into label (eq table:code|libelle:rowid)
8113 $fields_label = explode('|', $InfoFieldList[1]);
8114 if (count($fields_label) > 1) {
8115 $notrans = true;
8116 foreach ($fields_label as $field_toshow) {
8117 $labeltoshow .= $obj->$field_toshow . ' ';
8118 }
8119 } else {
8120 $labeltoshow = $obj->{$InfoFieldList[1]};
8121 }
8122 $labeltoshow = dol_trunc($labeltoshow, 45);
8123
8124 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8125 foreach ($fields_label as $field_toshow) {
8126 $translabel = $langs->trans($obj->$field_toshow);
8127 if ($translabel != $obj->$field_toshow) {
8128 $labeltoshow = dol_trunc($translabel, 18) . ' ';
8129 } else {
8130 $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
8131 }
8132 }
8133
8134 $data[$obj->rowid] = $labeltoshow;
8135 } else {
8136 if (!$notrans) {
8137 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8138 if ($translabel != $obj->{$InfoFieldList[1]}) {
8139 $labeltoshow = dol_trunc($translabel, 18);
8140 } else {
8141 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
8142 }
8143 }
8144 if (empty($labeltoshow)) {
8145 $labeltoshow = '(not defined)';
8146 }
8147
8148 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8149 $data[$obj->rowid] = $labeltoshow;
8150 }
8151
8152 if (!empty($InfoFieldList[3]) && $parentField) {
8153 $parent = $parentName . ':' . $obj->{$parentField};
8154 $isDependList = 1;
8155 }
8156
8157 $data[(int) $obj->rowid] = $labeltoshow;
8158 }
8159
8160 $i++;
8161 }
8162 $this->db->free($resql);
8163
8164 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
8165 } else {
8166 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
8167 }
8168 } else {
8169 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
8170 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[(int) $InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
8171 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
8172 }
8173 }
8174 } elseif ($type == 'link') {
8175 // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
8176 // Filter can contains some ':' inside.
8177 $param_list = array_keys($param['options']);
8178 $param_list_array = explode(':', $param_list[0], 4);
8179
8180 $showempty = (($required && $default != '') ? 0 : 1);
8181
8182 if (!preg_match('/search_/', $keyprefix)) {
8183 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
8184 // @phan-suppress-next-line PhanTypeMismatchProperty
8185 if (!empty($this->fields[$key]['picto'])) {
8186 $morecss .= ' widthcentpercentminusxx';
8187 } else {
8188 $morecss .= ' widthcentpercentminusx';
8189 }
8190 } else {
8191 // @phan-suppress-next-line PhanTypeMismatchProperty
8192 if (!empty($this->fields[$key]['picto'])) {
8193 $morecss .= ' widthcentpercentminusx';
8194 }
8195 }
8196 }
8197 $objectfield = $this->element.($this->module ? '@'.$this->module : '').':'.$key.$keysuffix;
8198 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), '', $objectfield);
8199
8200 if (!empty($param_list_array[2])) { // If the entry into $fields is set, we must add a create button
8201 if ((!GETPOSTISSET('backtopage') || strpos(GETPOST('backtopage'), $_SERVER['PHP_SELF']) === 0) // // To avoid to open several times the 'Plus' button (we accept only one level)
8202 && empty($val['disabled']) && empty($nonewbutton)) { // and to avoid to show the button if the field is protected by a "disabled".
8203 list($class, $classfile) = explode(':', $param_list[0]);
8204 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
8205 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
8206 } else {
8207 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
8208 }
8209 $paramforthenewlink = '';
8210 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
8211 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOSTINT('id') : '');
8212 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
8213 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOSTINT('originid') : '');
8214 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
8215 // TODO Add JavaScript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
8216 $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>';
8217 }
8218 }
8219 } elseif ($type == 'password') {
8220 // If prefix is 'search_', field is used as a filter, we use a common text field.
8221 if ($keyprefix.$key.$keysuffix == 'pass_crypted') {
8222 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="pass" id="pass" value="" '.($moreparam ? $moreparam : '').'>';
8223 $out .= '<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
8224 } else {
8225 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
8226 }
8227 } elseif ($type == 'array') {
8228 $newval = $val;
8229 $newval['type'] = 'varchar(256)';
8230
8231 $out = '';
8232 if (!empty($value)) {
8233 foreach ($value as $option) {
8234 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8235 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
8236 }
8237 }
8238 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8239
8240 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8241 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
8242
8243 if (!empty($conf->use_javascript_ajax)) {
8244 $out .= '
8245 <script nonce="'.getNonce().'">
8246 $(document).ready(function() {
8247 $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
8248 $("'.dol_escape_js($newInput).'").insertBefore(this);
8249 });
8250
8251 $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
8252 $(this).parent().remove();
8253 });
8254 });
8255 </script>';
8256 }
8257 }
8258 if (!empty($hidden)) {
8259 $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
8260 }
8261
8262 if ($isDependList == 1) {
8263 $out .= $this->getJSListDependancies('_common');
8264 }
8265 /* Add comments
8266 if ($type == 'date') $out.=' (YYYY-MM-DD)';
8267 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
8268 */
8269
8270 // Display error message for field
8271 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
8272 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
8273 }
8274
8275 return $out;
8276 }
8277
8291 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
8292 {
8293 global $conf, $langs, $form;
8294
8295 if (!is_object($form)) {
8296 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
8297 $form = new Form($this->db);
8298 }
8299
8300 //$label = empty($val['label']) ? '' : $val['label'];
8301 $type = empty($val['type']) ? '' : $val['type'];
8302 $size = empty($val['css']) ? '' : $val['css'];
8303 $reg = array();
8304
8305 // Convert var to be able to share same code than showOutputField of extrafields
8306 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8307 $type = 'varchar'; // convert varchar(xx) int varchar
8308 $size = $reg[1];
8309 } elseif (preg_match('/varchar/', $type)) {
8310 $type = 'varchar'; // convert varchar(xx) int varchar
8311 }
8312 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8313 // @phan-suppress-next-line PhanTypeMismatchProperty
8314 if (empty($this->fields[$key]['multiinput'])) {
8315 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
8316 }
8317 }
8318 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8319 $type = 'link';
8320 }
8321
8322 $default = empty($val['default']) ? '' : $val['default'];
8323 $computed = empty($val['computed']) ? '' : $val['computed'];
8324 $unique = empty($val['unique']) ? '' : $val['unique'];
8325 $required = empty($val['required']) ? '' : $val['required'];
8326 $param = array();
8327 $param['options'] = array();
8328
8329 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8330 $param['options'] = $val['arrayofkeyval'];
8331 }
8332 if (preg_match('/^integer:([^:]*):([^:]*)/i', $val['type'], $reg)) { // ex: integer:User:user/class/user.class.php
8333 $type = 'link';
8334 $stringforoptions = $reg[1].':'.$reg[2];
8335 // Special case: Force addition of getnomurlparam1 to -1 for users
8336 if ($reg[1] == 'User') {
8337 $stringforoptions .= ':#getnomurlparam1=-1';
8338 }
8339 $param['options'] = array($stringforoptions => $stringforoptions);
8340 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8341 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8342 $type = 'sellist';
8343 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8344 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8345 $type = 'sellist';
8346 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8347 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8348 $type = 'sellist';
8349 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
8350 $param['options'] = array($reg[1] => 'N');
8351 $type = 'chkbxlst';
8352 } elseif (preg_match('/stars\‍((\d+)\‍)/', $val['type'], $reg)) {
8353 $param['options'] = array();
8354 $type = 'stars';
8355 $size = $reg[1];
8356 }
8357
8358 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
8359 $list = (empty($val['list']) ? '' : $val['list']);
8360 $help = (empty($val['help']) ? '' : $val['help']);
8361 $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)
8362
8363 if ($hidden) {
8364 return '';
8365 }
8366
8367 // If field is a computed field, value must become result of compute
8368 if ($computed) {
8369 // Make the eval of compute string
8370 //var_dump($computed);
8371 $value = dol_eval($computed, 1, 0, '2');
8372 }
8373
8374 if (empty($morecss)) {
8375 if ($type == 'date') {
8376 $morecss = 'minwidth100imp';
8377 } elseif ($type == 'datetime' || $type == 'timestamp') {
8378 $morecss = 'minwidth200imp';
8379 } elseif (in_array($type, array('int', 'double', 'price'))) {
8380 $morecss = 'maxwidth75';
8381 } elseif ($type == 'url') {
8382 $morecss = 'minwidth400';
8383 } elseif ($type == 'boolean') {
8384 $morecss = '';
8385 } else {
8386 if (is_numeric($size) && round((float) $size) < 12) {
8387 $morecss = 'minwidth100';
8388 } elseif (is_numeric($size) && round((float) $size) <= 48) {
8389 $morecss = 'minwidth200';
8390 } else {
8391 $morecss = 'minwidth400';
8392 }
8393 }
8394 }
8395
8396 // Format output value differently according to properties of field
8397 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
8398 // @phan-suppress-next-line PhanTypeMismatchProperty
8399 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.
8400 $value = $this->getNomUrl(1, '', 0, '', 1);
8401 }
8402 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
8403 $value = $this->getLibStatut(3);
8404 } elseif ($type == 'date') {
8405 if (!empty($value)) {
8406 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
8407 } else {
8408 $value = '';
8409 }
8410 } elseif ($type == 'datetime' || $type == 'timestamp') {
8411 if (!empty($value)) {
8412 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
8413 } else {
8414 $value = '';
8415 }
8416 } elseif ($type == 'duration') {
8417 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
8418 if (!is_null($value) && $value !== '') {
8419 $value = convertSecondToTime((int) $value, 'allhourmin');
8420 }
8421 } elseif ($type == 'double' || $type == 'real') {
8422 if (!is_null($value) && $value !== '') {
8423 $value = price($value);
8424 }
8425 } elseif ($type == 'boolean') {
8426 $checked = '';
8427 if (!empty($value)) {
8428 $checked = ' checked ';
8429 }
8430 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
8431 $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
8432 } else {
8433 $value = yn($value ? 1 : 0);
8434 }
8435 } elseif ($type == 'mail' || $type == 'email') {
8436 $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
8437 } elseif ($type == 'url') {
8438 $value = dol_print_url($value, '_blank', 32, 1);
8439 } elseif ($type == 'phone') {
8440 $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
8441 } elseif ($type == 'ip') {
8442 $value = dol_print_ip($value, 0);
8443 } elseif ($type == 'stars') {
8444 $value = '<input type="hidden" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.$this->id.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
8445 $value .= '<div class="star-selection" id="'.$keyprefix.$key.$keysuffix.$this->id.'_selection">';
8446 $i = 1;
8447 while ($i <= $size) {
8448 $value .= '<span class="star" data-value="'.$i.'">'.img_picto('', 'fontawesome_star_fas').'</span>';
8449 $i++;
8450 }
8451 $value .= '</div>';
8452 $value .= '<script>
8453 $(document).ready(function() {
8454 let container = $("#'.$keyprefix.$key.$keysuffix.$this->id.'_selection");
8455 let selectedStars = parseInt($("#'.$keyprefix.$key.$keysuffix.$this->id.'").val()) || 0;
8456 container.find(".star").each(function() {
8457 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8458 });
8459 container.find(".star").on("mouseover", function() {
8460 let selectedStar = $(this).data("value");
8461 container.find(".star").each(function() {
8462 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
8463 });
8464 });
8465 container.on("mouseout", function() {
8466 container.find(".star").each(function() {
8467 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8468 });
8469 });
8470 container.find(".star").off("click").on("click", function() {
8471 selectedStars = $(this).data("value");
8472 if (selectedStars == 1 && $("#'.$keyprefix.$key.$keysuffix.$this->id.'").val() == 1) {
8473 selectedStars = 0;
8474 }
8475 container.find("#'.$keyprefix.$key.$keysuffix.$this->id.'").val(selectedStars);
8476 container.find(".star").each(function() {
8477 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
8478 });
8479 $.ajax({
8480 url: "ajax/'.$this->element.'.php",
8481 method: "POST",
8482 data: {
8483 objectId: "'.$this->id.'",
8484 field: "'.$keyprefix.$key.$keysuffix.'",
8485 value: selectedStars,
8486 token: "'.newToken().'"
8487 },
8488 success: function(response) {
8489 var res = JSON.parse(response);
8490 console[res.status === "success" ? "log" : "error"](res.message);
8491 },
8492 error: function(xhr, status, error) {
8493 console.log("Ajax request failed while updating '.$keyprefix.$key.$keysuffix.':", error);
8494 }
8495 });
8496 });
8497 });
8498 </script>';
8499 } elseif ($type == 'price') {
8500 if (!is_null($value) && $value !== '') {
8501 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
8502 }
8503 } elseif ($type == 'select') {
8504 $value = isset($param['options'][(string) $value]) ? $param['options'][(string) $value] : '';
8505 if (strpos($value, "|") !== false) {
8506 $value = $langs->trans(explode('|', $value)[0]);
8507 } elseif (! is_numeric($value)) {
8508 $value = $langs->trans($value);
8509 }
8510 } elseif ($type == 'sellist') {
8511 $param_list = array_keys($param['options']);
8512 $InfoFieldList = explode(":", $param_list[0]);
8513
8514 $selectkey = "rowid";
8515 $keyList = 'rowid';
8516
8517 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8518 $selectkey = $InfoFieldList[2];
8519 $keyList = $InfoFieldList[2].' as rowid';
8520 }
8521
8522 $fields_label = explode('|', $InfoFieldList[1]);
8523 if (is_array($fields_label)) {
8524 $keyList .= ', ';
8525 $keyList .= implode(', ', $fields_label);
8526 }
8527
8528 $filter_categorie = false;
8529 if (count($InfoFieldList) > 5) {
8530 if ($InfoFieldList[0] == 'categorie') {
8531 $filter_categorie = true;
8532 }
8533 }
8534
8535 $sql = "SELECT ".$keyList;
8536 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
8537 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra') !== false) {
8538 $sql .= ' as main';
8539 }
8540 if ($selectkey == 'rowid' && empty($value)) {
8541 $sql .= " WHERE ".$selectkey." = 0";
8542 } elseif ($selectkey == 'rowid') {
8543 $sql .= " WHERE ".$selectkey." = ".((int) $value);
8544 } else {
8545 $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
8546 }
8547
8548 //$sql.= ' AND entity = '.$conf->entity;
8549
8550 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
8551 $resql = $this->db->query($sql);
8552 if ($resql) {
8553 if (!$filter_categorie) {
8554 $value = ''; // value was used, so now we reset it to use it to build final output
8555 $numrows = $this->db->num_rows($resql);
8556 if ($numrows) {
8557 $obj = $this->db->fetch_object($resql);
8558
8559 // Several field into label (eq table:code|libelle:rowid)
8560 $fields_label = explode('|', $InfoFieldList[1]);
8561
8562 if (is_array($fields_label) && count($fields_label) > 1) {
8563 foreach ($fields_label as $field_toshow) {
8564 $translabel = '';
8565 if (!empty($obj->$field_toshow)) {
8566 $translabel = $langs->trans($obj->$field_toshow);
8567 }
8568 if ($translabel != $field_toshow) {
8569 $value .= dol_trunc($translabel, 18) . ' ';
8570 } else {
8571 $value .= $obj->$field_toshow . ' ';
8572 }
8573 }
8574 } else {
8575 $translabel = '';
8576 if (!empty($obj->{$InfoFieldList[1]})) {
8577 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8578 }
8579 if ($translabel != $obj->{$InfoFieldList[1]}) {
8580 $value = dol_trunc($translabel, 18);
8581 } else {
8582 $value = $obj->{$InfoFieldList[1]};
8583 }
8584 }
8585 }
8586 } else {
8587 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
8588
8589 $toprint = array();
8590 $obj = $this->db->fetch_object($resql);
8591 $c = new Categorie($this->db);
8592 $c->fetch($obj->rowid);
8593 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
8594 foreach ($ways as $way) {
8595 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
8596 }
8597 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
8598 }
8599 } else {
8600 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8601 }
8602 } elseif ($type == 'radio') {
8603 $value = $param['options'][(string) $value];
8604 } elseif ($type == 'checkbox') {
8605 $value_arr = explode(',', (string) $value);
8606 $value = '';
8607 if (is_array($value_arr) && count($value_arr) > 0) {
8608 $toprint = array();
8609 foreach ($value_arr as $keyval => $valueval) {
8610 if (!empty($valueval)) {
8611 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param['options'][$valueval] . '</li>';
8612 }
8613 }
8614 if (!empty($toprint)) {
8615 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
8616 }
8617 }
8618 } elseif ($type == 'chkbxlst') {
8619 $value_arr = (isset($value) ? explode(',', $value) : array());
8620
8621 $param_list = array_keys($param['options']);
8622 $InfoFieldList = explode(":", $param_list[0]);
8623
8624 $selectkey = "rowid";
8625 $keyList = 'rowid';
8626
8627 if (count($InfoFieldList) >= 3) {
8628 $selectkey = $InfoFieldList[2];
8629 $keyList = $InfoFieldList[2].' as rowid';
8630 }
8631
8632 $fields_label = explode('|', $InfoFieldList[1]);
8633 if (is_array($fields_label)) {
8634 $keyList .= ', ';
8635 $keyList .= implode(', ', $fields_label);
8636 }
8637
8638 $filter_categorie = false;
8639 if (count($InfoFieldList) > 5) {
8640 if ($InfoFieldList[0] == 'categorie') {
8641 $filter_categorie = true;
8642 }
8643 }
8644
8645 $sql = "SELECT ".$keyList;
8646 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
8647 if (strpos($InfoFieldList[4], 'extra') !== false) {
8648 $sql .= ' as main';
8649 }
8650 // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
8651 // $sql.= ' AND entity = '.$conf->entity;
8652
8653 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
8654 $resql = $this->db->query($sql);
8655 if ($resql) {
8656 if (!$filter_categorie) {
8657 $value = ''; // value was used, so now we reset it to use it to build final output
8658 $toprint = array();
8659 while ($obj = $this->db->fetch_object($resql)) {
8660 // Several field into label (eq table:code|libelle:rowid)
8661 $fields_label = explode('|', $InfoFieldList[1]);
8662 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8663 if (is_array($fields_label) && count($fields_label) > 1) {
8664 foreach ($fields_label as $field_toshow) {
8665 $translabel = '';
8666 if (!empty($obj->$field_toshow)) {
8667 $translabel = $langs->trans($obj->$field_toshow);
8668 }
8669 if ($translabel != $field_toshow) {
8670 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
8671 } else {
8672 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
8673 }
8674 }
8675 } else {
8676 $translabel = '';
8677 if (!empty($obj->{$InfoFieldList[1]})) {
8678 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8679 }
8680 if ($translabel != $obj->{$InfoFieldList[1]}) {
8681 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
8682 } else {
8683 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
8684 }
8685 }
8686 }
8687 }
8688 } else {
8689 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
8690
8691 $toprint = array();
8692 while ($obj = $this->db->fetch_object($resql)) {
8693 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8694 $c = new Categorie($this->db);
8695 $c->fetch($obj->rowid);
8696 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
8697 foreach ($ways as $way) {
8698 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
8699 }
8700 }
8701 }
8702 }
8703 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
8704 } else {
8705 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8706 }
8707 } elseif ($type == 'link') {
8708 $out = '';
8709
8710 // only if something to display (perf)
8711 if ($value) {
8712 $param_list = array_keys($param['options']);
8713 // Example: $param_list='ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
8714 // Example: $param_list='ObjectClass:PathToClass:#getnomurlparam1=-1#getnomurlparam2=customer'
8715
8716 $InfoFieldList = explode(":", $param_list[0]);
8717
8718 $classname = $InfoFieldList[0];
8719 $classpath = $InfoFieldList[1];
8720
8721 // Set $getnomurlparam1 et getnomurlparam2
8722 $getnomurlparam = 3;
8723 $getnomurlparam2 = '';
8724 $regtmp = array();
8725 if (preg_match('/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8726 $getnomurlparam = $regtmp[1];
8727 }
8728 if (preg_match('/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8729 $getnomurlparam2 = $regtmp[1];
8730 }
8731
8732 if (!empty($classpath)) {
8733 dol_include_once($InfoFieldList[1]);
8734
8735 if ($classname && !class_exists($classname)) {
8736 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
8737 // TODO use newObjectByElement() introduce in V20 by PR #30036 for better errors management
8738 $element_prop = getElementProperties($classname);
8739 if ($element_prop) {
8740 $classname = $element_prop['classname'];
8741 }
8742 }
8743
8744
8745 if ($classname && class_exists($classname)) {
8746 $object = new $classname($this->db);
8747 '@phan-var-force CommonObject $object';
8748 if ($object->element === 'product') { // Special case for product because default valut of fetch are wrong
8749 '@phan-var-force Product $object';
8750 $result = $object->fetch($value, '', '', '', 0, 1, 1);
8751 } else {
8752 $result = $object->fetch($value);
8753 }
8754 if ($result > 0) {
8755 if ($object->element === 'product') {
8756 '@phan-var-force Product $object';
8757 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
8758 if (isset($val['get_name_url_params'])) {
8759 $get_name_url_params = explode(':', $val['get_name_url_params']);
8760 if (!empty($get_name_url_params)) {
8761 $param_num_max = count($get_name_url_param_arr) - 1;
8762 foreach ($get_name_url_params as $param_num => $param_value) {
8763 if ($param_num > $param_num_max) {
8764 break;
8765 }
8766 $get_name_url_param_arr[$param_num] = $param_value;
8767 }
8768 }
8769 }
8770
8774 $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]);
8775 } else {
8776 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
8777 }
8778 } else {
8779 $value = '';
8780 }
8781 }
8782 } else {
8783 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
8784 return 'Error bad setup of extrafield';
8785 }
8786 } else {
8787 $value = '';
8788 }
8789 } elseif ($type == 'password') {
8790 $value = '<span class="opacitymedium">'.$langs->trans("Encrypted").'</span>';
8791 //$value = preg_replace('/./i', '*', $value);
8792 } elseif ($type == 'array') {
8793 if (is_array($value)) {
8794 $value = implode('<br>', $value);
8795 } else {
8796 dol_syslog(__METHOD__.' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
8797 return 'Error unexpected result from code evaluation';
8798 }
8799 } else { // text|html|varchar
8800 if (!empty($value) && preg_match('/^text/', (string) $type) && !preg_match('/search_/', $keyprefix) && !empty($param['options'])) {
8801 $value = str_replace(',', "\n", $value);
8802 }
8803 $value = dol_htmlentitiesbr($value);
8804 }
8805
8806 //print $type.'-'.$size.'-'.$value;
8807 $out = $value;
8808
8809 return is_null($out) ? '' : $out;
8810 }
8811
8818 public function clearFieldError($fieldKey)
8819 {
8820 $this->error = '';
8821 unset($this->validateFieldsErrors[$fieldKey]);
8822 }
8823
8831 public function setFieldError($fieldKey, $msg = '')
8832 {
8833 global $langs;
8834 if (empty($msg)) {
8835 $msg = $langs->trans("UnknownError");
8836 }
8837
8838 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
8839 }
8840
8847 public function getFieldError($fieldKey)
8848 {
8849 if (!empty($this->validateFieldsErrors[$fieldKey])) {
8850 return $this->validateFieldsErrors[$fieldKey];
8851 }
8852 return '';
8853 }
8854
8863 public function validateField($fields, $fieldKey, $fieldValue)
8864 {
8865 global $langs;
8866
8867 if (!class_exists('Validate')) {
8868 require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
8869 }
8870
8871 $this->clearFieldError($fieldKey);
8872
8873 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
8874 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
8875 return false;
8876 }
8877
8878 $val = $fields[$fieldKey];
8879
8880 $param = array();
8881 $param['options'] = array();
8882 $type = $val['type'];
8883
8884 $required = false;
8885 if (isset($val['notnull']) && $val['notnull'] === 1) {
8886 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
8887 $required = true;
8888 }
8889
8890 $maxSize = 0;
8891 $minSize = 0;
8892
8893 //
8894 // PREPARE Elements
8895 //
8896 $reg = array();
8897
8898 // Convert var to be able to share same code than showOutputField of extrafields
8899 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8900 $type = 'varchar'; // convert varchar(xx) int varchar
8901 $maxSize = $reg[1];
8902 } elseif (preg_match('/varchar/', $type)) {
8903 $type = 'varchar'; // convert varchar(xx) int varchar
8904 }
8905
8906 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8907 $type = 'select';
8908 }
8909
8910 if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8911 $type = 'link';
8912 }
8913
8914 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8915 $param['options'] = $val['arrayofkeyval'];
8916 }
8917
8918 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8919 $type = 'link';
8920 $param['options'] = array($reg[1].':'.$reg[2] => $reg[1].':'.$reg[2]);
8921 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8922 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8923 $type = 'sellist';
8924 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8925 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8926 $type = 'sellist';
8927 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8928 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8929 $type = 'sellist';
8930 }
8931
8932 //
8933 // TEST Value
8934 //
8935
8936 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
8937 $validate = new Validate($this->db, $langs);
8938
8939
8940 // little trick : to perform tests with good performances sort tests by quick to low
8941
8942 //
8943 // COMMON TESTS
8944 //
8945
8946 // Required test and empty value
8947 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8948 $this->setFieldError($fieldKey, $validate->error);
8949 return false;
8950 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8951 // if no value sent and the field is not mandatory, no need to perform tests
8952 return true;
8953 }
8954
8955 // MAX Size test
8956 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8957 $this->setFieldError($fieldKey, $validate->error);
8958 return false;
8959 }
8960
8961 // MIN Size test
8962 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8963 $this->setFieldError($fieldKey, $validate->error);
8964 return false;
8965 }
8966
8967 //
8968 // TESTS for TYPE
8969 //
8970
8971 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
8972 if (!$validate->isTimestamp($fieldValue)) {
8973 $this->setFieldError($fieldKey, $validate->error);
8974 return false;
8975 } else {
8976 return true;
8977 }
8978 } elseif ($type == 'duration') {
8979 if (!$validate->isDuration($fieldValue)) {
8980 $this->setFieldError($fieldKey, $validate->error);
8981 return false;
8982 } else {
8983 return true;
8984 }
8985 } elseif (in_array($type, array('double', 'real', 'price'))) {
8986 // is numeric
8987 if (!$validate->isNumeric($fieldValue)) {
8988 $this->setFieldError($fieldKey, $validate->error);
8989 return false;
8990 } else {
8991 return true;
8992 }
8993 } elseif ($type == 'boolean') {
8994 if (!$validate->isBool($fieldValue)) {
8995 $this->setFieldError($fieldKey, $validate->error);
8996 return false;
8997 } else {
8998 return true;
8999 }
9000 } elseif ($type == 'mail') {
9001 if (!$validate->isEmail($fieldValue)) {
9002 $this->setFieldError($fieldKey, $validate->error);
9003 return false;
9004 }
9005 } elseif ($type == 'url') {
9006 if (!$validate->isUrl($fieldValue)) {
9007 $this->setFieldError($fieldKey, $validate->error);
9008 return false;
9009 } else {
9010 return true;
9011 }
9012 } elseif ($type == 'phone') {
9013 if (!$validate->isPhone($fieldValue)) {
9014 $this->setFieldError($fieldKey, $validate->error);
9015 return false;
9016 } else {
9017 return true;
9018 }
9019 } elseif ($type == 'select' || $type == 'radio') {
9020 if (!isset($param['options'][$fieldValue])) {
9021 $this->error = $langs->trans('RequireValidValue');
9022 return false;
9023 } else {
9024 return true;
9025 }
9026 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
9027 $param_list = array_keys($param['options']);
9028 $InfoFieldList = explode(":", $param_list[0]);
9029 $value_arr = explode(',', $fieldValue);
9030 $value_arr = array_map(array($this->db, 'escape'), $value_arr);
9031
9032 $selectkey = "rowid";
9033 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
9034 $selectkey = $InfoFieldList[2];
9035 }
9036
9037 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
9038 $this->setFieldError($fieldKey, $validate->error);
9039 return false;
9040 } else {
9041 return true;
9042 }
9043 } elseif ($type == 'link') {
9044 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
9045 $InfoFieldList = explode(":", $param_list[0]);
9046 $classname = $InfoFieldList[0];
9047 $classpath = $InfoFieldList[1];
9048 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
9049 $lastIsFetchableError = $validate->error;
9050
9051 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
9052 if ($validate->isFetchableElement($fieldValue, $classname)) {
9053 return true;
9054 }
9055
9056 $this->setFieldError($fieldKey, $lastIsFetchableError);
9057 return false;
9058 } else {
9059 return true;
9060 }
9061 }
9062
9063 // if no test failed all is ok
9064 return true;
9065 }
9066
9080 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = '', $display_type = 'card')
9081 {
9082 global $db, $conf, $langs, $action, $form, $hookmanager;
9083
9084 if (!is_object($form)) {
9085 $form = new Form($db);
9086 }
9087 if (!is_object($extrafields)) {
9088 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
9089 return 'Bad parameter extrafields for showOptionals';
9090 }
9091 if (!is_array($extrafields->attributes[$this->table_element])) {
9092 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
9093 }
9094
9095 $out = '';
9096
9097 $parameters = array('mode' => $mode, 'params' => $params, 'keysuffix' => $keysuffix, 'keyprefix' => $keyprefix, 'display_type' => $display_type);
9098 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
9099
9100 if (empty($reshook)) {
9101 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) {
9102 $out .= "\n";
9103 $out .= '<!-- commonobject:showOptionals --> ';
9104 $out .= "\n";
9105
9106 $nbofextrafieldsshown = 0;
9107 $e = 0; // var to manage the modulo (odd/even)
9108
9109 $lastseparatorkeyfound = '';
9110 $extrafields_collapse_num = '';
9111 $extrafields_collapse_num_old = '';
9112 $i = 0;
9113
9114 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
9115 $i++;
9116
9117 // Show only the key field in params @phan-suppress-next-line PhanTypeArraySuspiciousNullable
9118 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
9119 continue;
9120 }
9121
9122 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
9123 $enabled = 1;
9124 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
9125 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
9126 }
9127 if (empty($enabled)) {
9128 continue;
9129 }
9130
9131 $visibility = 1;
9132 if (isset($extrafields->attributes[$this->table_element]['list'][$key])) {
9133 $visibility = (int) dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
9134 }
9135
9136 $perms = 1;
9137 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
9138 $perms = (int) dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
9139 }
9140
9141 if (($mode == 'create') && !in_array(abs($visibility), array(1, 3))) {
9142 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
9143 } elseif (($mode == 'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9144 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
9145 } elseif ($mode == 'view' && empty($visibility)) {
9146 continue;
9147 }
9148 if (empty($perms)) {
9149 continue;
9150 }
9151
9152 // Load language if required
9153 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
9154 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
9155 }
9156
9157 $colspan = 0;
9158 $value = null;
9159 if (is_array($params) && count($params) > 0 && $display_type == 'card') {
9160 if (array_key_exists('cols', $params)) {
9161 $colspan = $params['cols'];
9162 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
9163 $reg = array();
9164 if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
9165 $colspan = $reg[1];
9166 } else {
9167 $colspan = $params['colspan'];
9168 }
9169 }
9170 }
9171 $colspan = intval($colspan);
9172
9173 switch ($mode) {
9174 case "view":
9175 $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
9176 break;
9177 case "create":
9178 case "edit":
9179 // We get the value of property found with GETPOST so it takes into account:
9180 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
9181 $check = 'alphanohtml';
9182 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
9183 $check = 'restricthtml';
9184 }
9185 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
9186 // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
9187 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
9188 if (is_array($getposttemp)) {
9189 // $getposttemp is an array but following code expects a comma separated string
9190 $value = implode(",", $getposttemp);
9191 } else {
9192 $value = $getposttemp;
9193 }
9194 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('int'))) {
9195 $value = (!empty($this->array_options["options_".$key]) || (isset($this->array_options["options_".$key]) && $this->array_options["options_".$key] === '0')) ? $this->array_options["options_".$key] : '';
9196 } else {
9197 $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.
9198 }
9199 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
9200 break;
9201 }
9202
9203 $nbofextrafieldsshown++;
9204
9205 // Output value of the current field
9206 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
9207 $extrafields_collapse_num = $key;
9208 /*
9209 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
9210 if (!empty($extrafield_param) && is_array($extrafield_param)) {
9211 $extrafield_param_list = array_keys($extrafield_param['options']);
9212
9213 if (count($extrafield_param_list) > 0) {
9214 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
9215
9216 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
9217 //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
9218 $extrafields_collapse_num = $key;
9219 }
9220 }
9221 }
9222 */
9223
9224 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
9225 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9226
9227 $lastseparatorkeyfound = $key;
9228 } else {
9229 $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
9230
9231 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
9232 $csstyle = '';
9233 if (is_array($params) && count($params) > 0) {
9234 if (array_key_exists('class', $params)) {
9235 $class .= $params['class'].' ';
9236 }
9237 if (array_key_exists('style', $params)) {
9238 $csstyle = $params['style'];
9239 }
9240 }
9241
9242 // add html5 elements
9243 $domData = ' data-element="extrafield"';
9244 $domData .= ' data-targetelement="'.$this->element.'"';
9245 $domData .= ' data-targetid="'.$this->id.'"';
9246
9247 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
9248 if ($display_type == 'card') {
9249 if (getDolGlobalString('MAIN_EXTRAFIELDS_USE_TWO_COLUMS') && ($e % 2) == 0) {
9250 $colspan = 0;
9251 }
9252
9253 if ($action == 'selectlines') {
9254 $colspan++;
9255 }
9256 }
9257
9258 // Convert date into timestamp format (value in memory must be a timestamp)
9259 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
9260 $datenotinstring = null;
9261 if (array_key_exists('options_'.$key, $this->array_options)) {
9262 $datenotinstring = $this->array_options['options_'.$key];
9263 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
9264 $datenotinstring = $this->db->jdate($datenotinstring);
9265 }
9266 }
9267 $datekey = $keyprefix.'options_'.$key.$keysuffix;
9268 $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOSTINT($datekey.'month', 3), GETPOSTINT($datekey.'day', 3), GETPOSTINT($datekey.'year', 3)) : $datenotinstring;
9269 }
9270 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
9271 $datenotinstring = null;
9272 if (array_key_exists('options_'.$key, $this->array_options)) {
9273 $datenotinstring = $this->array_options['options_'.$key];
9274 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
9275 $datenotinstring = $this->db->jdate($datenotinstring);
9276 }
9277 }
9278 $timekey = $keyprefix.'options_'.$key.$keysuffix;
9279 $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;
9280 }
9281 // Convert float submitted string into real php numeric (value in memory must be a php numeric)
9282 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
9283 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
9284 $value = price2num($value);
9285 } elseif (isset($this->array_options['options_'.$key])) {
9286 $value = $this->array_options['options_'.$key];
9287 }
9288 }
9289
9290 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
9291 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'radio', 'int', 'boolean'))) {
9292 if ($action == 'create' || $mode == 'create') {
9293 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
9294 }
9295 }
9296
9297 $labeltoshow = $langs->trans($label);
9298 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
9299 if ($display_type == 'card') {
9300 $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9301 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER') && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
9302 $out .= '<td></td>';
9303 }
9304 $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldmax45' : $params['tdclass']).' wordbreak';
9305 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'text') {
9306 $out .= ' tdtop';
9307 }
9308 } elseif ($display_type == 'line') {
9309 $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9310 $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
9311 }
9312 //$out .= "titlefield";
9313 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
9314 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
9315 $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
9316 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
9317 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9318 $out .= ' fieldrequired';
9319 }
9320 }
9321 $out .= '">';
9322 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
9323 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9324 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9325 } else {
9326 $out .= $labeltoshow;
9327 }
9328 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9329 $out .= '&nbsp;<span style="color: red">*</span>';
9330 }
9331 } else {
9332 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9333 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9334 } else {
9335 $out .= $labeltoshow;
9336 }
9337 }
9338
9339 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9340
9341 // Second column
9342 $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
9343 if ($display_type == 'card') {
9344 // 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
9345 $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key;
9346 $out .= '" '.($colspan ? ' colspan="'.$colspan.'"' : '');
9347 $out .= '>';
9348 } elseif ($display_type == 'line') {
9349 $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].'">';
9350 }
9351
9352 switch ($mode) {
9353 case "view":
9354 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
9355 break;
9356 case "create":
9357 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICTO', 'email,phone,ip,password'));
9358 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9359 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9360 }
9361 //$out .= '<!-- type = '.$extrafields->attributes[$this->table_element]['type'][$key].' -->';
9362 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
9363 break;
9364 case "edit":
9365 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICTO', 'email,phone,ip,password'));
9366 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9367 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9368 }
9369 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
9370 break;
9371 }
9372
9373 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9374 $out .= ($display_type == 'card' ? '</tr>'."\n" : '</div>');
9375 $e++;
9376 }
9377 }
9378 $out .= "\n";
9379 // Add code to manage list depending on others
9380 if (!empty($conf->use_javascript_ajax)) {
9381 $out .= $this->getJSListDependancies();
9382 }
9383
9384 $out .= '<!-- commonobject:showOptionals end --> '."\n";
9385
9386 if (empty($nbofextrafieldsshown)) {
9387 $out = '';
9388 }
9389 }
9390 }
9391
9392 $out .= $hookmanager->resPrint;
9393
9394 return $out;
9395 }
9396
9401 public function getJSListDependancies($type = '_extra')
9402 {
9403 $out = '
9404 <script nonce="'.getNonce().'">
9405 jQuery(document).ready(function() {
9406 function showOptions'.$type.'(child_list, parent_list, orig_select)
9407 {
9408 var val = $("select[name=\""+parent_list+"\"]").val();
9409 var parentVal = parent_list + ":" + val;
9410 if(typeof val == "string"){
9411 if(val != "") {
9412 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9413 $("select[name=\""+child_list+"\"] option[parent]").remove();
9414 $("select[name=\""+child_list+"\"]").append(options);
9415 } else {
9416 var options = orig_select.find("option[parent]").clone();
9417 $("select[name=\""+child_list+"\"] option[parent]").remove();
9418 $("select[name=\""+child_list+"\"]").append(options);
9419 }
9420 } else if(val > 0) {
9421 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9422 $("select[name=\""+child_list+"\"] option[parent]").remove();
9423 $("select[name=\""+child_list+"\"]").append(options);
9424 } else {
9425 var options = orig_select.find("option[parent]").clone();
9426 $("select[name=\""+child_list+"\"] option[parent]").remove();
9427 $("select[name=\""+child_list+"\"]").append(options);
9428 }
9429 }
9430 function setListDependencies'.$type.'() {
9431 jQuery("select option[parent]").parent().each(function() {
9432 var orig_select = {};
9433 var child_list = $(this).attr("name");
9434 orig_select[child_list] = $(this).clone();
9435 var parent = $(this).find("option[parent]:first").attr("parent");
9436 var infos = parent.split(":");
9437 var parent_list = infos[0];
9438
9439 //Hide daughters lists
9440 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9441 $("#"+child_list).hide();
9442 //Show mother lists
9443 } else if ($("#"+parent_list).val() != 0){
9444 $("#"+parent_list).show();
9445 }
9446 //Show the child list if the parent list value is selected
9447 $("select[name=\""+parent_list+"\"]").click(function() {
9448 if ($(this).val() != 0){
9449 $("#"+child_list).show()
9450 }
9451 });
9452
9453 //When we change parent list
9454 $("select[name=\""+parent_list+"\"]").change(function() {
9455 showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
9456 //Select the value 0 on child list after a change on the parent list
9457 $("#"+child_list).val(0).trigger("change");
9458 //Hide child lists if the parent value is set to 0
9459 if ($(this).val() == 0){
9460 $("#"+child_list).hide();
9461 }
9462 });
9463 });
9464 }
9465
9466 setListDependencies'.$type.'();
9467 });
9468 </script>'."\n";
9469 return $out;
9470 }
9471
9477 public function getRights()
9478 {
9479 global $user;
9480
9481 $module = empty($this->module) ? '' : $this->module;
9482 $element = $this->element;
9483
9484 if ($element == 'facturerec') {
9485 $element = 'facture';
9486 } elseif ($element == 'invoice_supplier_rec') {
9487 return !$user->hasRight('fournisseur', 'facture') ? null : $user->hasRight('fournisseur', 'facture');
9488 } elseif ($module && $user->hasRight($module, $element)) {
9489 // for modules built with ModuleBuilder
9490 return $user->hasRight($module, $element);
9491 }
9492
9493 return $user->rights->$element;
9494 }
9495
9508 public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
9509 {
9510 global $hookmanager;
9511
9512 $parameters = array(
9513 'origin_id' => $origin_id,
9514 'dest_id' => $dest_id,
9515 'tables' => $tables,
9516 );
9517 $reshook = $hookmanager->executeHooks('commonReplaceThirdparty', $parameters);
9518 if ($reshook) {
9519 return true; // replacement code
9520 } elseif ($reshook < 0) {
9521 return $ignoreerrors === 1; // failure
9522 } // reshook = 0 => execute normal code
9523
9524 foreach ($tables as $table) {
9525 $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
9526
9527 if (!$dbs->query($sql)) {
9528 if ($ignoreerrors) {
9529 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.
9530 }
9531 //$this->errors = $db->lasterror();
9532 return false;
9533 }
9534 }
9535
9536 return true;
9537 }
9538
9551 public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
9552 {
9553 foreach ($tables as $table) {
9554 $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
9555
9556 if (!$dbs->query($sql)) {
9557 if ($ignoreerrors) {
9558 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.
9559 }
9560 //$this->errors = $db->lasterror();
9561 return false;
9562 }
9563 }
9564
9565 return true;
9566 }
9567
9580 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9581 {
9582 global $conf;
9583
9584 $buyPrice = 0;
9585
9586 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && getDolGlobalInt('ForceBuyingPriceIfNull') > 0)) {
9587 // When ForceBuyingPriceIfNull is set
9588 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9589 } else {
9590 // Get cost price for margin calculation
9591 if (!empty($fk_product) && $fk_product > 0) {
9592 $result = 0;
9593 if (getDolGlobalString('MARGIN_TYPE') == 'costprice') {
9594 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
9595 $product = new Product($this->db);
9596 $result = $product->fetch($fk_product);
9597 if ($result <= 0) {
9598 $this->errors[] = 'ErrorProductIdDoesNotExists';
9599 return -1;
9600 }
9601 if ($product->cost_price > 0) {
9602 $buyPrice = $product->cost_price;
9603 } elseif ($product->pmp > 0) {
9604 $buyPrice = $product->pmp;
9605 }
9606 } elseif (getDolGlobalString('MARGIN_TYPE') == 'pmp') {
9607 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
9608 $product = new Product($this->db);
9609 $result = $product->fetch($fk_product);
9610 if ($result <= 0) {
9611 $this->errors[] = 'ErrorProductIdDoesNotExists';
9612 return -1;
9613 }
9614 if ($product->pmp > 0) {
9615 $buyPrice = $product->pmp;
9616 }
9617 }
9618
9619 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
9620 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
9621 $productFournisseur = new ProductFournisseur($this->db);
9622 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9623 $buyPrice = $productFournisseur->fourn_unitprice;
9624 } elseif ($result < 0) {
9625 $this->errors[] = $productFournisseur->error;
9626 return -2;
9627 }
9628 }
9629 }
9630 }
9631 return $buyPrice;
9632 }
9633
9641 public function getDataToShowPhoto($modulepart, $imagesize)
9642 {
9643 // See getDataToShowPhoto() implemented by Product for example.
9644 return array('dir' => '', 'file' => '', 'originalfile' => '', 'altfile' => '', 'email' => '', 'capture' => '');
9645 }
9646
9647
9648 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
9668 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')
9669 {
9670 // phpcs:enable
9671 global $user, $langs;
9672
9673 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
9674 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
9675
9676 $sortfield = 'position_name';
9677 $sortorder = 'asc';
9678
9679 $dir = $sdir.'/';
9680 $pdir = '/';
9681
9682 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
9683 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
9684
9685 // For backward compatibility
9686 if ($modulepart == 'product') {
9687 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
9688 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9689 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9690 }
9691 }
9692 if ($modulepart == 'category') {
9693 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9694 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9695 }
9696
9697 // Defined relative dir to DOL_DATA_ROOT
9698 $relativedir = '';
9699 if ($dir) {
9700 $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
9701 $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
9702 $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
9703 }
9704
9705 $dirthumb = $dir.'thumbs/';
9706 $pdirthumb = $pdir.'thumbs/';
9707
9708 $return = '<!-- Photo -->'."\n";
9709 $nbphoto = 0;
9710
9711 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
9712
9713 /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatibility, we scan also old dirs
9714 {
9715 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
9716 $filearray=array_merge($filearray, $filearrayold);
9717 }*/
9718
9719 completeFileArrayWithDatabaseInfo($filearray, $relativedir);
9720
9721 if (count($filearray)) {
9722 if ($sortfield && $sortorder) {
9723 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
9724 }
9725
9726 foreach ($filearray as $key => $val) {
9727 $photo = '';
9728 $file = $val['name'];
9729
9730 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
9731 if (image_format_supported($file) >= 0) {
9732 $nbphoto++;
9733 $photo = $file;
9734 $viewfilename = $file;
9735
9736 if ($size == 1 || $size == 'small') { // Format vignette
9737 // Find name of thumb file
9738 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
9739 if (!dol_is_file($dirthumb.$photo_vignette)) {
9740 // The thumb does not exists, so we will use the original file
9741 $dirthumb = $dir;
9742 $pdirthumb = $pdir;
9743 $photo_vignette = basename($file);
9744 }
9745
9746 // Get filesize of original file
9747 $imgarray = dol_getImageSize($dir.$photo);
9748
9749 if ($nbbyrow > 0) {
9750 if ($nbphoto == 1) {
9751 $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
9752 }
9753
9754 if ($nbphoto % $nbbyrow == 1) {
9755 $return .= '<tr class="center valignmiddle" style="border: 1px">';
9756 }
9757 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
9758 } elseif ($nbbyrow < 0) {
9759 $return .= '<div class="inline-block">'."\n";
9760 }
9761
9762 $relativefile = preg_replace('/^\//', '', $pdir.$photo);
9763 if (empty($nolink)) {
9764 $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
9765 if ($urladvanced) {
9766 $return .= '<a href="'.$urladvanced.'">';
9767 } else {
9768 $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
9769 }
9770 }
9771
9772 // Show image (width height=$maxHeight)
9773 // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
9774 $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
9775 $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
9776 if ($overwritetitle) {
9777 if (is_numeric($overwritetitle)) {
9778 $alt = '';
9779 } else {
9780 $alt = $overwritetitle;
9781 }
9782 }
9783 if (empty($cache) && !empty($val['label'])) {
9784 // label is md5 of file
9785 // use it in url to say we want to cache this version of the file
9786 $cache = $val['label'];
9787 }
9788 if ($usesharelink) {
9789 if (array_key_exists('share', $val) && $val['share']) {
9790 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
9791 $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
9792 $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).'">';
9793 } else {
9794 $return .= '<!-- Show original file -->';
9795 $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).'">';
9796 }
9797 } else {
9798 $return .= '<!-- Show nophoto file (because file is not shared) -->';
9799 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
9800 }
9801 } else {
9802 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
9803 $return .= '<!-- Show thumb -->';
9804 $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).'">';
9805 } else {
9806 $return .= '<!-- Show original file -->';
9807 $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).'">';
9808 }
9809 }
9810
9811 if (empty($nolink)) {
9812 $return .= '</a>';
9813 }
9814
9815 if ($showfilename) {
9816 $return .= '<br>'.$viewfilename;
9817 }
9818 if ($showaction) {
9819 $return .= '<br>';
9820 // If $photo_vignette set, we add a link to generate thumbs if file is an image and width or height higher than limits
9821 if ($photo_vignette && (image_format_supported($photo) > 0) && ((isset($imgarray['width']) && $imgarray['width'] > $maxWidth) || (isset($imgarray['width']) && $imgarray['width'] > $maxHeight))) {
9822 $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>';
9823 }
9824 // Special case for product
9825 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
9826 // Link to resize
9827 $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; ';
9828
9829 // Link to delete
9830 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
9831 $return .= img_delete().'</a>';
9832 }
9833 }
9834 $return .= "\n";
9835
9836 if ($nbbyrow > 0) {
9837 $return .= '</td>';
9838 if (($nbphoto % $nbbyrow) == 0) {
9839 $return .= '</tr>';
9840 }
9841 } elseif ($nbbyrow < 0) {
9842 $return .= '</div>'."\n";
9843 }
9844 }
9845
9846 if (empty($size)) { // Format origine
9847 $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
9848
9849 if ($showfilename) {
9850 $return .= '<br>'.$viewfilename;
9851 }
9852 if ($showaction) {
9853 // Special case for product
9854 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
9855 // Link to resize
9856 $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; ';
9857
9858 // Link to delete
9859 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
9860 $return .= img_delete().'</a>';
9861 }
9862 }
9863 }
9864
9865 // On continue ou on arrete de boucler ?
9866 if ($nbmax && $nbphoto >= $nbmax) {
9867 break;
9868 }
9869 }
9870 }
9871
9872 if ($size == 1 || $size == 'small') {
9873 if ($nbbyrow > 0) {
9874 // Ferme tableau
9875 while ($nbphoto % $nbbyrow) {
9876 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
9877 $nbphoto++;
9878 }
9879
9880 if ($nbphoto) {
9881 $return .= '</table>';
9882 }
9883 }
9884 }
9885 }
9886
9887 $this->nbphoto = $nbphoto;
9888
9889 return $return;
9890 }
9891
9892
9899 protected function isArray($info)
9900 {
9901 if (is_array($info)) {
9902 if (isset($info['type']) && $info['type'] == 'array') {
9903 return true;
9904 } else {
9905 return false;
9906 }
9907 }
9908 return false;
9909 }
9910
9917 public function isDate($info)
9918 {
9919 if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
9920 return true;
9921 }
9922 return false;
9923 }
9924
9931 public function isDuration($info)
9932 {
9933 if (is_array($info)) {
9934 if (isset($info['type']) && ($info['type'] == 'duration')) {
9935 return true;
9936 } else {
9937 return false;
9938 }
9939 } else {
9940 return false;
9941 }
9942 }
9943
9950 public function isInt($info)
9951 {
9952 if (is_array($info)) {
9953 if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
9954 return true;
9955 } else {
9956 return false;
9957 }
9958 } else {
9959 return false;
9960 }
9961 }
9962
9969 public function isFloat($info)
9970 {
9971 if (is_array($info)) {
9972 if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
9973 return true;
9974 } else {
9975 return false;
9976 }
9977 }
9978 return false;
9979 }
9980
9987 public function isText($info)
9988 {
9989 if (is_array($info)) {
9990 if (isset($info['type']) && $info['type'] == 'text') {
9991 return true;
9992 } else {
9993 return false;
9994 }
9995 }
9996 return false;
9997 }
9998
10005 protected function canBeNull($info)
10006 {
10007 if (is_array($info)) {
10008 if (array_key_exists('notnull', $info) && $info['notnull'] != '1') {
10009 return true;
10010 } else {
10011 return false;
10012 }
10013 }
10014 return true;
10015 }
10016
10023 protected function isForcedToNullIfZero($info)
10024 {
10025 if (is_array($info)) {
10026 if (array_key_exists('notnull', $info) && $info['notnull'] == '-1') {
10027 return true;
10028 } else {
10029 return false;
10030 }
10031 }
10032 return false;
10033 }
10034
10041 protected function isIndex($info)
10042 {
10043 if (is_array($info)) {
10044 if (array_key_exists('index', $info) && $info['index'] == true) {
10045 return true;
10046 } else {
10047 return false;
10048 }
10049 }
10050 return false;
10051 }
10052
10053
10062 protected function setSaveQuery()
10063 {
10064 global $conf;
10065
10066 $queryarray = array();
10067 foreach ($this->fields as $field => $info) { // Loop on definition of fields
10068 // Depending on field type ('datetime', ...)
10069 if ($this->isDate($info)) {
10070 if (empty($this->{$field})) {
10071 $queryarray[$field] = null;
10072 } else {
10073 $queryarray[$field] = $this->db->idate($this->{$field});
10074 }
10075 } elseif ($this->isDuration($info)) {
10076 // $this->{$field} may be null, '', 0, '0', 123, '123'
10077 if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
10078 if (!isset($this->{$field})) {
10079 if (!empty($info['default'])) {
10080 $queryarray[$field] = $info['default'];
10081 } else {
10082 $queryarray[$field] = 0;
10083 }
10084 } else {
10085 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
10086 }
10087 } else {
10088 $queryarray[$field] = null;
10089 }
10090 } elseif ($this->isInt($info) || $this->isFloat($info)) {
10091 if ($field == 'entity' && is_null($this->{$field})) {
10092 $queryarray[$field] = ((int) $conf->entity);
10093 } else {
10094 // $this->{$field} may be null, '', 0, '0', 123, '123'
10095 if ((isset($this->{$field}) && ((string) $this->{$field}) != '') || !empty($info['notnull'])) {
10096 if (!isset($this->{$field})) {
10097 $queryarray[$field] = 0;
10098 } elseif ($this->isInt($info)) {
10099 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
10100 } elseif ($this->isFloat($info)) {
10101 $queryarray[$field] = (float) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
10102 }
10103 } else {
10104 $queryarray[$field] = null;
10105 }
10106 }
10107 } else {
10108 // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
10109 // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
10110 $queryarray[$field] = $this->{$field};
10111 }
10112
10113 if (array_key_exists('type', $info) && $info['type'] == 'timestamp' && empty($queryarray[$field])) {
10114 unset($queryarray[$field]);
10115 }
10116 if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
10117 $queryarray[$field] = null; // May force 0 to null
10118 }
10119 }
10120
10121 return $queryarray;
10122 }
10123
10130 public function setVarsFromFetchObj(&$obj)
10131 {
10132 global $db;
10133
10134 foreach ($this->fields as $field => $info) {
10135 if ($this->isDate($info)) {
10136 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') {
10137 $this->$field = '';
10138 } else {
10139 $this->$field = $db->jdate($obj->$field);
10140 }
10141 } elseif ($this->isInt($info)) {
10142 if ($field == 'rowid') {
10143 $this->id = (int) $obj->$field;
10144 } else {
10145 if ($this->isForcedToNullIfZero($info)) {
10146 if (empty($obj->$field)) {
10147 $this->$field = null;
10148 } else {
10149 $this->$field = (int) $obj->$field;
10150 }
10151 } else {
10152 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
10153 $this->$field = (int) $obj->$field;
10154 } else {
10155 $this->$field = null;
10156 }
10157 }
10158 }
10159 } elseif ($this->isFloat($info)) {
10160 if ($this->isForcedToNullIfZero($info)) {
10161 if (empty($obj->$field)) {
10162 $this->$field = null;
10163 } else {
10164 $this->$field = (float) $obj->$field;
10165 }
10166 } else {
10167 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
10168 $this->$field = (float) $obj->$field;
10169 } else {
10170 $this->$field = null;
10171 }
10172 }
10173 } else {
10174 $this->$field = isset($obj->$field) ? $obj->$field : null;
10175 }
10176 }
10177
10178 // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
10179 if (!isset($this->fields['ref']) && isset($this->id)) {
10180 $this->ref = (string) $this->id;
10181 }
10182 }
10183
10188 public function emtpyObjectVars()
10189 {
10190 foreach ($this->fields as $field => $arr) {
10191 $this->$field = null;
10192 }
10193 }
10194
10202 public function getFieldList($alias = '', $excludefields = array())
10203 {
10204 $keys = array_keys($this->fields);
10205 if (!empty($alias)) {
10206 $keys_with_alias = array();
10207 foreach ($keys as $fieldname) {
10208 if (!empty($excludefields)) {
10209 if (in_array($fieldname, $excludefields)) { // The field is excluded and must not be in output
10210 continue;
10211 }
10212 }
10213 $keys_with_alias[] = $alias . '.' . $fieldname;
10214 }
10215 return implode(',', $keys_with_alias);
10216 } else {
10217 return implode(',', $keys);
10218 }
10219 }
10220
10228 protected function quote($value, $fieldsentry)
10229 {
10230 if (is_null($value)) {
10231 return 'NULL';
10232 } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
10233 return price2num((string) $value);
10234 } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
10235 return (int) $value;
10236 } elseif ($fieldsentry['type'] == 'boolean') {
10237 if ($value) {
10238 return 'true';
10239 } else {
10240 return 'false';
10241 }
10242 } else {
10243 return "'".$this->db->escape($value)."'";
10244 }
10245 }
10246
10247
10255 public function createCommon(User $user, $notrigger = 0)
10256 {
10257 global $langs;
10258
10259 dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
10260
10261 $error = 0;
10262
10263 $now = dol_now();
10264
10265 $fieldvalues = $this->setSaveQuery();
10266
10267 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
10268
10269 if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
10270 $fieldvalues['date_creation'] = $this->db->idate($now);
10271 }
10272 if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
10273 $fieldvalues['fk_user_creat'] = $user->id;
10274 $this->fk_user_creat = $user->id;
10275 }
10276 if (array_key_exists('user_creation_id', $fieldvalues) && !($fieldvalues['user_creation_id'] > 0)) {
10277 $fieldvalues['user_creation_id'] = $user->id;
10278 $this->user_creation_id = $user->id;
10279 }
10280 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass')) {
10281 // @phan-suppress-next-line PhanUndeclaredProperty
10282 $fieldvalues['pass_crypted'] = dol_hash($this->pass);
10283 }
10284 if (array_key_exists('ref', $fieldvalues)) {
10285 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
10286 }
10287
10288 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
10289
10290 $keys = array();
10291 $values = array(); // Array to store string forged for SQL syntax
10292 foreach ($fieldvalues as $k => $v) {
10293 $keys[$k] = $k;
10294 $value = $this->fields[$k];
10295 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10296 $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
10297 }
10298
10299 // Clean and check mandatory
10300 foreach ($keys as $key) {
10301 if (!isset($this->fields[$key])) {
10302 continue;
10303 }
10304 $key_fields = $this->fields[$key];
10305
10306 // If field is an implicit foreign key field (so type = 'integer:...')
10307 if (preg_match('/^integer:/i', $key_fields['type']) && $values[$key] == '-1') {
10308 $values[$key] = '';
10309 }
10310 if (!empty($key_fields['foreignkey']) && $values[$key] == '-1') {
10311 $values[$key] = '';
10312 }
10313
10314 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && (!isset($key_fields['default']) || is_null($key_fields['default']))) {
10315 $error++;
10316 $langs->load("errors");
10317 dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
10318 $this->errors[] = $langs->trans("ErrorFieldRequired", isset($key_fields['label']) ? $key_fields['label'] : $key);
10319 }
10320
10321 // If value is null and there is a default value for field @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10322 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($key_fields['default'])) {
10323 $values[$key] = $this->quote($key_fields['default'], $key_fields);
10324 }
10325
10326 // If field is an implicit foreign key field (so type = 'integer:...')
10327 if (isset($key_fields['type']) && preg_match('/^integer:/i', $key_fields['type']) && empty($values[$key])) {
10328 if (isset($key_fields['default'])) {
10329 $values[$key] = ((int) $key_fields['default']);
10330 } else {
10331 $values[$key] = 'null';
10332 }
10333 }
10334 if (!empty($key_fields['foreignkey']) && empty($values[$key])) {
10335 $values[$key] = 'null';
10336 }
10337 }
10338
10339 if ($error) {
10340 return -1;
10341 }
10342
10343 $this->db->begin();
10344
10345 if (!$error) {
10346 $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
10347 $sql .= " (".implode(", ", $keys).')';
10348 $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
10349
10350 $res = $this->db->query($sql);
10351 if (!$res) {
10352 $error++;
10353 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
10354 $this->errors[] = "ErrorRefAlreadyExists";
10355 } else {
10356 $this->errors[] = $this->db->lasterror();
10357 }
10358 }
10359 }
10360
10361 if (!$error) {
10362 $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10363 }
10364
10365 // If we have a field ref with a default value of (PROV)
10366 if (!$error) {
10367 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10368 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)') {
10369 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
10370 $resqlupdate = $this->db->query($sql);
10371
10372 if ($resqlupdate === false) {
10373 $error++;
10374 $this->errors[] = $this->db->lasterror();
10375 } else {
10376 $this->ref = '(PROV'.$this->id.')';
10377 }
10378 }
10379 }
10380
10381 // Create extrafields
10382 if (!$error) {
10383 $result = $this->insertExtraFields();
10384 if ($result < 0) {
10385 $error++;
10386 }
10387 }
10388
10389 // Create lines
10390 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
10391 foreach ($this->lines as $line) {
10392 $keyforparent = $this->fk_element;
10393 $line->$keyforparent = $this->id;
10394
10395 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
10396 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
10397 if (!is_object($line)) {
10398 $line = (object) $line;
10399 }
10400
10401 $result = 0;
10402 if (method_exists($line, 'insert')) {
10403 $result = $line->insert($user, 1);
10404 } elseif (method_exists($line, 'create')) {
10405 $result = $line->create($user, 1);
10406 }
10407 if ($result < 0) {
10408 $this->error = $line->error;
10409 $this->db->rollback();
10410 return -1;
10411 }
10412 }
10413 }
10414
10415 // Triggers
10416 if (!$error && !$notrigger) {
10417 // Call triggers
10418 $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
10419 if ($result < 0) {
10420 $error++;
10421 }
10422 // End call triggers
10423 }
10424
10425 // Commit or rollback
10426 if ($error) {
10427 $this->db->rollback();
10428 return -1;
10429 } else {
10430 $this->db->commit();
10431 return $this->id;
10432 }
10433 }
10434
10435
10445 public function fetchCommon($id, $ref = null, $morewhere = '', $noextrafields = 0)
10446 {
10447 if (empty($id) && empty($ref) && empty($morewhere)) {
10448 return -1;
10449 }
10450
10451 $fieldlist = $this->getFieldList('t');
10452 if (empty($fieldlist)) {
10453 return 0;
10454 }
10455
10456 $sql = "SELECT ".$fieldlist;
10457 $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
10458
10459 if (!empty($id)) {
10460 $sql .= ' WHERE t.rowid = '.((int) $id);
10461 } elseif (!empty($ref)) {
10462 $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
10463 } else {
10464 $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
10465 }
10466 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10467 $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
10468 }
10469 if ($morewhere) {
10470 $sql .= $morewhere;
10471 }
10472 $sql .= ' LIMIT 1'; // This is a fetch, to be certain to get only one record
10473
10474 $res = $this->db->query($sql);
10475 if ($res) {
10476 $obj = $this->db->fetch_object($res);
10477 if ($obj) {
10478 $this->setVarsFromFetchObj($obj);
10479
10480 // Retrieve all extrafield
10481 // fetch optionals attributes and labels
10482 if (empty($noextrafields)) {
10483 $result = $this->fetch_optionals();
10484 if ($result < 0) {
10485 $this->error = $this->db->lasterror();
10486 $this->errors[] = $this->error;
10487 return -4;
10488 }
10489 }
10490
10491 return $this->id;
10492 } else {
10493 return 0;
10494 }
10495 } else {
10496 $this->error = $this->db->lasterror();
10497 $this->errors[] = $this->error;
10498 return -1;
10499 }
10500 }
10501
10509 public function fetchLinesCommon($morewhere = '', $noextrafields = 0)
10510 {
10511 $objectlineclassname = get_class($this).'Line';
10512 if (!class_exists($objectlineclassname)) {
10513 $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
10514 return -1;
10515 }
10516
10517 $objectline = new $objectlineclassname($this->db);
10518 '@phan-var-force CommonObjectLine $objectline';
10519
10520 $sql = "SELECT ".$objectline->getFieldList('l');
10521 $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
10522 $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
10523 if ($morewhere) {
10524 $sql .= $morewhere;
10525 }
10526 if (isset($objectline->fields['position'])) {
10527 $sql .= $this->db->order('position', 'ASC');
10528 }
10529
10530 $resql = $this->db->query($sql);
10531 if ($resql) {
10532 $num_rows = $this->db->num_rows($resql);
10533 $i = 0;
10534 $this->lines = array();
10535 while ($i < $num_rows) {
10536 $obj = $this->db->fetch_object($resql);
10537 if ($obj) {
10538 $newline = new $objectlineclassname($this->db);
10539 '@phan-var-force CommonObjectLine $newline';
10540 $newline->setVarsFromFetchObj($obj);
10541
10542 // Note: extrafields load of line not yet supported
10543 /*
10544 if (empty($noextrafields)) {
10545 // Load extrafields of line
10546 }*/
10547
10548 $this->lines[] = $newline;
10549 }
10550 $i++;
10551 }
10552
10553 return 1;
10554 } else {
10555 $this->error = $this->db->lasterror();
10556 $this->errors[] = $this->error;
10557 return -1;
10558 }
10559 }
10560
10568 public function updateCommon(User $user, $notrigger = 0)
10569 {
10570 dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
10571
10572 $error = 0;
10573
10574 $now = dol_now();
10575
10576 // $this->oldcopy should have been set by the caller of update
10577 //if (empty($this->oldcopy)) {
10578 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
10579 // $this->oldcopy = dol_clone($this, 2);
10580 //}
10581
10582 $fieldvalues = $this->setSaveQuery();
10583
10584 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
10585
10586 if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
10587 $fieldvalues['date_modification'] = $this->db->idate($now);
10588 }
10589 if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
10590 $fieldvalues['fk_user_modif'] = $user->id;
10591 }
10592 if (array_key_exists('user_modification_id', $fieldvalues) && !($fieldvalues['user_modification_id'] > 0)) {
10593 $fieldvalues['user_modification_id'] = $user->id;
10594 }
10595 if (array_key_exists('ref', $fieldvalues)) {
10596 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
10597 }
10598
10599 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
10600
10601 // Add quotes and escape on fields with type string
10602 $keys = array();
10603 $values = array();
10604 $tmp = array();
10605 foreach ($fieldvalues as $k => $v) {
10606 $keys[$k] = $k;
10607 $value = $this->fields[$k];
10608 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10609 $values[$k] = $this->quote($v, $value);
10610 if (($value["type"] == "text") && !empty($value['arrayofkeyval']) && is_array($value['arrayofkeyval'])) {
10611 // Clean values for text with selectbox
10612 $v = preg_replace('/\s/', ',', $v);
10613 $v = preg_replace('/,+/', ',', $v);
10614 }
10615 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10616 $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
10617 }
10618
10619 // Clean and check mandatory fields
10620 foreach ($keys as $key) {
10621 if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
10622 $values[$key] = ''; // This is an implicit foreign key field
10623 }
10624 if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
10625 $values[$key] = ''; // This is an explicit foreign key field
10626 }
10627
10628 //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
10629 /*
10630 if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
10631 {
10632 $error++;
10633 $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
10634 }*/
10635 }
10636
10637 $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
10638
10639 $this->db->begin();
10640
10641 if (!$error) {
10642 $res = $this->db->query($sql);
10643 if (!$res) {
10644 $error++;
10645 $this->errors[] = $this->db->lasterror();
10646 }
10647 }
10648
10649 // Update extrafield
10650 if (!$error) {
10651 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
10652 if ($result < 0) {
10653 $error++;
10654 }
10655 }
10656
10657 // Triggers
10658 if (!$error && !$notrigger) {
10659 // Call triggers
10660 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
10661 if ($result < 0) {
10662 $error++;
10663 } //Do also here what you must do to rollback action if trigger fail
10664 // End call triggers
10665 }
10666
10667 // Commit or rollback
10668 if ($error) {
10669 $this->db->rollback();
10670 return -1;
10671 } else {
10672 $this->db->commit();
10673 return $this->id;
10674 }
10675 }
10676
10685 public function deleteCommon(User $user, $notrigger = 0, $forcechilddeletion = 0)
10686 {
10687 dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
10688
10689 $error = 0;
10690
10691 $this->db->begin();
10692
10693 if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
10694 foreach ($this->childtables as $table) {
10695 $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
10696 $resql = $this->db->query($sql);
10697 if (!$resql) {
10698 $this->error = $this->db->lasterror();
10699 $this->errors[] = $this->error;
10700 $this->db->rollback();
10701 return -1;
10702 }
10703 }
10704 } elseif (!empty($this->childtables)) { // If object has children linked with a foreign key field, we check all child tables.
10705 $objectisused = $this->isObjectUsed($this->id);
10706 if (!empty($objectisused)) {
10707 dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10708 $this->error = 'ErrorRecordHasChildren';
10709 $this->errors[] = $this->error;
10710 $this->db->rollback();
10711 return 0;
10712 }
10713 }
10714
10715 // Delete cascade first
10716 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10717 foreach ($this->childtablesoncascade as $tabletodelete) {
10718 $deleteFromObject = explode(':', $tabletodelete, 4);
10719 if (count($deleteFromObject) >= 2) {
10720 $className = str_replace('@', '', $deleteFromObject[0]);
10721 $filePath = $deleteFromObject[1];
10722 $columnName = $deleteFromObject[2];
10723 $filter = '';
10724 if (!empty($deleteFromObject[3])) {
10725 $filter = $deleteFromObject[3];
10726 }
10727 if (dol_include_once($filePath)) {
10728 $childObject = new $className($this->db);
10729 if (method_exists($childObject, 'deleteByParentField')) {
10730 '@phan-var-force CommonObject $childObject';
10731 $result = $childObject->deleteByParentField($this->id, $columnName, $filter);
10732 if ($result < 0) {
10733 $error++;
10734 $this->errors[] = $childObject->error;
10735 break;
10736 }
10737 } else {
10738 $error++;
10739 $this->errors[] = "You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
10740 break;
10741 }
10742 } else {
10743 $error++;
10744 $this->errors[] = 'Cannot include child class file '.$filePath;
10745 break;
10746 }
10747 } else {
10748 // Delete record in child table
10749 $sql = "DELETE FROM ".$this->db->prefix().$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
10750
10751 $resql = $this->db->query($sql);
10752 if (!$resql) {
10753 $error++;
10754 $this->error = $this->db->lasterror();
10755 $this->errors[] = $this->error;
10756 break;
10757 }
10758 }
10759 }
10760 }
10761
10762 if (!$error) {
10763 if (!$notrigger) {
10764 // Call triggers
10765 $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
10766 if ($result < 0) {
10767 $error++;
10768 } // Do also here what you must do to rollback action if trigger fail
10769 // End call triggers
10770 }
10771 }
10772
10773 // Delete llx_ecm_files
10774 if (!$error) {
10775 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
10776 if (!$res) {
10777 $error++;
10778 }
10779 }
10780
10781 // Delete linked object
10782 $res = $this->deleteObjectLinked();
10783 if ($res < 0) {
10784 $error++;
10785 }
10786
10787 if (!$error && !empty($this->isextrafieldmanaged)) {
10788 $result = $this->deleteExtraFields();
10789 if ($result < 0) {
10790 $error++;
10791 }
10792 }
10793
10794 if (!$error) {
10795 $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
10796
10797 $resql = $this->db->query($sql);
10798 if (!$resql) {
10799 $error++;
10800 $this->errors[] = $this->db->lasterror();
10801 }
10802 }
10803
10804 // Commit or rollback
10805 if ($error) {
10806 $this->db->rollback();
10807 return -1;
10808 } else {
10809 $this->db->commit();
10810 return 1;
10811 }
10812 }
10813
10825 public function deleteByParentField($parentId = 0, $parentField = '', $filter = '', $filtermode = "AND")
10826 {
10827 global $user;
10828
10829 $error = 0;
10830 $deleted = 0;
10831
10832 if (!empty($parentId) && !empty($parentField)) {
10833 $this->db->begin();
10834
10835 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
10836 $sql .= " WHERE ".$this->db->sanitize($parentField)." = ".(int) $parentId;
10837
10838 // Manage filter
10839 $errormessage = '';
10840 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
10841 if ($errormessage) {
10842 $this->errors[] = $errormessage;
10843 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
10844 return -1;
10845 }
10846
10847 $resql = $this->db->query($sql);
10848 if (!$resql) {
10849 $this->errors[] = $this->db->lasterror();
10850 $error++;
10851 } else {
10852 while ($obj = $this->db->fetch_object($resql)) {
10853 $result = $this->fetch($obj->rowid); // @phpstan-ignore-line
10854 if ($result < 0) {
10855 $error++;
10856 $this->errors[] = $this->error;
10857 } else {
10858 $result = $this->delete($user); // @phpstan-ignore-line
10859 if ($result < 0) {
10860 $error++;
10861 $this->errors[] = $this->error;
10862 } else {
10863 $deleted++;
10864 }
10865 }
10866 }
10867 }
10868
10869 if (empty($error)) {
10870 $this->db->commit();
10871 return $deleted;
10872 } else {
10873 $this->error = implode(', ', $this->errors);
10874 $this->db->rollback();
10875 return $error * -1;
10876 }
10877 }
10878
10879 return $deleted;
10880 }
10881
10890 public function deleteLineCommon(User $user, $idline, $notrigger = 0)
10891 {
10892 $error = 0;
10893
10894 $tmpforobjectclass = get_class($this);
10895 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
10896
10897 $this->db->begin();
10898
10899 // Call trigger
10900 $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
10901 if ($result < 0) {
10902 $error++;
10903 }
10904 // End call triggers
10905
10906 if (empty($error)) {
10907 $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
10908 $sql .= " WHERE rowid = ".((int) $idline);
10909
10910 $resql = $this->db->query($sql);
10911 if (!$resql) {
10912 $this->error = "Error ".$this->db->lasterror();
10913 $error++;
10914 }
10915 }
10916
10917 if (empty($error)) {
10918 // Remove extrafields
10919 $tmpobjectline = new $tmpforobjectlineclass($this->db);
10920 '@phan-var-force CommonObjectLine $tmpobjectline';
10921 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
10922 $tmpobjectline->id = $idline;
10923 $result = $tmpobjectline->deleteExtraFields();
10924 if ($result < 0) {
10925 $error++;
10926 $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
10927 }
10928 }
10929 }
10930
10931 if (empty($error)) {
10932 $this->db->commit();
10933 return 1;
10934 } else {
10935 dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
10936 $this->db->rollback();
10937 return -1;
10938 }
10939 }
10940
10941
10951 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
10952 {
10953 $error = 0;
10954
10955 $this->db->begin();
10956
10957 $statusfield = 'status';
10958 if (in_array($this->element, array('don', 'donation', 'shipping'))) {
10959 $statusfield = 'fk_statut';
10960 }
10961
10962 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
10963 $sql .= " SET ".$statusfield." = ".((int) $status);
10964 $sql .= " WHERE rowid = ".((int) $this->id);
10965
10966 if ($this->db->query($sql)) {
10967 if (!$error) {
10968 $this->oldcopy = clone $this;
10969 }
10970
10971 if (!$error && !$notrigger) {
10972 // Call trigger
10973 $result = $this->call_trigger($triggercode, $user);
10974 if ($result < 0) {
10975 $error++;
10976 }
10977 }
10978
10979 if (!$error) {
10980 $this->status = $status;
10981 if (property_exists($this, 'statut')) { // For backward compatibility
10982 $this->statut = $status;
10983 }
10984 $this->db->commit();
10985 return 1;
10986 } else {
10987 $this->db->rollback();
10988 return -1;
10989 }
10990 } else {
10991 $this->error = $this->db->error();
10992 $this->db->rollback();
10993 return -1;
10994 }
10995 }
10996
11003 public function initAsSpecimenCommon()
11004 {
11005 global $user;
11006
11007 $this->id = 0;
11008 $this->specimen = 1;
11009 $fields = array(
11010 'label' => 'This is label',
11011 'ref' => 'ABCD1234',
11012 'description' => 'This is a description',
11013 'qty' => 123.12,
11014 'note_public' => 'Public note',
11015 'note_private' => 'Private note',
11016 'date_creation' => (dol_now() - 3600 * 48),
11017 'date_modification' => (dol_now() - 3600 * 24),
11018 'fk_user_creat' => $user->id,
11019 'fk_user_modif' => $user->id,
11020 'date' => dol_now(),
11021 );
11022 foreach ($fields as $key => $value) {
11023 if (array_key_exists($key, $this->fields)) {
11024 $this->{$key} = $value; // @phpstan-ignore-line
11025 }
11026 }
11027
11028 // Force values to default values when known
11029 if (property_exists($this, 'fields')) {
11030 foreach ($this->fields as $key => $value) {
11031 // If fields are already set, do nothing
11032 if (array_key_exists($key, $fields)) {
11033 continue;
11034 }
11035
11036 if (!empty($value['default'])) {
11037 $this->$key = $value['default'];
11038 }
11039 }
11040 }
11041
11042 return 1;
11043 }
11044
11045
11046 /* Part for comments */
11047
11053 public function fetchComments()
11054 {
11055 require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
11056
11057 $comment = new Comment($this->db);
11058 $result = $comment->fetchAllFor($this->element, $this->id);
11059 if ($result < 0) {
11060 $this->errors = array_merge($this->errors, $comment->errors);
11061 return -1;
11062 } else {
11063 $this->comments = $comment->comments;
11064 }
11065 return count($this->comments);
11066 }
11067
11073 public function getNbComments()
11074 {
11075 return count($this->comments);
11076 }
11077
11084 public function trimParameters($parameters)
11085 {
11086 if (!is_array($parameters)) {
11087 return;
11088 }
11089 foreach ($parameters as $parameter) {
11090 if (isset($this->$parameter)) {
11091 $this->$parameter = trim($this->$parameter);
11092 }
11093 }
11094 }
11095
11096 /* Part for categories/tags */
11097
11108 public function getCategoriesCommon($type_categ)
11109 {
11110 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11111
11112 // Get current categories
11113 $c = new Categorie($this->db);
11114 $existing = $c->containing($this->id, $type_categ, 'id');
11115
11116 return $existing;
11117 }
11118
11131 public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
11132 {
11133 // Handle single category
11134 if (!is_array($categories)) {
11135 $categories = array($categories);
11136 }
11137
11138 dol_syslog(get_class($this)."::setCategoriesCommon Object Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
11139
11140 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11141
11142 if (empty($type_categ)) {
11143 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
11144 return -1;
11145 }
11146
11147 // Get current categories
11148 $c = new Categorie($this->db);
11149 $existing = $c->containing($this->id, $type_categ, 'id');
11150 if ($remove_existing) {
11151 // Diff
11152 if (is_array($existing)) {
11153 $to_del = array_diff($existing, $categories);
11154 $to_add = array_diff($categories, $existing);
11155 } else {
11156 $to_del = array(); // Nothing to delete
11157 $to_add = $categories;
11158 }
11159 } else {
11160 $to_del = array(); // Nothing to delete
11161 $to_add = array_diff($categories, $existing);
11162 }
11163
11164 $error = 0;
11165 $ok = 0;
11166
11167 // Process
11168 foreach ($to_del as $del) {
11169 if ($c->fetch($del) > 0) {
11170 $result = $c->del_type($this, $type_categ);
11171 if ($result < 0) {
11172 $error++;
11173 $this->error = $c->error;
11174 $this->errors = $c->errors;
11175 break;
11176 } else {
11177 $ok += $result;
11178 }
11179 }
11180 }
11181 foreach ($to_add as $add) {
11182 if ($c->fetch($add) > 0) {
11183 $result = $c->add_type($this, $type_categ);
11184 if ($result < 0) {
11185 $error++;
11186 $this->error = $c->error;
11187 $this->errors = $c->errors;
11188 break;
11189 } else {
11190 $ok += $result;
11191 }
11192 }
11193 }
11194
11195 return $error ? (-1 * $error) : $ok;
11196 }
11197
11206 public function cloneCategories($fromId, $toId, $type = '')
11207 {
11208 $this->db->begin();
11209
11210 if (empty($type)) {
11211 $type = $this->table_element;
11212 }
11213
11214 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11215 $categorystatic = new Categorie($this->db);
11216
11217 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
11218 $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11219 $sql .= " WHERE fk_product = ".((int) $fromId);
11220
11221 if (!$this->db->query($sql)) {
11222 $this->error = $this->db->lasterror();
11223 $this->db->rollback();
11224 return -1;
11225 }
11226
11227 $this->db->commit();
11228 return 1;
11229 }
11230
11237 public function deleteEcmFiles($mode = 0)
11238 {
11239 global $conf;
11240
11241 $this->db->begin();
11242
11243 // Delete in database with mode 0
11244 if ($mode == 0) {
11245 switch ($this->element) {
11246 case 'propal':
11247 $element = 'propale';
11248 break;
11249 case 'product':
11250 $element = 'produit';
11251 break;
11252 case 'order_supplier':
11253 $element = 'fournisseur/commande';
11254 break;
11255 case 'invoice_supplier':
11256 // Special cases that need to use get_exdir to get real dir of object
11257 // In future, all object should use this to define path of documents.
11258 $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
11259 break;
11260 case 'shipping':
11261 $element = 'expedition/sending';
11262 break;
11263 case 'task':
11264 case 'project_task':
11265 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
11266
11267 $project_result = $this->fetchProject();
11268 if ($project_result >= 0) {
11269 $element = 'projet/'.dol_sanitizeFileName($this->project->ref).'/';
11270 }
11271 // no break
11272 default:
11273 $element = $this->element;
11274 }
11275 '@phan-var-force string $element';
11276
11277 // Delete ecm_files_extrafields with mode 0 (using name)
11278 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
11279 $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
11280 $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
11281 $sql .= ")";
11282
11283 if (!$this->db->query($sql)) {
11284 $this->error = $this->db->lasterror();
11285 $this->db->rollback();
11286 return false;
11287 }
11288
11289 // Delete ecm_files with mode 0 (using name)
11290 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
11291 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
11292 $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
11293
11294 if (!$this->db->query($sql)) {
11295 $this->error = $this->db->lasterror();
11296 $this->db->rollback();
11297 return false;
11298 }
11299 }
11300
11301 // Delete in database with mode 1
11302 if ($mode == 1) {
11303 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
11304 $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).")";
11305 $resql = $this->db->query($sql);
11306 if (!$resql) {
11307 $this->error = $this->db->lasterror();
11308 $this->db->rollback();
11309 return false;
11310 }
11311
11312 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
11313 $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
11314 $resql = $this->db->query($sql);
11315 if (!$resql) {
11316 $this->error = $this->db->lasterror();
11317 $this->db->rollback();
11318 return false;
11319 }
11320 }
11321
11322 $this->db->commit();
11323 return true;
11324 }
11325}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:457
$object ref
Definition info.php:79
Class to manage categories.
Class to manage comment.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
getCategoriesCommon($type_categ)
Sets object to given categories.
indexFile($destfull, $update_main_doc_field)
Index a file into the ECM database.
getFormatedSupplierRef($objref)
Return supplier ref for screen output.
line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
Save a new position (field rang) for details lines.
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
isEmpty()
isEmpty We consider CommonObject isEmpty if this->id is empty
clearFieldError($fieldKey)
clear validation message result for a field
static getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Count items linked to an object id in association table.
deleteEcmFiles($mode=0)
Delete related files of object in database.
getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
Return the link of last main doc file for direct public download.
liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
Return array with list of possible values for type of contacts.
getTooltipContent($params)
getTooltipContent
update_price($exclspec=0, $roundingadjust='auto', $nodatabaseupdate=0, $seller=null)
Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
swapContactStatus($rowid)
Update status of a contact linked to object.
getFieldError($fieldKey)
get field error message
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $f_user=null, $notrigger=0)
Update object linked of a current object.
defineBuyPrice($unitPrice=0.0, $discountPercent=0.0, $fk_product=0)
Get buy price to use for margin calculation.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
liste_contact($statusoflink=-1, $source='external', $list=0, $code='', $status=-1, $arrayoftcids=array())
Get array of all contacts for an object.
fetchObjectFrom($table, $field, $key, $element=null)
Load object from specific field.
fetchProject()
Load the project with id $this->fk_project into this->project.
fetch_thirdparty($force_thirdparty_id=0)
Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty.
static deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
Function used to remove all items linked to an object id in association table.
setFieldError($fieldKey, $msg='')
set validation error message a field
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
getDataToShowPhoto($modulepart, $imagesize)
Function used to get the logos or photos of an object.
setMulticurrencyCode($code)
Change the multicurrency code.
add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
Add resources to the current object : add entry into llx_element_resources Need $this->element & $thi...
emtpyObjectVars()
Sets all object fields to null.
fetch_projet()
Load the project with id $this->fk_project into this->project.
getIdContact($source, $code, $status=0)
Return id of contacts for a source and a contact code.
setExtraField($key, $value)
Convenience method for setting the value of an extrafield without actually updating it in the databas...
setDocModel($user, $modelpdf)
Set last model used by doc generator.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
getExtraField($key)
Convenience method for retrieving the value of an extrafield without actually fetching it from the da...
updateExtraField($key, $trigger=null, $userused=null)
Update 1 extra field value for the current object.
setPaymentTerms($id, $deposit_percent=null)
Change the payments terms.
isFloat($info)
Function test if type is float.
setBankAccount($fk_account, $notrigger=0, $userused=null)
Change the bank account.
setExtraParameters()
Set extra parameters.
setErrorsFromObject($object)
setErrorsFromObject
setShippingMethod($shipping_method_id, $notrigger=0, $userused=null)
Change the shipping method.
update_note_public($note)
Update public note (kept for backward compatibility)
getSpecialCode($lineid)
Get special code of a line.
clearObjectLinkedCache()
Clear the cache saying that all linked object were already loaded.
update_ref_ext($ref_ext)
Update external ref of element.
fetchOneLike($ref)
Looks for an object with ref matching the wildcard provided It does only work when $this->table_ref_f...
hasProductsOrServices($predefined=-1)
Function to say how many lines object contains.
static isExistingObject($element, $id, $ref='', $ref_ext='')
Check if an object id or ref exists If you don't need or want to instantiate the object and just need...
isObjectUsed($id=0, $entity=0)
Function to check if an object is used by others (by children).
updateRangOfLine($rowid, $rang)
Update position of line (rang)
getDefaultCreateValueFor($fieldname, $alternatevalue=null, $type='alphanohtml')
Return the default value to use for a field when showing the create form of object.
createCommon(User $user, $notrigger=0)
Create object in the database.
getTotalWeightVolume()
Return into unit=0, the calculated total of weight and volume of all lines * qty Calculate by adding ...
update_note($note, $suffix='', $notrigger=0)
Update note of element.
getFullAddress($withcountry=0, $sep="\n", $withregion=0, $extralangcode='')
Return full address of contact.
fetch_project()
Load the project with id $this->fk_project into this->project.
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of an object.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
getNbComments()
Return nb comments already posted.
setVarsFromFetchObj(&$obj)
Function to load data from a SQL pointer into properties of current object $this.
printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0, $defaulttpldir='/core/tpl')
Return HTML table for object lines TODO Move this into an output class file (htmlline....
getChildrenOfLine($id, $includealltree=0)
Get children of line.
updateCommon(User $user, $notrigger=0)
Update object into database.
updateExtraLanguages($key, $trigger=null, $userused=null)
Update an extra language value for the current object.
deleteExtraFields()
Delete all extra fields values for the current object.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
deprecatedProperties()
Provide list of deprecated properties and replacements.
addThumbs($file)
Build thumb.
setSaveQuery()
Function to return the array of data key-value from the ->fields and all the ->properties of an objec...
setValuesForExtraLanguages($onlykey='')
Fill array_options property of object by extrafields value (using for data sent by forms)
insertExtraLanguages($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
setTransportMode($id)
Change the transport mode methods.
isArray($info)
Function test if type is array.
isInt($info)
Function test if type is integer.
fetchObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $clause='OR', $alsosametype=1, $orderby='sourcetype', $loadalsoobjects=1)
Fetch array of objects linked to current object (object of enabled modules only).
delete_contact($rowid, $notrigger=0)
Delete a link to contact line.
updateLineUp($rowid, $rang)
Update position of line up (rang)
fetch_user($userid)
Load the user with id $userid into this->user.
errorsToString()
Method to output saved errors.
getListContactId($source='external')
Return list of id of contacts of object.
setWarehouse($warehouse_id)
Change the warehouse.
setDeliveryAddress($id)
Define delivery address.
getTotalDiscount()
Function that returns the total amount HT of discounts applied for all lines.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected=0, $extrafields=null, $defaulttpldir='/core/tpl')
Return HTML content of a detail line TODO Move this into an output class file (htmlline....
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
getValueFrom($table, $id, $field)
Getter generic.
trimParameters($parameters)
Trim object parameters.
fetch_product()
Load the product with id $this->fk_product into this->product.
isIndex($info)
Function test if is indexed.
quote($value, $fieldsentry)
Add quote to field value if necessary.
formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir='/core/tpl')
Show add free and predefined products/services form.
fetchComments()
Load comments linked with current task.
line_down($rowid, $fk_parent_line=true)
Update a line to have a higher rank.
setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
Setter generic.
fetch_contact($contactid=null)
Load object contact with id=$this->contact_id into $this->contact.
setRetainedWarrantyPaymentTerms($id)
Change the retained warranty payments terms.
delThumbs($file)
Delete thumbs.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
getRangOfLine($rowid)
Get position of line (rang)
showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0, $nonewbutton=0)
Return HTML string to put an input field into a page Code very similar with showInputField of extra f...
delete_resource($rowid, $element, $notrigger=0)
Delete a link to resource line.
update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
Update a link to contact line.
getElementType()
Return an element type string formatted like element_element target_type and source_type.
load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
Load properties id_previous and id_next by comparing $fieldid with $this->ref.
setCategoriesCommon($categories, $type_categ='', $remove_existing=true)
Sets object to given categories.
fetchValuesForExtraLanguages()
Function to get alternative languages of a data into $this->array_languages This method is NOT called...
fetchNoCompute($id)
Function to make a fetch but set environment to avoid to load computed values before.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
getJSListDependancies($type='_extra')
setProject($projectid, $notrigger=0)
Link element with a project.
isForcedToNullIfZero($info)
Function test if field is forced to null if zero or empty.
line_ajaxorder($rows)
Update position of line with ajax (rang)
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetch_origin()
Read linked origin object.
getIdOfLine($rang)
Get rowid of the line relative to its position.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
deleteByParentField($parentId=0, $parentField='', $filter='', $filtermode="AND")
Delete all child object from a parent ID.
static getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
Function used to get an array with all items linked to an object id in association table.
__clone()
Overwrite magic function to solve problem of cloning object that are kept as references.
setPaymentMethods($id)
Change the payments methods.
updateLineDown($rowid, $rang, $max)
Update position of line down (rang)
delete_linked_contact($source='', $code='')
Delete all links between an object $this and all its contacts in llx_element_contact.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
getFormatedCustomerRef($objref)
Return customer ref for screen output.
getTooltipContentArray($params)
Return array of data to show into a tooltip.
isText($info)
Function test if type is text.
isDate($info)
Function test if type is date.
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd='', $display_type='card')
Function to show lines of extrafields with output data.
getCanvas($id=0, $ref='')
Load type of canvas of an object if it exists.
line_up($rowid, $fk_parent_line=true)
Update a line to have a lower rank.
isDuration($info)
Function test if type is duration.
canBeNull($info)
Function test if field can be null.
listeTypeContacts($source='internal', $option=0, $activeonly=0, $code='', $element='', $excludeelement='')
Return array with list of possible values for type of contacts.
call_trigger($triggerName, $user)
Call trigger based on this instance.
getRights()
Returns the rights used for this class.
add_contact($fk_socpeople, $type_contact, $source='external', $notrigger=0)
Add a link between element $this->element and a contact.
cloneCategories($fromId, $toId, $type='')
Copy related categories to another object.
fetch_barcode()
Load data for barcode into properties ->barcode_type* Properties ->barcode_type that is id of barcode...
Class to manage contact/addresses.
Class to manage absolute discounts.
Class to manage a WYSIWYG editor.
Class to manage Dolibarr database access.
Class to manage ECM files.
Class to manage standard extra fields.
static isEmptyValue($v, string $type)
Return if a value is "empty" for a mandatory vision.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage generation of HTML components Only common components must be here.
Class to manage triggers.
Parent class to manage intervention document templates.
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_SERVICE
Service.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
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:162
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:242
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
dol_print_ip($ip, $mode=0)
Return an IP formatted to be shown on screen.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_print_phone($phone, $countrycode='', $cid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getPictoForType($key, $morecss='')
Return the picto for a data type.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
dol_getImageSize($file, $url=false)
Return size of image file on disk (Supported extensions are gif, jpg, png, bmp and webp)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $price_base_type, $info_bits, $type, $seller='', $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:88
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:141
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:137
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.