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 = ".$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 $resql = $this->db->query($sql);
1381 if ($resql) {
1382 return 0;
1383 } else {
1384 $this->error = $this->db->lasterror();
1385 return -1;
1386 }
1387 }
1388
1389 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1397 public function delete_contact($rowid, $notrigger = 0)
1398 {
1399 // phpcs:enable
1400 global $user;
1401
1402 $error = 0;
1403
1404 $this->db->begin();
1405
1406 if (!$error && empty($notrigger)) {
1407 // Call trigger
1408 $this->context['contact_id'] = ((int) $rowid);
1409 $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
1410 if ($result < 0) {
1411 $error++;
1412 }
1413 // End call triggers
1414 }
1415
1416 if (!$error) {
1417 dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
1418
1419 $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1420 $sql .= " WHERE rowid = ".((int) $rowid);
1421
1422 $result = $this->db->query($sql);
1423 if (!$result) {
1424 $error++;
1425 $this->errors[] = $this->db->lasterror();
1426 }
1427 }
1428
1429 if (!$error) {
1430 $this->db->commit();
1431 return 1;
1432 } else {
1433 $this->error = $this->db->lasterror();
1434 $this->db->rollback();
1435 return -1;
1436 }
1437 }
1438
1439 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1447 public function delete_linked_contact($source = '', $code = '')
1448 {
1449 // phpcs:enable
1450 $listId = '';
1451 $temp = array();
1452 $typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
1453
1454 if (!empty($typeContact)) {
1455 foreach ($typeContact as $key => $value) {
1456 array_push($temp, $key);
1457 }
1458 $listId = implode(",", $temp);
1459 }
1460
1461 // If $listId is empty, we have not criteria on fk_c_type_contact so we will delete record on element_id for
1462 // any type or record instead of only the ones of the current object. So we do nothing in such a case.
1463 if (empty($listId)) {
1464 return 0;
1465 }
1466
1467 $sql = "DELETE FROM ".$this->db->prefix()."element_contact";
1468 $sql .= " WHERE element_id = ".((int) $this->id);
1469 $sql .= " AND fk_c_type_contact IN (".$this->db->sanitize($listId).")";
1470
1471 dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
1472 if ($this->db->query($sql)) {
1473 return 1;
1474 } else {
1475 $this->error = $this->db->lasterror();
1476 return -1;
1477 }
1478 }
1479
1480 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1492 public function liste_contact($statusoflink = -1, $source = 'external', $list = 0, $code = '', $status = -1, $arrayoftcids = array())
1493 {
1494 // phpcs:enable
1495 global $langs;
1496
1497 $tab = array();
1498
1499 $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
1500 if ($source == 'internal') {
1501 $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo, t.gender";
1502 }
1503 if ($source == 'external' || $source == 'thirdparty') {
1504 $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
1505 }
1506 $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
1507 if (empty($arrayoftcids)) {
1508 $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
1509 }
1510 $sql .= " FROM";
1511 if (empty($arrayoftcids)) {
1512 $sql .= " ".$this->db->prefix()."c_type_contact as tc,";
1513 }
1514 $sql .= " ".$this->db->prefix()."element_contact as ec";
1515 if ($source == 'internal') { // internal contact (user)
1516 $sql .= " LEFT JOIN ".$this->db->prefix()."user as t on ec.fk_socpeople = t.rowid";
1517 }
1518 if ($source == 'external' || $source == 'thirdparty') { // external contact (socpeople)
1519 $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople as t on ec.fk_socpeople = t.rowid";
1520 }
1521 $sql .= " WHERE ec.element_id = ".((int) $this->id);
1522 if (empty($arrayoftcids)) {
1523 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1524 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1525 if ($code) {
1526 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1527 }
1528 if ($source == 'internal') {
1529 $sql .= " AND tc.source = 'internal'";
1530 }
1531 if ($source == 'external' || $source == 'thirdparty') {
1532 $sql .= " AND tc.source = 'external'";
1533 }
1534 $sql .= " AND tc.active = 1";
1535 } else {
1536 $sql .= " AND ec.fk_c_type_contact IN (".$this->db->sanitize(implode(',', $arrayoftcids)).")";
1537 }
1538 if ($status >= 0) {
1539 $sql .= " AND t.statut = ".((int) $status); // t is llx_user or llx_socpeople
1540 }
1541 if ($statusoflink >= 0) {
1542 $sql .= " AND ec.statut = ".((int) $statusoflink);
1543 }
1544 $sql .= " ORDER BY t.lastname ASC";
1545
1546 dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
1547 $resql = $this->db->query($sql);
1548 if ($resql) {
1549 $num = $this->db->num_rows($resql);
1550 $i = 0;
1551 while ($i < $num) {
1552 $obj = $this->db->fetch_object($resql);
1553
1554 if (!$list) {
1555 $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1556 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1557 $tab[$i] = array(
1558 'parentId' => $this->id,
1559 'source' => $obj->source,
1560 'socid' => $obj->socid,
1561 'id' => $obj->id,
1562 'nom' => $obj->lastname, // For backward compatibility
1563 'civility' => $obj->civility,
1564 'lastname' => $obj->lastname,
1565 'firstname' => $obj->firstname,
1566 'email' => $obj->email,
1567 'login' => (empty($obj->login) ? '' : $obj->login),
1568 'photo' => (empty($obj->photo) ? '' : $obj->photo),
1569 'gender' => (empty($obj->gender) ? '' : $obj->gender),
1570 'statuscontact' => $obj->statuscontact,
1571 'rowid' => $obj->rowid,
1572 'code' => $obj->code,
1573 'libelle' => $libelle_type,
1574 'status' => $obj->statuslink,
1575 'fk_c_type_contact' => $obj->fk_c_type_contact
1576 );
1577 } else {
1578 $tab[$i] = $obj->id;
1579 }
1580
1581 $i++;
1582 }
1583
1584 return $tab;
1585 } else {
1586 $this->error = $this->db->lasterror();
1587 dol_print_error($this->db);
1588 return -1;
1589 }
1590 }
1591
1592
1599 public function swapContactStatus($rowid)
1600 {
1601 $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1602 $sql .= " tc.code, tc.libelle as type_label";
1603 $sql .= " FROM (".$this->db->prefix()."element_contact as ec, ".$this->db->prefix()."c_type_contact as tc)";
1604 $sql .= " WHERE ec.rowid =".((int) $rowid);
1605 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1606 $sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1607
1608 dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1609 $resql = $this->db->query($sql);
1610 if ($resql) {
1611 $obj = $this->db->fetch_object($resql);
1612 $newstatut = ($obj->statut == 4) ? 5 : 4;
1613 $result = $this->update_contact($rowid, $newstatut);
1614 $this->db->free($resql);
1615 return $result;
1616 } else {
1617 $this->error = $this->db->error();
1618 dol_print_error($this->db);
1619 return -1;
1620 }
1621 }
1622
1623 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1634 public function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1635 {
1636 // phpcs:enable
1637 global $langs;
1638
1639 if (empty($order)) {
1640 $order = 'position';
1641 }
1642 if ($order == 'position') {
1643 $order .= ',code';
1644 }
1645
1646 $tab = array();
1647 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position";
1648 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1649 $sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1650 if ($activeonly == 1) {
1651 $sql .= " AND tc.active=1"; // only the active types
1652 }
1653 if (!empty($source) && $source != 'all') {
1654 $sql .= " AND tc.source='".$this->db->escape($source)."'";
1655 }
1656 if (!empty($code)) {
1657 $sql .= " AND tc.code='".$this->db->escape($code)."'";
1658 }
1659 $sql .= $this->db->order($order, 'ASC');
1660
1661 //print "sql=".$sql;
1662 $resql = $this->db->query($sql);
1663 if ($resql) {
1664 $num = $this->db->num_rows($resql);
1665 $i = 0;
1666 while ($i < $num) {
1667 $obj = $this->db->fetch_object($resql);
1668
1669 $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1670 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1671 if (empty($option)) {
1672 $tab[$obj->rowid] = $libelle_type;
1673 } else {
1674 $tab[$obj->code] = $libelle_type;
1675 }
1676 $i++;
1677 }
1678 return $tab;
1679 } else {
1680 $this->error = $this->db->lasterror();
1681 //dol_print_error($this->db);
1682 return null;
1683 }
1684 }
1685
1697 public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '')
1698 {
1699 global $langs, $conf;
1700
1701 $langs->loadLangs(array('bills', 'contracts', 'interventions', 'orders', 'projects', 'propal', 'ticket', 'agenda'));
1702
1703 $tab = array();
1704
1705 $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle as type_label, tc.position, tc.element";
1706 $sql .= " FROM ".$this->db->prefix()."c_type_contact as tc";
1707
1708 $sqlWhere = array();
1709 if (!empty($element)) {
1710 $sqlWhere[] = " tc.element='".$this->db->escape($element)."'";
1711 }
1712 if (!empty($excludeelement)) {
1713 $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'";
1714 }
1715
1716 if ($activeonly == 1) {
1717 $sqlWhere[] = " tc.active=1"; // only the active types
1718 }
1719
1720 if (!empty($source) && $source != 'all') {
1721 $sqlWhere[] = " tc.source='".$this->db->escape($source)."'";
1722 }
1723
1724 if (!empty($code)) {
1725 $sqlWhere[] = " tc.code='".$this->db->escape($code)."'";
1726 }
1727
1728 if (count($sqlWhere) > 0) {
1729 $sql .= " WHERE ".implode(' AND ', $sqlWhere);
1730 }
1731
1732 $sql .= $this->db->order('tc.element, tc.position', 'ASC');
1733
1734 dol_syslog(__METHOD__, LOG_DEBUG);
1735 $resql = $this->db->query($sql);
1736 if ($resql) {
1737 $num = $this->db->num_rows($resql);
1738 if ($num > 0) {
1739 $langs->loadLangs(array("propal", "orders", "bills", "suppliers", "contracts", "supplier_proposal"));
1740
1741 while ($obj = $this->db->fetch_object($resql)) {
1742 $modulename = $obj->element;
1743 if (strpos($obj->element, 'project') !== false) {
1744 $modulename = 'projet';
1745 } elseif ($obj->element == 'contrat') {
1746 $element = 'contract';
1747 } elseif ($obj->element == 'action') {
1748 $modulename = 'agenda';
1749 } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') {
1750 $modulename = 'fournisseur';
1751 }
1752 if (!empty($conf->{$modulename}->enabled)) {
1753 $libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1754 $tmpelement = $obj->element;
1755 $transkey = "TypeContact_".$tmpelement."_".$source."_".$obj->code;
1756 $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
1757 $tab[$obj->rowid] = $libelle_element.' - '.$libelle_type;
1758 }
1759 }
1760 }
1761 return $tab;
1762 } else {
1763 $this->error = $this->db->lasterror();
1764 return null;
1765 }
1766 }
1767
1779 public function getIdContact($source, $code, $status = 0)
1780 {
1781 global $conf;
1782
1783 $result = array();
1784 $i = 0;
1785 // Particular case for shipping
1786 if ($this->element == 'shipping' && $this->origin_id != 0) {
1787 $id = $this->origin_id;
1788 $element = 'commande';
1789 } elseif ($this->element == 'reception' && $this->origin_id != 0) {
1790 $id = $this->origin_id;
1791 $element = 'order_supplier';
1792 } else {
1793 $id = $this->id;
1794 $element = $this->element;
1795 }
1796
1797 $sql = "SELECT ec.fk_socpeople";
1798 $sql .= " FROM ".$this->db->prefix()."element_contact as ec,";
1799 if ($source == 'internal') {
1800 $sql .= " ".$this->db->prefix()."user as c,";
1801 }
1802 if ($source == 'external') {
1803 $sql .= " ".$this->db->prefix()."socpeople as c,";
1804 }
1805 $sql .= " ".$this->db->prefix()."c_type_contact as tc";
1806 $sql .= " WHERE ec.element_id = ".((int) $id);
1807 $sql .= " AND ec.fk_socpeople = c.rowid";
1808 if ($source == 'internal') {
1809 $sql .= " AND c.entity IN (".getEntity('user').")";
1810 }
1811 if ($source == 'external') {
1812 $sql .= " AND c.entity IN (".getEntity('societe').")";
1813 }
1814 $sql .= " AND ec.fk_c_type_contact = tc.rowid";
1815 $sql .= " AND tc.element = '".$this->db->escape($element)."'";
1816 $sql .= " AND tc.source = '".$this->db->escape($source)."'";
1817 if ($code) {
1818 $sql .= " AND tc.code = '".$this->db->escape($code)."'";
1819 }
1820 $sql .= " AND tc.active = 1";
1821 if ($status) {
1822 $sql .= " AND ec.statut = ".((int) $status);
1823 }
1824
1825 dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1826 $resql = $this->db->query($sql);
1827 if ($resql) {
1828 while ($obj = $this->db->fetch_object($resql)) {
1829 $result[$i] = $obj->fk_socpeople;
1830 $i++;
1831 }
1832 } else {
1833 $this->error = $this->db->error();
1834 return null;
1835 }
1836
1837 return $result;
1838 }
1839
1840 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1847 public function fetch_contact($contactid = null)
1848 {
1849 // phpcs:enable
1850 if (empty($contactid)) {
1851 $contactid = $this->contact_id;
1852 }
1853
1854 if (empty($contactid)) {
1855 return 0;
1856 }
1857
1858 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1859 $contact = new Contact($this->db);
1860 $result = $contact->fetch($contactid);
1861 $this->contact = $contact;
1862 return $result;
1863 }
1864
1865 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1873 public function fetch_thirdparty($force_thirdparty_id = 0)
1874 {
1875 // phpcs:enable
1876 if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) {
1877 return 0;
1878 }
1879
1880 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1881
1882 $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : 0);
1883 if ($force_thirdparty_id) {
1884 $idtofetch = $force_thirdparty_id;
1885 }
1886
1887 if ($idtofetch) {
1888 $thirdparty = new Societe($this->db);
1889 $result = $thirdparty->fetch($idtofetch);
1890 if ($result < 0) {
1891 $this->errors = array_merge($this->errors, $thirdparty->errors);
1892 }
1893 $this->thirdparty = $thirdparty;
1894
1895 // Use first price level if level not defined for third party
1896 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && empty($this->thirdparty->price_level)) {
1897 $this->thirdparty->price_level = 1;
1898 }
1899
1900 return $result;
1901 } else {
1902 return -1;
1903 }
1904 }
1905
1906
1914 public function fetchOneLike($ref)
1915 {
1916 if (!$this->table_ref_field) {
1917 return 0;
1918 }
1919
1920 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
1921 $sql .= " WHERE ".$this->table_ref_field." LIKE '".$this->db->escape($ref)."'"; // no escapeforlike here
1922 $sql .= " LIMIT 1";
1923
1924 $query = $this->db->query($sql);
1925
1926 if (!$this->db->num_rows($query)) {
1927 return 0;
1928 }
1929
1930 $result = $this->db->fetch_object($query);
1931
1932 if (method_exists($this, 'fetch')) {
1933 return $this->fetch($result->rowid);
1934 } else {
1935 $this->error = 'Fetch method not implemented on '.get_class($this);
1936 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
1937 array_push($this->errors, $this->error);
1938 return -1;
1939 }
1940 }
1941
1942 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1950 public function fetch_barcode()
1951 {
1952 // phpcs:enable
1953 global $conf;
1954
1955 dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1956
1957 $idtype = $this->barcode_type;
1958 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
1959 if ($this->element == 'product' && getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE')) {
1960 $idtype = getDolGlobalString('PRODUIT_DEFAULT_BARCODE_TYPE');
1961 } elseif ($this->element == 'societe') {
1962 $idtype = getDolGlobalString('GENBARCODE_BARCODETYPE_THIRDPARTY');
1963 } else {
1964 dol_syslog('Call fetch_barcode with barcode_type not defined and cannot be guessed', LOG_WARNING);
1965 }
1966 }
1967
1968 if ($idtype > 0) {
1969 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
1970 $sql = "SELECT rowid, code, libelle as label, coder";
1971 $sql .= " FROM ".$this->db->prefix()."c_barcode_type";
1972 $sql .= " WHERE rowid = ".((int) $idtype);
1973 dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1974 $resql = $this->db->query($sql);
1975 if ($resql) {
1976 $obj = $this->db->fetch_object($resql);
1977 $this->barcode_type = $obj->rowid;
1978 $this->barcode_type_code = $obj->code;
1979 $this->barcode_type_label = $obj->label;
1980 $this->barcode_type_coder = $obj->coder;
1981 return 1;
1982 } else {
1983 dol_print_error($this->db);
1984 return -1;
1985 }
1986 }
1987 }
1988 return 0;
1989 }
1990
1991 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1997 public function fetch_project()
1998 {
1999 // phpcs:enable
2000 return $this->fetch_projet();
2001 }
2002
2003 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2009 public function fetch_projet()
2010 {
2011 // phpcs:enable
2012 include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
2013
2014 if (empty($this->fk_project) && !empty($this->fk_projet)) {
2015 $this->fk_project = $this->fk_projet; // For backward compatibility
2016 }
2017 if (empty($this->fk_project)) {
2018 return 0;
2019 }
2020
2021 $project = new Project($this->db);
2022 $result = $project->fetch($this->fk_project);
2023
2024 $this->projet = $project; // deprecated
2025 $this->project = $project;
2026 return $result;
2027 }
2028
2029 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2035 public function fetch_product()
2036 {
2037 // phpcs:enable
2038 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2039
2040 // @phan-suppress-next-line PhanUndeclaredProperty
2041 if (empty($this->fk_product)) {
2042 return 0;
2043 }
2044
2045 $product = new Product($this->db);
2046 // @phan-suppress-next-line PhanUndeclaredProperty
2047 $result = $product->fetch($this->fk_product);
2048
2049 $this->product = $product;
2050 return $result;
2051 }
2052
2053 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2060 public function fetch_user($userid)
2061 {
2062 // phpcs:enable
2063 $user = new User($this->db);
2064 $result = $user->fetch($userid);
2065 $this->user = $user;
2066 return $result;
2067 }
2068
2069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2076 public function fetch_origin()
2077 {
2078 // phpcs:enable
2079 $origin = $this->origin ? $this->origin : $this->origin_type;
2080
2081 // Manage classes with non standard name
2082 if ($origin == 'shipping') {
2083 $origin = 'expedition';
2084 }
2085 if ($origin == 'delivery') {
2086 $origin = 'livraison';
2087 }
2088 if ($origin == 'order_supplier' || $origin == 'supplier_order') {
2089 $origin = 'commandeFournisseur';
2090 }
2091
2092 $classname = ucfirst($origin);
2093 $this->origin_object = new $classname($this->db);
2094 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
2095 $this->origin_object->fetch($this->origin_id);
2096 }
2097
2107 public function fetchObjectFrom($table, $field, $key, $element = null)
2108 {
2109 global $conf;
2110
2111 $result = false;
2112
2113 $sql = "SELECT rowid FROM ".$this->db->prefix().$table;
2114 $sql .= " WHERE ".$field." = '".$this->db->escape($key)."'";
2115 if (!empty($element)) {
2116 $sql .= " AND entity IN (".getEntity($element).")";
2117 } else {
2118 $sql .= " AND entity = ".((int) $conf->entity);
2119 }
2120
2121 dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
2122 $resql = $this->db->query($sql);
2123 if ($resql) {
2124 $obj = $this->db->fetch_object($resql);
2125 // Test for avoid error -1
2126 if ($obj) {
2127 if (method_exists($this, 'fetch')) {
2128 $result = $this->fetch($obj->rowid);
2129 } else {
2130 $this->error = 'fetch() method not implemented on '.get_class($this);
2131 dol_syslog(get_class($this).'::fetchOneLike Error='.$this->error, LOG_ERR);
2132 array_push($this->errors, $this->error);
2133 $result = -1;
2134 }
2135 }
2136 }
2137
2138 return $result;
2139 }
2140
2149 public function getValueFrom($table, $id, $field)
2150 {
2151 $result = false;
2152 if (!empty($id) && !empty($field) && !empty($table)) {
2153 $sql = "SELECT ".$field." FROM ".$this->db->prefix().$table;
2154 $sql .= " WHERE rowid = ".((int) $id);
2155
2156 dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
2157 $resql = $this->db->query($sql);
2158 if ($resql) {
2159 $row = $this->db->fetch_row($resql);
2160 $result = $row[0];
2161 }
2162 }
2163 return $result;
2164 }
2165
2182 public function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
2183 {
2184 global $user;
2185
2186 if (empty($table)) {
2187 $table = $this->table_element;
2188 }
2189 if (empty($id)) {
2190 $id = $this->id;
2191 }
2192 if (empty($format)) {
2193 $format = 'text';
2194 }
2195 if (empty($id_field)) {
2196 $id_field = 'rowid';
2197 }
2198
2199 // Special case
2200 if ($table == 'product' && $field == 'note_private') {
2201 $field = 'note';
2202 }
2203
2204 if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
2205 $fk_user_field = 'fk_user_mod';
2206 }
2207 if (in_array($table, array('prelevement_bons'))) { // TODO Add a field fk_user_modif into llx_prelevement_bons
2208 $fk_user_field = '';
2209 }
2210
2211 $oldvalue = null;
2212 if ($trigkey) {
2213 $sql = "SELECT " . $field;
2214 $sql .= " FROM " . MAIN_DB_PREFIX . $table;
2215 $sql .= " WHERE " . $id_field . " = " . ((int) $id);
2216
2217 $resql = $this->db->query($sql);
2218 if ($resql) {
2219 if ($obj = $this->db->fetch_object($resql)) {
2220 if ($format == 'date') {
2221 $oldvalue = $this->db->jdate($obj->$field);
2222 } else {
2223 $oldvalue = $obj->$field;
2224 }
2225 }
2226 } else {
2227 $this->error = $this->db->lasterror();
2228 return -1;
2229 }
2230 }
2231
2232 $error = 0;
2233
2234 dol_syslog(__METHOD__, LOG_DEBUG);
2235
2236 $this->db->begin();
2237
2238 $sql = "UPDATE ".$this->db->prefix().$table." SET ";
2239
2240 if ($format == 'text') {
2241 $sql .= $field." = '".$this->db->escape($value)."'";
2242 } elseif ($format == 'int') {
2243 $sql .= $field." = ".((int) $value);
2244 } elseif ($format == 'date') {
2245 $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
2246 } elseif ($format == 'dategmt') {
2247 $sql .= $field." = ".($value ? "'".$this->db->idate($value, 'gmt')."'" : "null");
2248 }
2249
2250 if ($fk_user_field) {
2251 if (!empty($fuser) && is_object($fuser)) {
2252 $sql .= ", ".$fk_user_field." = ".((int) $fuser->id);
2253 } elseif (empty($fuser) || $fuser != 'none') {
2254 $sql .= ", ".$fk_user_field." = ".((int) $user->id);
2255 }
2256 }
2257
2258 $sql .= " WHERE ".$id_field." = ".((int) $id);
2259
2260 $resql = $this->db->query($sql);
2261 if ($resql) {
2262 if ($trigkey) {
2263 // call trigger with updated object values
2264 if (method_exists($this, 'fetch')) {
2265 $result = $this->fetch($id);
2266 } else {
2267 $result = $this->fetchCommon($id);
2268 }
2269 $this->oldcopy = clone $this;
2270 if (property_exists($this->oldcopy, $field)) {
2271 $this->oldcopy->$field = $oldvalue;
2272 }
2273
2274 if ($result >= 0) {
2275 $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
2276 }
2277 if ($result < 0) {
2278 $error++;
2279 }
2280 }
2281
2282 if (!$error) {
2283 if (property_exists($this, $field)) {
2284 $this->$field = $value;
2285 }
2286 $this->db->commit();
2287 return 1;
2288 } else {
2289 $this->db->rollback();
2290 return -2;
2291 }
2292 } else {
2293 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2294 $this->error = 'DB_ERROR_RECORD_ALREADY_EXISTS';
2295 } else {
2296 $this->error = $this->db->lasterror();
2297 }
2298 $this->db->rollback();
2299 return -1;
2300 }
2301 }
2302
2303 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2314 public function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
2315 {
2316 // phpcs:enable
2317 global $conf, $user;
2318
2319 if (!$this->table_element) {
2320 dol_print_error(null, get_class($this)."::load_previous_next_ref was called on object with property table_element not defined");
2321 return -1;
2322 }
2323 if ($fieldid == 'none') {
2324 return 1;
2325 }
2326
2327 // For backward compatibility
2328 if (in_array($this->table_element, array('facture_rec', 'facture_fourn_rec')) && $fieldid == 'title') {
2329 $fieldid = 'titre';
2330 }
2331
2332 // Security on socid
2333 $socid = 0;
2334 if ($user->socid > 0) {
2335 $socid = $user->socid;
2336 }
2337
2338 // this->ismultientitymanaged contains
2339 // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
2340 $aliastablesociete = 's';
2341 if ($this->element == 'societe') {
2342 $aliastablesociete = 'te'; // te as table_element
2343 }
2344 $restrictiononfksoc = empty($this->restrictiononfksoc) ? 0 : $this->restrictiononfksoc;
2345 $sql = "SELECT MAX(te.".$fieldid.")";
2346 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2347 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2348 $tmparray = explode('@', $this->ismultientitymanaged);
2349 $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
2350 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2351 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2352 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2353 $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
2354 }
2355 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2356 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2357 }
2358 if ($fieldid == 'rowid') {
2359 $sql .= " WHERE te.".$fieldid." < ".((int) $this->id);
2360 } else {
2361 $sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2362 }
2363 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2364 $sql .= " AND sc.fk_user = ".((int) $user->id);
2365 }
2366 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2367 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2368 }
2369
2370 $filtermax = $filter;
2371
2372 // Manage filter
2373 $errormessage = '';
2374 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermax, $errormessage);
2375 if ($errormessage) {
2376 if (!preg_match('/^\s*AND/i', $filtermax)) {
2377 $sql .= " AND ";
2378 }
2379 $sql .= $filtermax;
2380 } else {
2381 $sql .= $tmpsql;
2382 }
2383
2384 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2385 $tmparray = explode('@', $this->ismultientitymanaged);
2386 $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2387 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2388 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2389 }
2390 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2391 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2392 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2393 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2394 } else {
2395 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2396 }
2397 } else {
2398 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2399 }
2400 }
2401 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2402 $tmparray = explode('@', $this->ismultientitymanaged);
2403 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2404 }
2405 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2406 $sql .= ' AND te.fk_soc = '.((int) $socid);
2407 }
2408 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2409 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2410 }
2411 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2412 $sql .= ' AND te.rowid = '.((int) $socid);
2413 }
2414 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2415
2416 $result = $this->db->query($sql);
2417 if (!$result) {
2418 $this->error = $this->db->lasterror();
2419 return -1;
2420 }
2421 $row = $this->db->fetch_row($result);
2422 $this->ref_previous = $row[0];
2423
2424 $sql = "SELECT MIN(te.".$fieldid.")";
2425 $sql .= " FROM ".(empty($nodbprefix) ? $this->db->prefix() : '').$this->table_element." as te";
2426 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2427 $tmparray = explode('@', $this->ismultientitymanaged);
2428 $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
2429 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2430 $sql .= ", ".$this->db->prefix()."societe as s"; // If we need to link to societe to limit select to socid
2431 } elseif ($restrictiononfksoc == 2 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2432 $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
2433 }
2434 if ($restrictiononfksoc && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2435 $sql .= " LEFT JOIN ".$this->db->prefix()."societe_commerciaux as sc ON ".$aliastablesociete.".rowid = sc.fk_soc";
2436 }
2437 if ($fieldid == 'rowid') {
2438 $sql .= " WHERE te.".$fieldid." > ".((int) $this->id);
2439 } else {
2440 $sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
2441 }
2442 if ($restrictiononfksoc == 1 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2443 $sql .= " AND (sc.fk_user = ".((int) $user->id);
2444 if (getDolGlobalInt('MAIN_SEE_SUBORDINATES')) {
2445 $userschilds = $user->getAllChildIds();
2446 $sql .= " OR sc.fk_user IN (".$this->db->sanitize(implode(',', $userschilds)).")";
2447 }
2448 $sql .= ')';
2449 }
2450 if ($restrictiononfksoc == 2 && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2451 $sql .= " AND (sc.fk_user = ".((int) $user->id).' OR te.fk_soc IS NULL)';
2452 }
2453
2454 $filtermin = $filter;
2455
2456 // Manage filter
2457 $errormessage = '';
2458 $tmpsql = forgeSQLFromUniversalSearchCriteria($filtermin, $errormessage);
2459 if ($errormessage) {
2460 if (!preg_match('/^\s*AND/i', $filtermin)) {
2461 $sql .= " AND ";
2462 }
2463 $sql .= $filtermin;
2464
2465 $filtermin = '';
2466 } else {
2467 $sql .= $tmpsql;
2468 }
2469
2470 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) {
2471 $tmparray = explode('@', $this->ismultientitymanaged);
2472 $sql .= " AND te.".$tmparray[0]." = ".($tmparray[1] == "societe" ? "s" : "parenttable").".rowid"; // If we need to link to this table to limit select to entity
2473 } elseif ($restrictiononfksoc == 1 && $this->element != 'societe' && !$user->hasRight('societe', 'client', 'voir') && !$socid) {
2474 $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
2475 }
2476 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
2477 if ($this->element == 'user' && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2478 if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
2479 $sql .= " AND te.entity IS NOT NULL"; // Show all users
2480 } else {
2481 $sql .= " AND te.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2482 }
2483 } else {
2484 $sql .= ' AND te.entity IN ('.getEntity($this->element).')';
2485 }
2486 }
2487 if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') {
2488 $tmparray = explode('@', $this->ismultientitymanaged);
2489 $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')';
2490 }
2491 if ($restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
2492 $sql .= ' AND te.fk_soc = '.((int) $socid);
2493 }
2494 if ($restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
2495 $sql .= ' AND (te.fk_soc = '.((int) $socid).' OR te.fk_soc IS NULL)';
2496 }
2497 if ($restrictiononfksoc && $socid && $this->element == 'societe') {
2498 $sql .= ' AND te.rowid = '.((int) $socid);
2499 }
2500 //print 'socid='.$socid.' restrictiononfksoc='.$restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
2501 // 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
2502
2503 $result = $this->db->query($sql);
2504 if (!$result) {
2505 $this->error = $this->db->lasterror();
2506 return -2;
2507 }
2508 $row = $this->db->fetch_row($result);
2509 $this->ref_next = $row[0];
2510
2511 return 1;
2512 }
2513
2514
2522 public function getListContactId($source = 'external')
2523 {
2524 $contactAlreadySelected = array();
2525 $tab = $this->liste_contact(-1, $source);
2526 $num = count($tab);
2527 $i = 0;
2528 while ($i < $num) {
2529 if ($source == 'thirdparty') {
2530 $contactAlreadySelected[$i] = $tab[$i]['socid'];
2531 } else {
2532 $contactAlreadySelected[$i] = $tab[$i]['id'];
2533 }
2534 $i++;
2535 }
2536 return $contactAlreadySelected;
2537 }
2538
2539
2547 public function setProject($projectid, $notrigger = 0)
2548 {
2549 global $user;
2550 $error = 0;
2551
2552 if (!$this->table_element) {
2553 dol_syslog(get_class($this)."::setProject was called on object with property table_element not defined", LOG_ERR);
2554 return -1;
2555 }
2556
2557 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2558 // @phan-suppress-next-line PhanTypeMismatchProperty
2559 if (!empty($this->fields['fk_project'])) { // Common case
2560 if ($projectid) {
2561 $sql .= " SET fk_project = ".((int) $projectid);
2562 } else {
2563 $sql .= " SET fk_project = NULL";
2564 }
2565 $sql .= ' WHERE rowid = '.((int) $this->id);
2566 } elseif ($this->table_element == 'actioncomm') { // Special case for actioncomm
2567 if ($projectid) {
2568 $sql .= " SET fk_project = ".((int) $projectid);
2569 } else {
2570 $sql .= " SET fk_project = NULL";
2571 }
2572 $sql .= ' WHERE id = '.((int) $this->id);
2573 } else { // Special case for old architecture objects
2574 if ($projectid) {
2575 $sql .= ' SET fk_projet = '.((int) $projectid);
2576 } else {
2577 $sql .= ' SET fk_projet = NULL';
2578 }
2579 $sql .= " WHERE rowid = ".((int) $this->id);
2580 }
2581
2582 $this->db->begin();
2583
2584 dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
2585 if ($this->db->query($sql)) {
2586 $this->fk_project = ((int) $projectid);
2587 } else {
2588 dol_print_error($this->db);
2589 $error++;
2590 }
2591
2592 // Triggers
2593 if (!$error && !$notrigger) {
2594 // Call triggers
2595 $result = $this->call_trigger(strtoupper($this->element) . '_MODIFY', $user);
2596 if ($result < 0) {
2597 $error++;
2598 } //Do also here what you must do to rollback action if trigger fail
2599 // End call triggers
2600 }
2601
2602 // Commit or rollback
2603 if ($error) {
2604 $this->db->rollback();
2605 return -1;
2606 } else {
2607 $this->db->commit();
2608 return 1;
2609 }
2610 }
2611
2618 public function setPaymentMethods($id)
2619 {
2620 global $user;
2621
2622 $error = 0;
2623 $notrigger = 0;
2624
2625 dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
2626
2627 if ($this->status >= 0 || $this->element == 'societe') {
2628 // TODO uniformize field name
2629 $fieldname = 'fk_mode_reglement';
2630 if ($this->element == 'societe') {
2631 $fieldname = 'mode_reglement';
2632 }
2633 if (get_class($this) == 'Fournisseur') {
2634 $fieldname = 'mode_reglement_supplier';
2635 }
2636 if (get_class($this) == 'Tva') {
2637 $fieldname = 'fk_typepayment';
2638 }
2639 if (get_class($this) == 'Salary') {
2640 $fieldname = 'fk_typepayment';
2641 }
2642
2643 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
2644 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2645 $sql .= ' WHERE rowid='.((int) $this->id);
2646
2647 if ($this->db->query($sql)) {
2648 $this->mode_reglement_id = $id;
2649 // for supplier
2650 if (get_class($this) == 'Fournisseur') {
2651 $this->mode_reglement_supplier_id = $id;
2652 }
2653 // Triggers
2654 if (!$error && !$notrigger) {
2655 // Call triggers
2656 if (get_class($this) == 'Commande') {
2657 $result = $this->call_trigger('ORDER_MODIFY', $user);
2658 } else {
2659 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
2660 }
2661 if ($result < 0) {
2662 $error++;
2663 }
2664 // End call triggers
2665 }
2666 return 1;
2667 } else {
2668 dol_syslog(get_class($this).'::setPaymentMethods Error '.$this->db->error());
2669 $this->error = $this->db->error();
2670 return -1;
2671 }
2672 } else {
2673 dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
2674 $this->error = 'Status of the object is incompatible '.$this->status;
2675 return -2;
2676 }
2677 }
2678
2685 public function setMulticurrencyCode($code)
2686 {
2687 dol_syslog(get_class($this).'::setMulticurrencyCode('.$code.')');
2688 if ($this->status >= 0 || $this->element == 'societe') {
2689 $fieldname = 'multicurrency_code';
2690
2691 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2692 $sql .= " SET ".$fieldname." = '".$this->db->escape($code)."'";
2693 $sql .= ' WHERE rowid='.((int) $this->id);
2694
2695 if ($this->db->query($sql)) {
2696 $this->multicurrency_code = $code;
2697
2698 list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
2699 if ($rate) {
2700 $this->setMulticurrencyRate($rate, 2);
2701 }
2702
2703 return 1;
2704 } else {
2705 dol_syslog(get_class($this).'::setMulticurrencyCode Error '.$sql.' - '.$this->db->error());
2706 $this->error = $this->db->error();
2707 return -1;
2708 }
2709 } else {
2710 dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
2711 $this->error = 'Status of the object is incompatible '.$this->status;
2712 return -2;
2713 }
2714 }
2715
2723 public function setMulticurrencyRate($rate, $mode = 1)
2724 {
2725 dol_syslog(get_class($this).'::setMulticurrencyRate('.$rate.', '.$mode.')');
2726 if ($this->status >= 0 || $this->element == 'societe') {
2727 $fieldname = 'multicurrency_tx';
2728
2729 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2730 $sql .= " SET ".$fieldname." = ".((float) $rate);
2731 $sql .= ' WHERE rowid='.((int) $this->id);
2732
2733 if ($this->db->query($sql)) {
2734 $this->multicurrency_tx = $rate;
2735
2736 // Update line price
2737 if (!empty($this->lines)) {
2738 foreach ($this->lines as &$line) {
2739 // Amounts in company currency will be recalculated
2740 if ($mode == 1) {
2741 $line->subprice = 0;
2742 }
2743
2744 // Amounts in foreign currency will be recalculated
2745 if ($mode == 2) {
2746 $line->multicurrency_subprice = 0;
2747 }
2748
2749 switch ($this->element) {
2750 case 'propal':
2753 '@phan-var-force Propal $this';
2754 '@phan-var-force PropaleLigne $line';
2755 $this->updateline(
2756 $line->id,
2757 $line->subprice,
2758 $line->qty,
2759 $line->remise_percent,
2760 $line->tva_tx,
2761 $line->localtax1_tx,
2762 $line->localtax2_tx,
2763 ($line->description ? $line->description : $line->desc),
2764 'HT',
2765 $line->info_bits,
2766 $line->special_code,
2767 $line->fk_parent_line,
2768 $line->skip_update_total,
2769 $line->fk_fournprice,
2770 $line->pa_ht,
2771 $line->label,
2772 $line->product_type,
2773 $line->date_start,
2774 $line->date_end,
2775 $line->array_options,
2776 $line->fk_unit,
2777 $line->multicurrency_subprice
2778 );
2779 break;
2780 case 'commande':
2783 '@phan-var-force Commande $this';
2784 '@phan-var-force OrderLine $line';
2785 $this->updateline(
2786 $line->id,
2787 ($line->description ? $line->description : $line->desc),
2788 $line->subprice,
2789 $line->qty,
2790 $line->remise_percent,
2791 $line->tva_tx,
2792 $line->localtax1_tx,
2793 $line->localtax2_tx,
2794 'HT',
2795 $line->info_bits,
2796 $line->date_start,
2797 $line->date_end,
2798 $line->product_type,
2799 $line->fk_parent_line,
2800 $line->skip_update_total,
2801 $line->fk_fournprice,
2802 $line->pa_ht,
2803 $line->label,
2804 $line->special_code,
2805 $line->array_options,
2806 $line->fk_unit,
2807 $line->multicurrency_subprice
2808 );
2809 break;
2810 case 'facture':
2813 '@phan-var-force Facture $this';
2814 '@phan-var-force FactureLigne $line';
2815 $this->updateline(
2816 $line->id,
2817 ($line->description ? $line->description : $line->desc),
2818 $line->subprice,
2819 $line->qty,
2820 $line->remise_percent,
2821 $line->date_start,
2822 $line->date_end,
2823 $line->tva_tx,
2824 $line->localtax1_tx,
2825 $line->localtax2_tx,
2826 'HT',
2827 $line->info_bits,
2828 $line->product_type,
2829 $line->fk_parent_line,
2830 $line->skip_update_total,
2831 $line->fk_fournprice,
2832 $line->pa_ht,
2833 $line->label,
2834 $line->special_code,
2835 $line->array_options,
2836 $line->situation_percent,
2837 $line->fk_unit,
2838 $line->multicurrency_subprice
2839 );
2840 break;
2841 case 'supplier_proposal':
2844 '@phan-var-force SupplierProposal $this';
2845 '@phan-var-force SupplierProposalLine $line';
2846 $this->updateline(
2847 $line->id,
2848 $line->subprice,
2849 $line->qty,
2850 $line->remise_percent,
2851 $line->tva_tx,
2852 $line->localtax1_tx,
2853 $line->localtax2_tx,
2854 ($line->description ? $line->description : $line->desc),
2855 'HT',
2856 $line->info_bits,
2857 $line->special_code,
2858 $line->fk_parent_line,
2859 $line->skip_update_total,
2860 $line->fk_fournprice,
2861 $line->pa_ht,
2862 $line->label,
2863 $line->product_type,
2864 $line->array_options,
2865 $line->ref_fourn,
2866 $line->multicurrency_subprice
2867 );
2868 break;
2869 case 'order_supplier':
2872 '@phan-var-force CommandeFournisseur $this';
2873 '@phan-var-force CommandeFournisseurLigne $line';
2874 $this->updateline(
2875 $line->id,
2876 ($line->description ? $line->description : $line->desc),
2877 $line->subprice,
2878 $line->qty,
2879 $line->remise_percent,
2880 $line->tva_tx,
2881 $line->localtax1_tx,
2882 $line->localtax2_tx,
2883 'HT',
2884 $line->info_bits,
2885 $line->product_type,
2886 0,
2887 $line->date_start,
2888 $line->date_end,
2889 $line->array_options,
2890 $line->fk_unit,
2891 $line->multicurrency_subprice,
2892 $line->ref_supplier
2893 );
2894 break;
2895 case 'invoice_supplier':
2898 '@phan-var-force FactureFournisseur $this';
2899 '@phan-var-force SupplierInvoiceLIne $line';
2900 $this->updateline(
2901 $line->id,
2902 ($line->description ? $line->description : $line->desc),
2903 $line->subprice,
2904 $line->tva_tx,
2905 $line->localtax1_tx,
2906 $line->localtax2_tx,
2907 $line->qty,
2908 0,
2909 'HT',
2910 $line->info_bits,
2911 $line->product_type,
2912 $line->remise_percent,
2913 0,
2914 $line->date_start,
2915 $line->date_end,
2916 $line->array_options,
2917 $line->fk_unit,
2918 $line->multicurrency_subprice,
2919 $line->ref_supplier
2920 );
2921 break;
2922 default:
2923 dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
2924 break;
2925 }
2926 }
2927 }
2928
2929 return 1;
2930 } else {
2931 dol_syslog(get_class($this).'::setMulticurrencyRate Error '.$sql.' - '.$this->db->error());
2932 $this->error = $this->db->error();
2933 return -1;
2934 }
2935 } else {
2936 dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
2937 $this->error = 'Status of the object is incompatible '.$this->status;
2938 return -2;
2939 }
2940 }
2941
2949 public function setPaymentTerms($id, $deposit_percent = null)
2950 {
2951 dol_syslog(get_class($this).'::setPaymentTerms('.$id.', '.var_export($deposit_percent, true).')');
2952 if ($this->status >= 0 || $this->element == 'societe') {
2953 // TODO uniformize field name
2954 $fieldname = 'fk_cond_reglement';
2955 if ($this->element == 'societe') {
2956 $fieldname = 'cond_reglement';
2957 }
2958 if (get_class($this) == 'Fournisseur') {
2959 $fieldname = 'cond_reglement_supplier';
2960 }
2961
2962 if (empty($deposit_percent) || $deposit_percent < 0) {
2963 $deposit_percent = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $id);
2964 }
2965
2966 if ($deposit_percent > 100) {
2967 $deposit_percent = 100;
2968 }
2969
2970 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
2971 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
2972 if (in_array($this->table_element, array('propal', 'commande', 'societe'))) {
2973 $sql .= " , deposit_percent = " . (empty($deposit_percent) ? 'NULL' : "'".$this->db->escape($deposit_percent)."'");
2974 }
2975 $sql .= ' WHERE rowid='.((int) $this->id);
2976
2977 if ($this->db->query($sql)) {
2978 $this->cond_reglement_id = $id;
2979 // for supplier
2980 if (get_class($this) == 'Fournisseur') {
2981 $this->cond_reglement_supplier_id = $id;
2982 }
2983 $this->cond_reglement = $id; // for compatibility
2984 $this->deposit_percent = $deposit_percent;
2985 return 1;
2986 } else {
2987 dol_syslog(get_class($this).'::setPaymentTerms Error '.$sql.' - '.$this->db->error());
2988 $this->error = $this->db->error();
2989 return -1;
2990 }
2991 } else {
2992 dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
2993 $this->error = 'Status of the object is incompatible '.$this->status;
2994 return -2;
2995 }
2996 }
2997
3004 public function setTransportMode($id)
3005 {
3006 dol_syslog(get_class($this).'::setTransportMode('.$id.')');
3007 if ($this->status >= 0 || $this->element == 'societe') {
3008 $fieldname = 'fk_transport_mode';
3009 if ($this->element == 'societe') {
3010 $fieldname = 'transport_mode';
3011 }
3012 if (get_class($this) == 'Fournisseur') {
3013 $fieldname = 'transport_mode_supplier';
3014 }
3015
3016 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3017 $sql .= " SET ".$fieldname." = ".(($id > 0 || $id == '0') ? ((int) $id) : 'NULL');
3018 $sql .= ' WHERE rowid='.((int) $this->id);
3019
3020 if ($this->db->query($sql)) {
3021 $this->transport_mode_id = $id;
3022 // for supplier
3023 if (get_class($this) == 'Fournisseur') {
3024 $this->transport_mode_supplier_id = $id;
3025 }
3026 return 1;
3027 } else {
3028 dol_syslog(get_class($this).'::setTransportMode Error '.$sql.' - '.$this->db->error());
3029 $this->error = $this->db->error();
3030 return -1;
3031 }
3032 } else {
3033 dol_syslog(get_class($this).'::setTransportMode, status of the object is incompatible');
3034 $this->error = 'Status of the object is incompatible '.$this->status;
3035 return -2;
3036 }
3037 }
3038
3046 {
3047 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms('.$id.')');
3048 if ($this->status >= 0 || $this->element == 'societe') {
3049 $fieldname = 'retained_warranty_fk_cond_reglement';
3050
3051 $sql = 'UPDATE '.$this->db->prefix().$this->table_element;
3052 $sql .= " SET ".$fieldname." = ".((int) $id);
3053 $sql .= ' WHERE rowid='.((int) $this->id);
3054
3055 if ($this->db->query($sql)) {
3056 $this->retained_warranty_fk_cond_reglement = $id;
3057 return 1;
3058 } else {
3059 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms Error '.$sql.' - '.$this->db->error());
3060 $this->error = $this->db->error();
3061 return -1;
3062 }
3063 } else {
3064 dol_syslog(get_class($this).'::setRetainedWarrantyPaymentTerms, status of the object is incompatible');
3065 $this->error = 'Status of the object is incompatible '.$this->status;
3066 return -2;
3067 }
3068 }
3069
3077 public function setDeliveryAddress($id)
3078 {
3079 $fieldname = 'fk_delivery_address';
3080 if ($this->element == 'delivery' || $this->element == 'shipping') {
3081 $fieldname = 'fk_address';
3082 }
3083
3084 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ".$fieldname." = ".((int) $id);
3085 $sql .= " WHERE rowid = ".((int) $this->id)." AND fk_statut = 0";
3086
3087 if ($this->db->query($sql)) {
3088 $this->fk_delivery_address = $id;
3089 return 1;
3090 } else {
3091 $this->error = $this->db->error();
3092 dol_syslog(get_class($this).'::setDeliveryAddress Error '.$this->error);
3093 return -1;
3094 }
3095 }
3096
3097
3106 public function setShippingMethod($shipping_method_id, $notrigger = 0, $userused = null)
3107 {
3108 global $user;
3109
3110 if (empty($userused)) {
3111 $userused = $user;
3112 }
3113
3114 $error = 0;
3115
3116 if (!$this->table_element) {
3117 dol_syslog(get_class($this)."::setShippingMethod was called on object with property table_element not defined", LOG_ERR);
3118 return -1;
3119 }
3120
3121 $this->db->begin();
3122
3123 if ($shipping_method_id < 0) {
3124 $shipping_method_id = 'NULL';
3125 }
3126 dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
3127
3128 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3129 $sql .= " SET fk_shipping_method = ".((int) $shipping_method_id);
3130 $sql .= " WHERE rowid=".((int) $this->id);
3131 $resql = $this->db->query($sql);
3132 if (!$resql) {
3133 dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
3134 $this->error = $this->db->lasterror();
3135 $error++;
3136 } else {
3137 if (!$notrigger) {
3138 // Call trigger
3139 $this->context = array('shippingmethodupdate' => 1);
3140 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
3141 if ($result < 0) {
3142 $error++;
3143 }
3144 // End call trigger
3145 }
3146 }
3147 if ($error) {
3148 $this->db->rollback();
3149 return -1;
3150 } else {
3151 $this->shipping_method_id = ($shipping_method_id == 'NULL') ? null : $shipping_method_id;
3152 $this->db->commit();
3153 return 1;
3154 }
3155 }
3156
3157
3164 public function setWarehouse($warehouse_id)
3165 {
3166 if (!$this->table_element) {
3167 dol_syslog(get_class($this)."::setWarehouse was called on object with property table_element not defined", LOG_ERR);
3168 return -1;
3169 }
3170 if ($warehouse_id < 0) {
3171 $warehouse_id = 'NULL';
3172 }
3173 dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
3174
3175 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3176 $sql .= " SET fk_warehouse = ".((int) $warehouse_id);
3177 $sql .= " WHERE rowid=".((int) $this->id);
3178
3179 if ($this->db->query($sql)) {
3180 $this->warehouse_id = ($warehouse_id == 'NULL') ? null : $warehouse_id;
3181 return 1;
3182 } else {
3183 dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
3184 $this->error = $this->db->error();
3185 return 0;
3186 }
3187 }
3188
3189
3197 public function setDocModel($user, $modelpdf)
3198 {
3199 if (!$this->table_element) {
3200 dol_syslog(get_class($this)."::setDocModel was called on object with property table_element not defined", LOG_ERR);
3201 return -1;
3202 }
3203
3204 $newmodelpdf = dol_trunc($modelpdf, 255);
3205
3206 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3207 $sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
3208 $sql .= " WHERE rowid = ".((int) $this->id);
3209
3210 dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
3211 $resql = $this->db->query($sql);
3212 if ($resql) {
3213 $this->model_pdf = $modelpdf;
3214 return 1;
3215 } else {
3216 dol_print_error($this->db);
3217 return 0;
3218 }
3219 }
3220
3221
3230 public function setBankAccount($fk_account, $notrigger = 0, $userused = null)
3231 {
3232 global $user;
3233
3234 if (empty($userused)) {
3235 $userused = $user;
3236 }
3237
3238 $error = 0;
3239
3240 if (!$this->table_element) {
3241 dol_syslog(get_class($this)."::setBankAccount was called on object with property table_element not defined", LOG_ERR);
3242 return -1;
3243 }
3244 $this->db->begin();
3245
3246 if ($fk_account < 0) {
3247 $fk_account = 'NULL';
3248 }
3249 dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
3250
3251 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3252 $sql .= " SET fk_account = ".((int) $fk_account);
3253 $sql .= " WHERE rowid=".((int) $this->id);
3254
3255 $resql = $this->db->query($sql);
3256 if (!$resql) {
3257 dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
3258 $this->error = $this->db->lasterror();
3259 $error++;
3260 } else {
3261 if (!$notrigger) {
3262 // Call trigger
3263 $this->context['bankaccountupdate'] = 1;
3264 $triggerName = strtoupper(get_class($this)).'_MODIFY';
3265 // Special cases
3266 if ($triggerName == 'FACTUREREC_MODIFY') {
3267 $triggerName = 'BILLREC_MODIFY';
3268 }
3269 $result = $this->call_trigger($triggerName, $userused);
3270 if ($result < 0) {
3271 $error++;
3272 }
3273 // End call trigger
3274 }
3275 }
3276 if ($error) {
3277 $this->db->rollback();
3278 return -1;
3279 } else {
3280 $this->fk_account = ($fk_account == 'NULL') ? null : $fk_account;
3281 $this->db->commit();
3282 return 1;
3283 }
3284 }
3285
3286
3287 // TODO: Move line related operations to CommonObjectLine?
3288
3289 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3299 public function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
3300 {
3301 // phpcs:enable
3302 if (!$this->table_element_line) {
3303 dol_syslog(get_class($this)."::line_order was called on object with property table_element_line not defined", LOG_ERR);
3304 return -1;
3305 }
3306 if (!$this->fk_element) {
3307 dol_syslog(get_class($this)."::line_order was called on object with property fk_element not defined", LOG_ERR);
3308 return -1;
3309 }
3310
3311 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3312 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3313 $fieldposition = 'position';
3314 }
3315
3316 // Count number of lines to reorder (according to choice $renum)
3317 $nl = 0;
3318 $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
3319 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3320 if (!$renum) {
3321 $sql .= " AND " . $fieldposition . " = 0";
3322 }
3323 if ($renum) {
3324 $sql .= " AND " . $fieldposition . " <> 0";
3325 }
3326
3327 dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
3328 $resql = $this->db->query($sql);
3329 if ($resql) {
3330 $row = $this->db->fetch_row($resql);
3331 $nl = $row[0];
3332 } else {
3333 dol_print_error($this->db);
3334 }
3335 if ($nl > 0) {
3336 // The goal of this part is to reorder all lines, with all children lines sharing the same counter that parents.
3337 $rows = array();
3338
3339 // We first search all lines that are parent lines (for multilevel details lines)
3340 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3341 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3342 if ($fk_parent_line) {
3343 $sql .= ' AND fk_parent_line IS NULL';
3344 }
3345 $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
3346
3347 dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
3348 $resql = $this->db->query($sql);
3349 if ($resql) {
3350 $i = 0;
3351 $num = $this->db->num_rows($resql);
3352 while ($i < $num) {
3353 $row = $this->db->fetch_row($resql);
3354 $rows[] = $row[0]; // Add parent line into array rows
3355 $children = $this->getChildrenOfLine($row[0]);
3356 if (!empty($children)) {
3357 foreach ($children as $child) {
3358 array_push($rows, $child);
3359 }
3360 }
3361 $i++;
3362 }
3363
3364 // Now we set a new number for each lines (parent and children with children included into parent tree)
3365 if (!empty($rows)) {
3366 foreach ($rows as $key => $row) {
3367 $this->updateRangOfLine($row, ($key + 1));
3368 }
3369 }
3370 } else {
3371 dol_print_error($this->db);
3372 }
3373 }
3374 return 1;
3375 }
3376
3384 public function getChildrenOfLine($id, $includealltree = 0)
3385 {
3386 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3387 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3388 $fieldposition = 'position';
3389 }
3390
3391 $rows = array();
3392
3393 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3394 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3395 $sql .= ' AND fk_parent_line = '.((int) $id);
3396 $sql .= " ORDER BY " . $fieldposition . " ASC";
3397
3398 dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
3399
3400 $resql = $this->db->query($sql);
3401 if ($resql) {
3402 if ($this->db->num_rows($resql) > 0) {
3403 while ($row = $this->db->fetch_row($resql)) {
3404 $rows[] = $row[0];
3405 if (!empty($includealltree) && $includealltree <= 1000) { // Test <= 1000 is a protection in depth of recursive call to avoid infinite loop
3406 $rows = array_merge($rows, $this->getChildrenOfLine($row[0], $includealltree + 1));
3407 }
3408 }
3409 }
3410 }
3411 return $rows;
3412 }
3413
3414 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3422 public function line_up($rowid, $fk_parent_line = true)
3423 {
3424 // phpcs:enable
3425 $this->line_order(false, 'ASC', $fk_parent_line);
3426
3427 // Get rang of line
3428 $rang = $this->getRangOfLine($rowid);
3429
3430 // Update position of line
3431 $this->updateLineUp($rowid, $rang);
3432 }
3433
3434 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3442 public function line_down($rowid, $fk_parent_line = true)
3443 {
3444 // phpcs:enable
3445 $this->line_order(false, 'ASC', $fk_parent_line);
3446
3447 // Get rang of line
3448 $rang = $this->getRangOfLine($rowid);
3449
3450 // Get max value for rang
3451 $max = $this->line_max();
3452
3453 // Update position of line
3454 $this->updateLineDown($rowid, $rang, $max);
3455 }
3456
3464 public function updateRangOfLine($rowid, $rang)
3465 {
3466 global $hookmanager;
3467 $fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
3468 if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3469 $fieldposition = 'position';
3470 }
3471
3472 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3473 $sql .= ' WHERE rowid = '.((int) $rowid);
3474
3475 dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
3476 if (!$this->db->query($sql)) {
3477 dol_print_error($this->db);
3478 return -1;
3479 } else {
3480 $parameters = array('rowid' => $rowid, 'rang' => $rang, 'fieldposition' => $fieldposition);
3481 $action = '';
3482 $reshook = $hookmanager->executeHooks('afterRankOfLineUpdate', $parameters, $this, $action);
3483 return 1;
3484 }
3485 }
3486
3487 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3494 public function line_ajaxorder($rows)
3495 {
3496 // phpcs:enable
3497 $num = count($rows);
3498 for ($i = 0; $i < $num; $i++) {
3499 $this->updateRangOfLine($rows[$i], ($i + 1));
3500 }
3501 }
3502
3510 public function updateLineUp($rowid, $rang)
3511 {
3512 if ($rang > 1) {
3513 $fieldposition = 'rang';
3514 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3515 $fieldposition = 'position';
3516 }
3517
3518 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3519 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3520 $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
3521 if ($this->db->query($sql)) {
3522 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
3523 $sql .= ' WHERE rowid = '.((int) $rowid);
3524 if (!$this->db->query($sql)) {
3525 dol_print_error($this->db);
3526 }
3527 } else {
3528 dol_print_error($this->db);
3529 }
3530 }
3531 }
3532
3541 public function updateLineDown($rowid, $rang, $max)
3542 {
3543 if ($rang < $max) {
3544 $fieldposition = 'rang';
3545 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3546 $fieldposition = 'position';
3547 }
3548
3549 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
3550 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3551 $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
3552 if ($this->db->query($sql)) {
3553 $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
3554 $sql .= ' WHERE rowid = '.((int) $rowid);
3555 if (!$this->db->query($sql)) {
3556 dol_print_error($this->db);
3557 }
3558 } else {
3559 dol_print_error($this->db);
3560 }
3561 }
3562 }
3563
3570 public function getRangOfLine($rowid)
3571 {
3572 $fieldposition = 'rang';
3573 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3574 $fieldposition = 'position';
3575 }
3576
3577 $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
3578 $sql .= " WHERE rowid = ".((int) $rowid);
3579
3580 dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
3581 $resql = $this->db->query($sql);
3582 if ($resql) {
3583 $row = $this->db->fetch_row($resql);
3584 return $row[0];
3585 }
3586
3587 return 0;
3588 }
3589
3596 public function getIdOfLine($rang)
3597 {
3598 $fieldposition = 'rang';
3599 if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
3600 $fieldposition = 'position';
3601 }
3602
3603 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
3604 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3605 $sql .= " AND " . $fieldposition . " = ".((int) $rang);
3606 $resql = $this->db->query($sql);
3607 if ($resql) {
3608 $row = $this->db->fetch_row($resql);
3609 return $row[0];
3610 }
3611
3612 return 0;
3613 }
3614
3615 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3622 public function line_max($fk_parent_line = 0)
3623 {
3624 // phpcs:enable
3625 $positionfield = 'rang';
3626 if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
3627 $positionfield = 'position';
3628 }
3629
3630 // Search the last rang with fk_parent_line
3631 if ($fk_parent_line) {
3632 $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3633 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3634 $sql .= " AND fk_parent_line = ".((int) $fk_parent_line);
3635
3636 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3637 $resql = $this->db->query($sql);
3638 if ($resql) {
3639 $row = $this->db->fetch_row($resql);
3640 if (!empty($row[0])) {
3641 return $row[0];
3642 } else {
3643 return $this->getRangOfLine($fk_parent_line);
3644 }
3645 }
3646 } else {
3647 // If not, search the last rang of element
3648 $sql = "SELECT max(".$positionfield.") FROM ".$this->db->prefix().$this->table_element_line;
3649 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3650
3651 dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
3652 $resql = $this->db->query($sql);
3653 if ($resql) {
3654 $row = $this->db->fetch_row($resql);
3655 return $row[0];
3656 }
3657 }
3658
3659 return 0;
3660 }
3661
3662 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3669 public function update_ref_ext($ref_ext)
3670 {
3671 // phpcs:enable
3672 if (!$this->table_element) {
3673 dol_syslog(get_class($this)."::update_ref_ext was called on object with property table_element not defined", LOG_ERR);
3674 return -1;
3675 }
3676
3677 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3678 $sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
3679 // @phan-suppress-next-line PhanUndeclaredProperty
3680 $sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".((int) $this->id);
3681
3682 dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
3683 if ($this->db->query($sql)) {
3684 $this->ref_ext = $ref_ext;
3685 return 1;
3686 } else {
3687 $this->error = $this->db->error();
3688 return -1;
3689 }
3690 }
3691
3692 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3701 public function update_note($note, $suffix = '', $notrigger = 0)
3702 {
3703 // phpcs:enable
3704 global $user;
3705
3706 if (!$this->table_element) {
3707 $this->error = 'update_note was called on object with property table_element not defined';
3708 dol_syslog(get_class($this)."::update_note was called on object with property table_element not defined", LOG_ERR);
3709 return -1;
3710 }
3711 if (!in_array($suffix, array('', '_public', '_private'))) {
3712 $this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
3713 dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
3714 return -2;
3715 }
3716
3717 $newsuffix = $suffix;
3718
3719 // Special case
3720 if ($this->table_element == 'product' && $newsuffix == '_private') {
3721 $newsuffix = '';
3722 }
3723 if (in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
3724 $fieldusermod = "fk_user_mod";
3725 } elseif ($this->table_element == 'ecm_files') {
3726 $fieldusermod = "fk_user_m";
3727 } else {
3728 $fieldusermod = "fk_user_modif";
3729 }
3730 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
3731 $sql .= " SET note".$newsuffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
3732 $sql .= ", ".$fieldusermod." = ".((int) $user->id);
3733 $sql .= " WHERE rowid = ".((int) $this->id);
3734
3735 dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
3736 if ($this->db->query($sql)) {
3737 if ($suffix == '_public') {
3738 $this->note_public = $note;
3739 } elseif ($suffix == '_private') {
3740 $this->note_private = $note;
3741 } else {
3742 $this->note = $note; // deprecated
3743 $this->note_private = $note;
3744 }
3745 if (empty($notrigger)) {
3746 switch ($this->element) {
3747 case 'societe':
3748 $trigger_name = 'COMPANY_MODIFY';
3749 break;
3750 case 'commande':
3751 $trigger_name = 'ORDER_MODIFY';
3752 break;
3753 case 'facture':
3754 $trigger_name = 'BILL_MODIFY';
3755 break;
3756 case 'invoice_supplier':
3757 $trigger_name = 'BILL_SUPPLIER_MODIFY';
3758 break;
3759 case 'facturerec':
3760 $trigger_name = 'BILLREC_MODIFIY';
3761 break;
3762 case 'expensereport':
3763 $trigger_name = 'EXPENSE_REPORT_MODIFY';
3764 break;
3765 default:
3766 $trigger_name = strtoupper($this->element) . '_MODIFY';
3767 }
3768 $ret = $this->call_trigger($trigger_name, $user);
3769 if ($ret < 0) {
3770 return -1;
3771 }
3772 }
3773 return 1;
3774 } else {
3775 $this->error = $this->db->lasterror();
3776 return -1;
3777 }
3778 }
3779
3780 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3789 public function update_note_public($note)
3790 {
3791 // phpcs:enable
3792 return $this->update_note($note, '_public');
3793 }
3794
3795 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3806 public function update_price($exclspec = 0, $roundingadjust = 'auto', $nodatabaseupdate = 0, $seller = null)
3807 {
3808 // phpcs:enable
3809 global $conf, $hookmanager, $action;
3810
3811 $parameters = array('exclspec' => $exclspec, 'roundingadjust' => $roundingadjust, 'nodatabaseupdate' => $nodatabaseupdate, 'seller' => $seller);
3812 $reshook = $hookmanager->executeHooks('updateTotalPrice', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3813 if ($reshook > 0) {
3814 return 1; // replacement code
3815 } elseif ($reshook < 0) {
3816 return -1; // failure
3817 } // reshook = 0 => execute normal code
3818
3819 // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
3820 $isElementForSupplier = false;
3821 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND'; // const for customer by default
3822 $MODULE = "";
3823 if ($this->element == 'propal') {
3824 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
3825 } elseif ($this->element == 'commande' || $this->element == 'order') {
3826 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
3827 } elseif ($this->element == 'facture' || $this->element == 'invoice') {
3828 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
3829 } elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier' || $this->element == 'invoice_supplier_rec') {
3830 $isElementForSupplier = true;
3831 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
3832 } elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') {
3833 $isElementForSupplier = true;
3834 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
3835 } elseif ($this->element == 'supplier_proposal') {
3836 $isElementForSupplier = true;
3837 $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
3838 }
3839 if ($isElementForSupplier) {
3840 $roundTotalConstName = 'MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND_SUPPLIER'; // const for supplier
3841 }
3842
3843 if (!empty($MODULE)) {
3844 if (getDolGlobalString($MODULE)) {
3845 $modsactivated = explode(',', getDolGlobalString($MODULE));
3846 foreach ($modsactivated as $mod) {
3847 if (isModEnabled($mod)) {
3848 return 1; // update was disabled by specific setup
3849 }
3850 }
3851 }
3852 }
3853
3854 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
3855
3856 $forcedroundingmode = $roundingadjust;
3857 if ($forcedroundingmode == 'auto' && isset($conf->global->{$roundTotalConstName})) {
3858 $forcedroundingmode = getDolGlobalString($roundTotalConstName);
3859 } elseif ($forcedroundingmode == 'auto') {
3860 $forcedroundingmode = '0';
3861 }
3862
3863 $error = 0;
3864
3865 $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
3866
3867 // Define constants to find lines to sum (field name int the table_element_line not into table_element)
3868 $fieldtva = 'total_tva';
3869 $fieldlocaltax1 = 'total_localtax1';
3870 $fieldlocaltax2 = 'total_localtax2';
3871 $fieldup = 'subprice';
3872 $base_price_type = 'HT';
3873 if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3874 $fieldtva = 'tva';
3875 $fieldup = 'pu_ht';
3876 }
3877 if ($this->element == 'invoice_supplier_rec') {
3878 $fieldup = 'pu_ht';
3879 }
3880 if ($this->element == 'expensereport') {
3881 // Force rounding mode to '0', otherwise when you set MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND to 1, you may have lines with different totals.
3882 // 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
3883 // and 5,16 on HT total and 1,04 on VAT total to get 6,20 on TTT total on second line (see #30051).
3884 $forcedroundingmode = '0';
3885 $fieldup = 'value_unit';
3886 $base_price_type = 'TTC';
3887 }
3888
3889 $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,";
3890 $sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
3891 if ($this->table_element_line == 'facturedet') {
3892 $sql .= ', situation_percent';
3893 }
3894 $sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
3895 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
3896 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
3897 if ($exclspec) {
3898 $product_field = 'product_type';
3899 if ($this->table_element_line == 'contratdet') {
3900 $product_field = ''; // contratdet table has no product_type field
3901 }
3902 if ($product_field) {
3903 $sql .= " AND ".$product_field." <> 9";
3904 }
3905 }
3906 $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
3907
3908 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
3909
3910 $resql = $this->db->query($sql);
3911 if ($resql) {
3912 $this->total_ht = 0;
3913 $this->total_tva = 0;
3914 $this->total_localtax1 = 0;
3915 $this->total_localtax2 = 0;
3916 $this->total_ttc = 0;
3917 $total_ht_by_vats = array();
3918 $total_tva_by_vats = array();
3919 $total_ttc_by_vats = array();
3920 $this->multicurrency_total_ht = 0;
3921 $this->multicurrency_total_tva = 0;
3922 $this->multicurrency_total_ttc = 0;
3923
3924 $this->db->begin();
3925
3926 $num = $this->db->num_rows($resql);
3927 $i = 0;
3928 while ($i < $num) {
3929 $obj = $this->db->fetch_object($resql);
3930
3931 // Note: There is no check on detail line and no check on total, if $forcedroundingmode = '0'
3932 $parameters = array('fk_element' => $obj->rowid);
3933 $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3934
3935 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'
3936 // This part of code is to fix data. We should not call it too often.
3937 $localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
3938 $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);
3939
3940 $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.
3941 $diff_on_current_total = price2num($obj->total_ttc - $obj->total_ht - $obj->total_tva - $obj->total_localtax1 - $obj->total_localtax2, 'MT', 1);
3942 //var_dump($obj->total_ht.' '.$obj->total_tva.' '.$obj->total_localtax1.' '.$obj->total_localtax2.' => '.$obj->total_ttc);
3943 //var_dump($diff_when_using_price_ht.' '.$diff_on_current_total);
3944
3945 if ($diff_on_current_total) {
3946 // This should not happen, we should always have in table: total_ttc = total_ht + total_vat + total_localtax1 + total_localtax2
3947 $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);
3948 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);
3949 $resqlfix = $this->db->query($sqlfix);
3950 if (!$resqlfix) {
3951 dol_print_error($this->db, 'Failed to update line');
3952 }
3953 $obj->total_tva = $tmpcal[1];
3954 $obj->total_ttc = $tmpcal[2];
3955 } elseif ($diff_when_using_price_ht) {
3956 // After calculation from HT, total is consistent but we have found a difference between VAT part in calculation and into database and
3957 // we ask to force the use of rounding on line (like done on calculation) so we force update of line
3958 $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);
3959 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);
3960 $resqlfix = $this->db->query($sqlfix);
3961 if (!$resqlfix) {
3962 dol_print_error($this->db, 'Failed to update line');
3963 }
3964 $obj->total_tva = $tmpcal[1];
3965 $obj->total_ttc = $tmpcal[2];
3966 }
3967 }
3968
3969 $this->total_ht += $obj->total_ht; // The field visible at end of line detail
3970 $this->total_tva += $obj->total_tva;
3971 $this->total_localtax1 += $obj->total_localtax1;
3972 $this->total_localtax2 += $obj->total_localtax2;
3973 $this->total_ttc += $obj->total_ttc;
3974 $this->multicurrency_total_ht += $obj->multicurrency_total_ht; // The field visible at end of line detail
3975 $this->multicurrency_total_tva += $obj->multicurrency_total_tva;
3976 $this->multicurrency_total_ttc += $obj->multicurrency_total_ttc;
3977
3978 if (!isset($total_ht_by_vats[$obj->vatrate])) {
3979 $total_ht_by_vats[$obj->vatrate] = 0;
3980 }
3981 if (!isset($total_tva_by_vats[$obj->vatrate])) {
3982 $total_tva_by_vats[$obj->vatrate] = 0;
3983 }
3984 if (!isset($total_ttc_by_vats[$obj->vatrate])) {
3985 $total_ttc_by_vats[$obj->vatrate] = 0;
3986 }
3987 $total_ht_by_vats[$obj->vatrate] += $obj->total_ht;
3988 $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
3989 $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
3990
3991 if ($forcedroundingmode == '1') { // Check if we need adjustment onto line for vat. TODO This works on the company currency but not on foreign currency
3992 if ($base_price_type == 'TTC') {
3993 $tmpvat = price2num($total_ttc_by_vats[$obj->vatrate] * $obj->vatrate / (100 + $obj->vatrate), 'MT', 1);
3994 } else {
3995 $tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3996 }
3997 $diff = price2num($total_tva_by_vats[$obj->vatrate] - (float) $tmpvat, 'MT', 1);
3998 //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";
3999 if ($diff) {
4000 $maxdiff = (10 * pow(10, -1 * getDolGlobalInt('MAIN_MAX_DECIMALS_TOT', 0)));
4001 if (abs((float) $diff) > $maxdiff) {
4002 // If error is more than 10 times the accuracy of rounding. This should not happen.
4003 $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.';
4004 dol_syslog($errmsg, LOG_WARNING);
4005 $this->error = $errmsg;
4006 $error++;
4007 break;
4008 }
4009
4010 if ($base_price_type == 'TTC') {
4011 $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);
4012 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);
4013 } else {
4014 $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);
4015 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);
4016 }
4017
4018 $resqlfix = $this->db->query($sqlfix);
4019
4020 if (!$resqlfix) {
4021 dol_print_error($this->db, 'Failed to update line');
4022 }
4023
4024 $this->total_tva = (float) price2num($this->total_tva - (float) $diff, '', 1);
4025 $total_tva_by_vats[$obj->vatrate] = (float) price2num($total_tva_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4026 if ($base_price_type == 'TTC') {
4027 $this->total_ht = (float) price2num($this->total_ht + (float) $diff, '', 1);
4028 $total_ht_by_vats[$obj->vatrate] = (float) price2num($total_ht_by_vats[$obj->vatrate] + (float) $diff, '', 1);
4029 } else {
4030 $this->total_ttc = (float) price2num($this->total_ttc - (float) $diff, '', 1);
4031 $total_ttc_by_vats[$obj->vatrate] = (float) price2num($total_ttc_by_vats[$obj->vatrate] - (float) $diff, '', 1);
4032 }
4033 }
4034 }
4035
4036 $i++;
4037 }
4038
4039 // Add revenue stamp to total
4040 // @phan-suppress-next-line PhanUndeclaredProperty
4041 $this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
4042 // @phan-suppress-next-line PhanUndeclaredProperty
4043 $this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
4044
4045 // Situations totals
4046 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
4047 '@phan-var-force Facture $this';
4048 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
4049 if ($this->type != Facture::TYPE_CREDIT_NOTE) { // @phpstan-ignore-line
4050 if (getDolGlobalInt('INVOICE_USE_SITUATION') != 2) {
4051 $prev_sits = $this->get_prev_sits();
4052
4053 foreach ($prev_sits as $sit) { // $sit is an object Facture loaded with a fetch.
4054 $this->total_ht -= $sit->total_ht;
4055 $this->total_tva -= $sit->total_tva;
4056 $this->total_localtax1 -= $sit->total_localtax1;
4057 $this->total_localtax2 -= $sit->total_localtax2;
4058 $this->total_ttc -= $sit->total_ttc;
4059 $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
4060 $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
4061 $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
4062 }
4063 }
4064 }
4065 }
4066
4067 // Clean total
4068 $this->total_ht = (float) price2num($this->total_ht);
4069 $this->total_tva = (float) price2num($this->total_tva);
4070 $this->total_localtax1 = (float) price2num($this->total_localtax1);
4071 $this->total_localtax2 = (float) price2num($this->total_localtax2);
4072 $this->total_ttc = (float) price2num($this->total_ttc);
4073
4074 $this->db->free($resql);
4075
4076 // Now update global fields total_ht, total_ttc, total_tva, total_localtax1, total_localtax2, multicurrency_total_* of main object
4077 $fieldht = 'total_ht';
4078 $fieldtva = 'tva';
4079 $fieldlocaltax1 = 'localtax1';
4080 $fieldlocaltax2 = 'localtax2';
4081 $fieldttc = 'total_ttc';
4082 // Specific code for backward compatibility with old field names
4083 if (in_array($this->element, array('propal', 'commande', 'facture', 'facturerec', 'supplier_proposal', 'order_supplier', 'facture_fourn', 'invoice_supplier', 'invoice_supplier_rec', 'expensereport'))) {
4084 $fieldtva = 'total_tva';
4085 }
4086
4087 if (!$error && empty($nodatabaseupdate)) {
4088 $sql = "UPDATE ".$this->db->prefix().$this->table_element.' SET';
4089 $sql .= " ".$fieldht." = ".((float) price2num($this->total_ht, 'MT', 1)).",";
4090 $sql .= " ".$fieldtva." = ".((float) price2num($this->total_tva, 'MT', 1)).",";
4091 $sql .= " ".$fieldlocaltax1." = ".((float) price2num($this->total_localtax1, 'MT', 1)).",";
4092 $sql .= " ".$fieldlocaltax2." = ".((float) price2num($this->total_localtax2, 'MT', 1)).",";
4093 $sql .= " ".$fieldttc." = ".((float) price2num($this->total_ttc, 'MT', 1));
4094 $sql .= ", multicurrency_total_ht = ".((float) price2num($this->multicurrency_total_ht, 'MT', 1));
4095 $sql .= ", multicurrency_total_tva = ".((float) price2num($this->multicurrency_total_tva, 'MT', 1));
4096 $sql .= ", multicurrency_total_ttc = ".((float) price2num($this->multicurrency_total_ttc, 'MT', 1));
4097 $sql .= " WHERE rowid = ".((int) $this->id);
4098
4099 dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
4100 $resql = $this->db->query($sql);
4101
4102 if (!$resql) {
4103 $error++;
4104 $this->error = $this->db->lasterror();
4105 $this->errors[] = $this->db->lasterror();
4106 }
4107 }
4108
4109 if (!$error) {
4110 $this->db->commit();
4111 return 1;
4112 } else {
4113 $this->db->rollback();
4114 return -1;
4115 }
4116 } else {
4117 dol_print_error($this->db, 'Bad request in update_price');
4118 return -1;
4119 }
4120 }
4121
4122 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4133 public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0)
4134 {
4135 // phpcs:enable
4136 global $user, $hookmanager, $action;
4137 $origin = (!empty($origin) ? $origin : $this->origin);
4138 $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
4139 $f_user = isset($f_user) ? $f_user : $user;
4140
4141 // Special case
4142 if ($origin == 'order') {
4143 $origin = 'commande';
4144 }
4145 if ($origin == 'invoice') {
4146 $origin = 'facture';
4147 }
4148 if ($origin == 'invoice_template') {
4149 $origin = 'facturerec';
4150 }
4151 if ($origin == 'supplierorder') {
4152 $origin = 'order_supplier';
4153 }
4154
4155 // Add module part to target type
4156 $targettype = $this->getElementType();
4157
4158 $parameters = array('targettype' => $targettype);
4159 // Hook for explicitly set the targettype if it must be different than $this->element
4160 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4161 if ($reshook > 0) {
4162 if (!empty($hookmanager->resArray['targettype'])) {
4163 $targettype = $hookmanager->resArray['targettype'];
4164 }
4165 }
4166
4167 $this->db->begin();
4168 $error = 0;
4169
4170 $sql = "INSERT INTO " . $this->db->prefix() . "element_element (";
4171 $sql .= "fk_source";
4172 $sql .= ", sourcetype";
4173 $sql .= ", fk_target";
4174 $sql .= ", targettype";
4175 $sql .= ") VALUES (";
4176 $sql .= ((int) $origin_id);
4177 $sql .= ", '" . $this->db->escape($origin) . "'";
4178 $sql .= ", " . ((int) $this->id);
4179 $sql .= ", '" . $this->db->escape($targettype) . "'";
4180 $sql .= ")";
4181
4182 dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG);
4183 if ($this->db->query($sql)) {
4184 if (!$notrigger) {
4185 // Call trigger
4186 $this->context['link_origin'] = $origin;
4187 $this->context['link_origin_id'] = $origin_id;
4188 $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user);
4189 if ($result < 0) {
4190 $error++;
4191 }
4192 // End call triggers
4193 }
4194 } else {
4195 $this->error = $this->db->lasterror();
4196 $error++;
4197 }
4198
4199 if (!$error) {
4200 $this->db->commit();
4201 return 1;
4202 } else {
4203 $this->db->rollback();
4204 return 0;
4205 }
4206 }
4207
4213 public function getElementType()
4214 {
4215 // 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.
4216 // 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).
4217 $coreModule = array('knowledgemanagement', 'partnership', 'workstation', 'ticket', 'recruitment', 'eventorganization', 'asset');
4218 // Add module part to target type if object has $module property and isn't in core modules.
4219 return ((!empty($this->module) && !in_array($this->module, $coreModule)) ? $this->module.'_' : '').$this->element;
4220 }
4221
4222
4245 public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
4246 {
4247 global $conf, $hookmanager, $action;
4248
4249 // Important for pdf generation time reduction
4250 // This boolean is true if $this->linkedObjects has already been loaded with all objects linked without filter
4251 // If you need to force the reload, you can call clearObjectLinkedCache() before calling fetchObjectLinked()
4252 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4253 return 1;
4254 }
4255
4256 $this->linkedObjectsIds = array();
4257 $this->linkedObjects = array();
4258
4259 $justsource = false;
4260 $justtarget = false;
4261 $withtargettype = false;
4262 $withsourcetype = false;
4263
4264 $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
4265 // Hook for explicitly set the targettype if it must be differtent than $this->element
4266 $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4267 if ($reshook > 0) {
4268 if (!empty($hookmanager->resArray['sourcetype'])) {
4269 $sourcetype = $hookmanager->resArray['sourcetype'];
4270 }
4271 if (!empty($hookmanager->resArray['sourceid'])) {
4272 $sourceid = $hookmanager->resArray['sourceid'];
4273 }
4274 if (!empty($hookmanager->resArray['targettype'])) {
4275 $targettype = $hookmanager->resArray['targettype'];
4276 }
4277 if (!empty($hookmanager->resArray['targetid'])) {
4278 $targetid = $hookmanager->resArray['targetid'];
4279 }
4280 }
4281
4282 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
4283 $justsource = true; // the source (id and type) is a search criteria
4284 if (!empty($targettype)) {
4285 $withtargettype = true;
4286 }
4287 }
4288 if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
4289 $justtarget = true; // the target (id and type) is a search criteria
4290 if (!empty($sourcetype)) {
4291 $withsourcetype = true;
4292 }
4293 }
4294
4295 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4296 $targetid = (!empty($targetid) ? $targetid : $this->id);
4297 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4298 $targettype = (!empty($targettype) ? $targettype : $this->element);
4299
4300 /*if (empty($sourceid) && empty($targetid))
4301 {
4302 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
4303 return -1;
4304 }*/
4305
4306 // Links between objects are stored in table element_element
4307 $sql = "SELECT rowid, fk_source, sourcetype, fk_target, targettype";
4308 $sql .= " FROM ".$this->db->prefix()."element_element";
4309 $sql .= " WHERE ";
4310 if ($justsource || $justtarget) {
4311 if ($justsource) {
4312 $sql .= "fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."'";
4313 if ($withtargettype) {
4314 $sql .= " AND targettype = '".$this->db->escape($targettype)."'";
4315 }
4316 } elseif ($justtarget) {
4317 $sql .= "fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."'";
4318 if ($withsourcetype) {
4319 $sql .= " AND sourcetype = '".$this->db->escape($sourcetype)."'";
4320 }
4321 }
4322 } else {
4323 $sql .= "(fk_source = ".((int) $sourceid)." AND sourcetype = '".$this->db->escape($sourcetype)."')";
4324 $sql .= " ".$clause." (fk_target = ".((int) $targetid)." AND targettype = '".$this->db->escape($targettype)."')";
4325 if ($loadalsoobjects && $this->id > 0 && $sourceid == $this->id && $sourcetype == $this->element && $targetid == $this->id && $targettype == $this->element && $clause == 'OR') {
4326 $this->linkedObjectsFullLoaded[$this->id] = true;
4327 }
4328 }
4329 $sql .= " ORDER BY ".$orderby;
4330
4331 dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
4332 $resql = $this->db->query($sql);
4333 if ($resql) {
4334 $num = $this->db->num_rows($resql);
4335 $i = 0;
4336 while ($i < $num) {
4337 $obj = $this->db->fetch_object($resql);
4338 if ($justsource || $justtarget) {
4339 if ($justsource) {
4340 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4341 } elseif ($justtarget) {
4342 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4343 }
4344 } else {
4345 if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
4346 $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
4347 }
4348 if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
4349 $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
4350 }
4351 }
4352 $i++;
4353 }
4354
4355 if (!empty($this->linkedObjectsIds)) {
4356 $tmparray = $this->linkedObjectsIds;
4357 foreach ($tmparray as $objecttype => $objectids) { // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
4358 $element_properties = getElementProperties($objecttype);
4359 $element = $element_properties['element'];
4360 $classPath = $element_properties['classpath'];
4361 $classFile = $element_properties['classfile'];
4362 $className = $element_properties['classname'];
4363 $module = $element_properties['module'];
4364
4365 // Here $module, $classFile and $className are set, we can use them.
4366 if (isModEnabled($module) && (($element != $this->element) || $alsosametype)) {
4367 if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
4368 dol_include_once('/'.$classPath.'/'.$classFile.'.class.php');
4369 if (class_exists($className)) {
4370 foreach ($objectids as $i => $objectid) { // $i is rowid into llx_element_element
4371 $object = new $className($this->db);
4372 '@phan-var-force CommonObject $object';
4373 $ret = $object->fetch($objectid);
4374 if ($ret >= 0) {
4375 $this->linkedObjects[$objecttype][$i] = $object;
4376 }
4377 }
4378 }
4379 }
4380 } else {
4381 unset($this->linkedObjectsIds[$objecttype]);
4382 }
4383 }
4384 }
4385 return 1;
4386 } else {
4387 dol_print_error($this->db);
4388 return -1;
4389 }
4390 }
4391
4398 public function clearObjectLinkedCache()
4399 {
4400 if ($this->id > 0 && !empty($this->linkedObjectsFullLoaded[$this->id])) {
4401 unset($this->linkedObjectsFullLoaded[$this->id]);
4402 }
4403
4404 return 1;
4405 }
4406
4419 public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0)
4420 {
4421 global $user;
4422 $updatesource = false;
4423 $updatetarget = false;
4424 $f_user = isset($f_user) ? $f_user : $user;
4425
4426 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4427 $updatesource = true;
4428 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4429 $updatetarget = true;
4430 }
4431
4432 $this->db->begin();
4433 $error = 0;
4434
4435 $sql = "UPDATE " . $this->db->prefix() . "element_element SET ";
4436 if ($updatesource) {
4437 $sql .= "fk_source = " . ((int) $sourceid);
4438 $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'";
4439 $sql .= " WHERE fk_target = " . ((int) $this->id);
4440 $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'";
4441 } elseif ($updatetarget) {
4442 $sql .= "fk_target = " . ((int) $targetid);
4443 $sql .= ", targettype = '" . $this->db->escape($targettype) . "'";
4444 $sql .= " WHERE fk_source = " . ((int) $this->id);
4445 $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4446 }
4447
4448 dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG);
4449 if ($this->db->query($sql)) {
4450 if (!$notrigger) {
4451 // Call trigger
4452 $this->context['link_source_id'] = $sourceid;
4453 $this->context['link_source_type'] = $sourcetype;
4454 $this->context['link_target_id'] = $targetid;
4455 $this->context['link_target_type'] = $targettype;
4456 $result = $this->call_trigger('OBJECT_LINK_MODIFY', $f_user);
4457 if ($result < 0) {
4458 $error++;
4459 }
4460 // End call triggers
4461 }
4462 } else {
4463 $this->error = $this->db->lasterror();
4464 $error++;
4465 }
4466
4467 if (!$error) {
4468 $this->db->commit();
4469 return 1;
4470 } else {
4471 $this->db->rollback();
4472 return -1;
4473 }
4474 }
4475
4489 public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0)
4490 {
4491 global $user;
4492 $deletesource = false;
4493 $deletetarget = false;
4494 $f_user = isset($f_user) ? $f_user : $user;
4495
4496 if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
4497 $deletesource = true;
4498 } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
4499 $deletetarget = true;
4500 }
4501
4502 $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
4503 $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
4504 $targetid = (!empty($targetid) ? $targetid : $this->id);
4505 $targettype = (!empty($targettype) ? $targettype : $this->element);
4506 $this->db->begin();
4507 $error = 0;
4508
4509 if (!$notrigger) {
4510 // Call trigger
4511 $this->context['link_id'] = $rowid;
4512 $this->context['link_source_id'] = $sourceid;
4513 $this->context['link_source_type'] = $sourcetype;
4514 $this->context['link_target_id'] = $targetid;
4515 $this->context['link_target_type'] = $targettype;
4516 $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
4517 if ($result < 0) {
4518 $error++;
4519 }
4520 // End call triggers
4521 }
4522
4523 if (!$error) {
4524 $sql = "DELETE FROM " . $this->db->prefix() . "element_element";
4525 $sql .= " WHERE";
4526 if ($rowid > 0) {
4527 $sql .= " rowid = " . ((int) $rowid);
4528 } else {
4529 if ($deletesource) {
4530 $sql .= " fk_source = " . ((int) $sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
4531 $sql .= " AND fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "'";
4532 } elseif ($deletetarget) {
4533 $sql .= " fk_target = " . ((int) $targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
4534 $sql .= " AND fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
4535 } else {
4536 $sql .= " (fk_source = " . ((int) $this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
4537 $sql .= " OR";
4538 $sql .= " (fk_target = " . ((int) $this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
4539 }
4540 }
4541
4542 dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
4543 if (!$this->db->query($sql)) {
4544 $this->error = $this->db->lasterror();
4545 $this->errors[] = $this->error;
4546 $error++;
4547 }
4548 }
4549
4550 if (!$error) {
4551 $this->db->commit();
4552 return 1;
4553 } else {
4554 $this->db->rollback();
4555 return 0;
4556 }
4557 }
4558
4568 public static function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element)
4569 {
4570 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4571 return -1;
4572 }
4573 if (!preg_match('/^[_a-zA-Z0-9]+$/', $field_select)) {
4574 dol_syslog('Invalid value $field_select for parameter '.$field_select.' in call to getAllItemsLinkedByObjectID(). Must be a single field name.', LOG_ERR);
4575 }
4576
4577 global $db;
4578
4579 $sql = "SELECT ".$field_select." FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4580 $resql = $db->query($sql);
4581
4582 $TRes = array();
4583 if (!empty($resql)) {
4584 while ($res = $db->fetch_object($resql)) {
4585 $TRes[] = $res->{$field_select};
4586 }
4587 }
4588
4589 return $TRes;
4590 }
4591
4600 public static function getCountOfItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4601 {
4602 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4603 return -1;
4604 }
4605
4606 global $db;
4607
4608 $sql = "SELECT COUNT(*) as nb FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4609 $resql = $db->query($sql);
4610 $n = 0;
4611 if ($resql) {
4612 $res = $db->fetch_object($resql);
4613 if ($res) {
4614 $n = $res->nb;
4615 }
4616 }
4617
4618 return $n;
4619 }
4620
4629 public static function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element)
4630 {
4631 if (empty($fk_object_where) || empty($field_where) || empty($table_element)) {
4632 return -1;
4633 }
4634
4635 global $db;
4636
4637 $sql = "DELETE FROM ".$db->prefix().$table_element." WHERE ".$field_where." = ".((int) $fk_object_where);
4638 $resql = $db->query($sql);
4639
4640 if (empty($resql)) {
4641 return 0;
4642 }
4643
4644 return 1;
4645 }
4646
4657 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
4658 {
4659 global $user;
4660
4661 $savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
4662
4663 $elementId = (!empty($elementId) ? $elementId : $this->id);
4664 $elementTable = (!empty($elementType) ? $elementType : $this->table_element);
4665
4666 $this->db->begin();
4667
4668 if ($elementTable == 'facture_rec') {
4669 $fieldstatus = "suspended";
4670 }
4671 if ($elementTable == 'mailing') {
4672 $fieldstatus = "statut";
4673 }
4674 if ($elementTable == 'cronjob') {
4675 $fieldstatus = "status";
4676 }
4677 if ($elementTable == 'user') {
4678 $fieldstatus = "statut";
4679 }
4680 if ($elementTable == 'expensereport') {
4681 $fieldstatus = "fk_statut";
4682 }
4683 if ($elementTable == 'receptiondet_batch') {
4684 $fieldstatus = "status";
4685 }
4686 if ($elementTable == 'prelevement_bons') {
4687 $fieldstatus = "statut";
4688 }
4689 if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) {
4690 $fieldstatus = 'status';
4691 }
4692
4693 $sql = "UPDATE ".$this->db->prefix().$this->db->sanitize($elementTable);
4694 $sql .= " SET ".$this->db->sanitize($fieldstatus)." = ".((int) $status);
4695 // If status = 1 = validated, update also fk_user_valid
4696 // TODO Replace the test on $elementTable by doing a test on existence of the field in $this->fields
4697 if ($status == 1 && in_array($elementTable, array('expensereport', 'inventory'))) {
4698 $sql .= ", fk_user_valid = ".((int) $user->id);
4699 }
4700 if ($status == 1 && in_array($elementTable, array('expensereport'))) {
4701 $sql .= ", date_valid = '".$this->db->idate(dol_now())."'";
4702 }
4703 if ($status == 1 && in_array($elementTable, array('inventory'))) {
4704 $sql .= ", date_validation = '".$this->db->idate(dol_now())."'";
4705 }
4706 $sql .= " WHERE rowid = ".((int) $elementId);
4707 $sql .= " AND ".$fieldstatus." <> ".((int) $status); // We avoid update if status already correct
4708
4709 dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
4710 $resql = $this->db->query($sql);
4711 if ($resql) {
4712 $error = 0;
4713
4714 $nb_rows_affected = $this->db->affected_rows($resql); // should be 1 or 0 if status was already correct
4715
4716 if ($nb_rows_affected > 0) {
4717 if (empty($trigkey)) {
4718 // Try to guess trigkey (for backward compatibility, now we should have trigkey defined into the call of setStatus)
4719 if ($this->element == 'supplier_proposal' && $status == 2) {
4720 $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
4721 }
4722 if ($this->element == 'supplier_proposal' && $status == 3) {
4723 $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
4724 }
4725 if ($this->element == 'supplier_proposal' && $status == 4) {
4726 $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
4727 }
4728 if ($this->element == 'fichinter' && $status == 3) {
4729 $trigkey = 'FICHINTER_CLASSIFY_DONE';
4730 }
4731 if ($this->element == 'fichinter' && $status == 2) {
4732 $trigkey = 'FICHINTER_CLASSIFY_BILLED';
4733 }
4734 if ($this->element == 'fichinter' && $status == 1) {
4735 $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
4736 }
4737 }
4738
4739 $this->context = array_merge($this->context, array('newstatus' => $status));
4740
4741 if ($trigkey) {
4742 // Call trigger
4743 $result = $this->call_trigger($trigkey, $user);
4744 if ($result < 0) {
4745 $error++;
4746 }
4747 // End call triggers
4748 }
4749 } else {
4750 // The status was probably already good. We do nothing more, no triggers.
4751 }
4752
4753 if (!$error) {
4754 $this->db->commit();
4755
4756 if (empty($savElementId)) {
4757 // If the element we update is $this (so $elementId was provided as null)
4758 if ($fieldstatus == 'tosell') {
4759 $this->status = $status;
4760 } elseif ($fieldstatus == 'tobuy') {
4761 $this->status_buy = $status; // @phpstan-ignore-line
4762 } else {
4763 $this->status = $status;
4764 }
4765 }
4766
4767 return 1;
4768 } else {
4769 $this->db->rollback();
4770 dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR);
4771 return -1;
4772 }
4773 } else {
4774 $this->error = $this->db->lasterror();
4775 $this->db->rollback();
4776 return -1;
4777 }
4778 }
4779
4780
4788 public function getCanvas($id = 0, $ref = '')
4789 {
4790 global $conf;
4791
4792 if (empty($id) && empty($ref)) {
4793 return 0;
4794 }
4795 if (getDolGlobalString('MAIN_DISABLE_CANVAS')) {
4796 return 0; // To increase speed. Not enabled by default.
4797 }
4798
4799 // Clean parameters
4800 $ref = trim($ref);
4801
4802 $sql = "SELECT rowid, canvas";
4803 $sql .= " FROM ".$this->db->prefix().$this->table_element;
4804 $sql .= " WHERE entity IN (".getEntity($this->element).")";
4805 if (!empty($id)) {
4806 $sql .= " AND rowid = ".((int) $id);
4807 }
4808 if (!empty($ref)) {
4809 $sql .= " AND ref = '".$this->db->escape($ref)."'";
4810 }
4811
4812 $resql = $this->db->query($sql);
4813 if ($resql) {
4814 $obj = $this->db->fetch_object($resql);
4815 if ($obj) {
4816 $this->canvas = $obj->canvas;
4817 return 1;
4818 } else {
4819 return 0;
4820 }
4821 } else {
4822 dol_print_error($this->db);
4823 return -1;
4824 }
4825 }
4826
4827
4834 public function getSpecialCode($lineid)
4835 {
4836 $sql = "SELECT special_code FROM ".$this->db->prefix().$this->table_element_line;
4837 $sql .= " WHERE rowid = ".((int) $lineid);
4838 $resql = $this->db->query($sql);
4839 if ($resql) {
4840 $row = $this->db->fetch_row($resql);
4841 return (!empty($row[0]) ? $row[0] : 0);
4842 }
4843
4844 return 0;
4845 }
4846
4855 public function isObjectUsed($id = 0, $entity = 0)
4856 {
4857 global $langs;
4858
4859 if (empty($id)) {
4860 $id = $this->id;
4861 }
4862
4863 // Check parameters
4864 if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0) {
4865 dol_print_error(null, 'Called isObjectUsed on a class with property this->childtables not defined');
4866 return -1;
4867 }
4868
4869 $arraytoscan = $this->childtables; // array('tablename'=>array('fk_element'=>'parentfield'), ...) or array('tablename'=>array('parent'=>table_parent, 'parentkey'=>'nameoffieldforparentfkkey'), ...)
4870 // For backward compatibility, we check if array is old format array('tablename1', 'tablename2', ...)
4871 $tmparray = array_keys($this->childtables);
4872 if (is_numeric($tmparray[0])) {
4873 $arraytoscan = array_flip($this->childtables);
4874 }
4875
4876 // Test if child exists
4877 $haschild = 0;
4878 foreach ($arraytoscan as $table => $element) {
4879 //print $id.'-'.$table.'-'.$elementname.'<br>';
4880 // Check if element can be deleted
4881 $sql = "SELECT COUNT(*) as nb";
4882 $sql .= " FROM ".$this->db->prefix().$table." as c";
4883 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4884 $sql .= ", ".$this->db->prefix().$element['parent']." as p";
4885 }
4886 if (!empty($element['fk_element'])) {
4887 $sql .= " WHERE c.".$element['fk_element']." = ".((int) $id);
4888 } else {
4889 $sql .= " WHERE c.".$this->fk_element." = ".((int) $id);
4890 }
4891 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4892 $sql .= " AND c.".$element['parentkey']." = p.rowid";
4893 }
4894 if (!empty($element['parent']) && !empty($element['parenttypefield']) && !empty($element['parenttypevalue'])) {
4895 $sql .= " AND c.".$element['parenttypefield']." = '".$this->db->escape($element['parenttypevalue'])."'";
4896 }
4897 if (!empty($entity)) {
4898 if (!empty($element['parent']) && !empty($element['parentkey'])) {
4899 $sql .= " AND p.entity = ".((int) $entity);
4900 } else {
4901 $sql .= " AND c.entity = ".((int) $entity);
4902 }
4903 }
4904
4905 $resql = $this->db->query($sql);
4906 if ($resql) {
4907 $obj = $this->db->fetch_object($resql);
4908 if ($obj->nb > 0) {
4909 $langs->load("errors");
4910 //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
4911 $haschild += $obj->nb;
4912 if (is_numeric($element)) { // very old usage array('table1', 'table2', ...)
4913 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $table);
4914 } elseif (is_string($element)) { // old usage array('table1' => 'TranslateKey1', 'table2' => 'TranslateKey2', ...)
4915 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element));
4916 } else { // new usage: $element['name']=Translation key
4917 $this->errors[] = $langs->transnoentitiesnoconv("ErrorRecordHasAtLeastOneChildOfType", method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref, $langs->transnoentitiesnoconv($element['name']));
4918 }
4919 break; // We found at least one, we stop here
4920 }
4921 } else {
4922 $this->errors[] = $this->db->lasterror();
4923 return -1;
4924 }
4925 }
4926 if ($haschild > 0) {
4927 $this->errors[] = "ErrorRecordHasChildren";
4928 return $haschild;
4929 } else {
4930 return 0;
4931 }
4932 }
4933
4940 public function hasProductsOrServices($predefined = -1)
4941 {
4942 $nb = 0;
4943
4944 foreach ($this->lines as $key => $val) {
4945 $qualified = 0;
4946 if ($predefined == -1) {
4947 $qualified = 1;
4948 }
4949 if ($predefined == 1 && $val->fk_product > 0) {
4950 $qualified = 1;
4951 }
4952 if ($predefined == 0 && $val->fk_product <= 0) {
4953 $qualified = 1;
4954 }
4955 if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) {
4956 $qualified = 1;
4957 }
4958 if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) {
4959 $qualified = 1;
4960 }
4961 if ($qualified) {
4962 $nb++;
4963 }
4964 }
4965 dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
4966 return $nb;
4967 }
4968
4974 public function getTotalDiscount()
4975 {
4976 if (!empty($this->table_element_line)) {
4977 $total_discount = 0.00;
4978
4979 $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
4980 $sql .= " FROM ".$this->db->prefix().$this->table_element_line;
4981 $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
4982
4983 dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
4984 $resql = $this->db->query($sql);
4985 if ($resql) {
4986 $num = $this->db->num_rows($resql);
4987 $i = 0;
4988 while ($i < $num) {
4989 $obj = $this->db->fetch_object($resql);
4990
4991 $pu_ht = $obj->pu_ht;
4992 $qty = $obj->qty;
4993 $total_ht = $obj->total_ht;
4994
4995 $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT');
4996 $total_discount += $total_discount_line;
4997
4998 $i++;
4999 }
5000 }
5001
5002 //print $total_discount; exit;
5003 return (float) price2num($total_discount);
5004 }
5005
5006 return null;
5007 }
5008
5009
5016 public function getTotalWeightVolume()
5017 {
5018 $totalWeight = 0;
5019 $totalVolume = 0;
5020 // defined for shipment only
5021 $totalOrdered = 0;
5022 // defined for shipment only
5023 $totalToShip = 0;
5024
5025 if (empty($this->lines)) {
5026 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5027 }
5028
5029 foreach ($this->lines as $line) {
5030 if (isset($line->qty_asked)) {
5031 $totalOrdered += $line->qty_asked; // defined for shipment only
5032 }
5033 if (isset($line->qty_shipped)) {
5034 $totalToShip += $line->qty_shipped; // defined for shipment only
5035 } elseif ($line->element == 'commandefournisseurdispatch' && isset($line->qty)) {
5036 if (empty($totalToShip)) {
5037 $totalToShip = 0;
5038 }
5039 $totalToShip += $line->qty; // defined for reception only
5040 }
5041
5042 // Define qty, weight, volume, weight_units, volume_units
5043 if ($this->element == 'shipping') {
5044 // for shipments
5045 $qty = $line->qty_shipped ? $line->qty_shipped : 0;
5046 } else {
5047 $qty = $line->qty ? $line->qty : 0;
5048 }
5049
5050 $weight = !empty($line->weight) ? $line->weight : 0;
5051 ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
5052 $volume = !empty($line->volume) ? $line->volume : 0;
5053 ($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
5054
5055 $weight_units = !empty($line->weight_units) ? $line->weight_units : 0;
5056 ($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
5057 $volume_units = !empty($line->volume_units) ? $line->volume_units : 0;
5058 ($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
5059
5060 $weightUnit = 0;
5061 $volumeUnit = 0;
5062 if (!empty($weight_units)) {
5063 $weightUnit = $weight_units;
5064 }
5065 if (!empty($volume_units)) {
5066 $volumeUnit = $volume_units;
5067 }
5068
5069 if (empty($totalWeight)) {
5070 $totalWeight = 0; // Avoid warning because $totalWeight is ''
5071 }
5072 if (empty($totalVolume)) {
5073 $totalVolume = 0; // Avoid warning because $totalVolume is ''
5074 }
5075
5076 //var_dump($line->volume_units);
5077 if ($weight_units < 50) { // < 50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5078 $trueWeightUnit = pow(10, $weightUnit);
5079 $totalWeight += $weight * $qty * $trueWeightUnit;
5080 } else {
5081 if ($weight_units == 99) {
5082 // conversion 1 Pound = 0.45359237 KG
5083 $trueWeightUnit = 0.45359237;
5084 $totalWeight += $weight * $qty * $trueWeightUnit;
5085 } elseif ($weight_units == 98) {
5086 // conversion 1 Ounce = 0.0283495 KG
5087 $trueWeightUnit = 0.0283495;
5088 $totalWeight += $weight * $qty * $trueWeightUnit;
5089 } else {
5090 $totalWeight += $weight * $qty; // This may be wrong if we mix different units
5091 }
5092 }
5093 if ($volume_units < 50) { // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
5094 //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
5095 $trueVolumeUnit = pow(10, $volumeUnit);
5096 //print $line->volume;
5097 $totalVolume += $volume * $qty * $trueVolumeUnit;
5098 } else {
5099 $totalVolume += $volume * $qty; // This may be wrong if we mix different units
5100 }
5101 }
5102
5103 return array('weight' => $totalWeight, 'volume' => $totalVolume, 'ordered' => $totalOrdered, 'toship' => $totalToShip);
5104 }
5105
5106
5112 public function setExtraParameters()
5113 {
5114 $this->db->begin();
5115
5116 $extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
5117
5118 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
5119 $sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
5120 $sql .= " WHERE rowid = ".((int) $this->id);
5121
5122 dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
5123 $resql = $this->db->query($sql);
5124 if (!$resql) {
5125 $this->error = $this->db->lasterror();
5126 $this->db->rollback();
5127 return -1;
5128 } else {
5129 $this->db->commit();
5130 return 1;
5131 }
5132 }
5133
5134
5135 // --------------------
5136 // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
5137 // --------------------
5138
5139 /* This is to show add lines */
5140
5150 public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/core/tpl')
5151 {
5152 global $conf, $user, $langs, $object, $hookmanager, $extrafields, $form;
5153
5154 // Line extrafield
5155 if (!is_object($extrafields)) {
5156 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5157 $extrafields = new ExtraFields($this->db);
5158 }
5159 $extrafields->fetch_name_optionals_label($this->table_element_line);
5160
5161 // Output template part (modules that overwrite templates must declare this into descriptor)
5162 // Use global variables + $dateSelector + $seller and $buyer
5163 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
5164 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5165 foreach ($dirtpls as $module => $reldir) {
5166 if (!empty($module)) {
5167 $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
5168 } else {
5169 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_create.tpl.php';
5170 }
5171
5172 if (empty($conf->file->strict_mode)) {
5173 $res = @include $tpl;
5174 } else {
5175 $res = include $tpl; // for debug
5176 }
5177 if ($res) {
5178 break;
5179 }
5180 }
5181 }
5182
5183
5184
5185 /* This is to show array of line of details */
5186
5187
5202 public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl')
5203 {
5204 global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object;
5205 // TODO We should not use global var for this
5206 global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
5207
5208 // Define $usemargins (used by objectline_xxx.tpl.php files)
5209 $usemargins = 0;
5210 if (isModEnabled('margin') && !empty($this->element) && in_array($this->element, array('facture', 'facturerec', 'propal', 'commande'))) {
5211 $usemargins = 1;
5212 }
5213
5214 $num = count($this->lines);
5215
5216 // Line extrafield
5217 if (!is_object($extrafields)) {
5218 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5219 $extrafields = new ExtraFields($this->db);
5220 }
5221 $extrafields->fetch_name_optionals_label($this->table_element_line);
5222
5223 $parameters = array('num' => $num, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
5224 $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5225 if (empty($reshook)) {
5226 // Output template part (modules that overwrite templates must declare this into descriptor)
5227 // Use global variables + $dateSelector + $seller and $buyer
5228 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
5229 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5230 foreach ($dirtpls as $module => $reldir) {
5231 $res = 0;
5232 if (!empty($module)) {
5233 $tpl = dol_buildpath($reldir.'/objectline_title.tpl.php');
5234 } else {
5235 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_title.tpl.php';
5236 }
5237 if (file_exists($tpl)) {
5238 if (empty($conf->file->strict_mode)) {
5239 $res = @include $tpl;
5240 } else {
5241 $res = include $tpl; // for debug
5242 }
5243 }
5244 if ($res) {
5245 break;
5246 }
5247 }
5248 }
5249
5250 $i = 0;
5251
5252 print "<!-- begin printObjectLines() --><tbody>\n";
5253 foreach ($this->lines as $line) {
5254 //Line extrafield
5255 $line->fetch_optionals();
5256
5257 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
5258 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5259 if (empty($line->fk_parent_line)) {
5260 $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'dateSelector' => $dateSelector, 'seller' => $seller, 'buyer' => $buyer, 'selected' => $selected, 'table_element_line' => $line->table_element, 'defaulttpldir' => $defaulttpldir);
5261 $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5262 } else {
5263 $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);
5264 $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5265 }
5266 }
5267 if (empty($reshook)) {
5268 $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafields, $defaulttpldir);
5269 }
5270
5271 $i++;
5272 }
5273 print "</tbody><!-- end printObjectLines() -->\n";
5274 }
5275
5293 public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl')
5294 {
5295 global $conf, $langs, $user, $object, $hookmanager;
5296 global $form;
5297 global $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
5298
5299 // var used into tpl
5300 $text = '';
5301 $description = '';
5302
5303 // Line in view mode
5304 if ($action != 'editline' || $selected != $line->id) {
5305 // Product
5306 if (!empty($line->fk_product) && $line->fk_product > 0) {
5307 $product_static = new Product($this->db);
5308 $product_static->fetch($line->fk_product);
5309
5310 $product_static->ref = $line->ref; //can change ref in hook
5311 $product_static->label = !empty($line->label) ? $line->label : ""; //can change label in hook
5312
5313 $text = $product_static->getNomUrl(1);
5314
5315 // Define output language and label
5316 if (getDolGlobalInt('MAIN_MULTILANGS')) {
5317 if (property_exists($this, 'socid') && !is_object($this->thirdparty)) {
5318 dol_print_error(null, 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
5319 return;
5320 }
5321
5322 $prod = new Product($this->db);
5323 $prod->fetch($line->fk_product);
5324
5325 $outputlangs = $langs;
5326 $newlang = '';
5327 if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
5328 $newlang = GETPOST('lang_id', 'aZ09');
5329 }
5330 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && empty($newlang) && is_object($this->thirdparty)) {
5331 $newlang = $this->thirdparty->default_lang; // To use language of customer
5332 }
5333 if (!empty($newlang)) {
5334 $outputlangs = new Translate("", $conf);
5335 $outputlangs->setDefaultLang($newlang);
5336 }
5337
5338 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
5339 } else {
5340 $label = $line->product_label;
5341 }
5342
5343 $text .= ' - '.(!empty($line->label) ? $line->label : $label);
5344 $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.
5345 }
5346
5347 $line->pu_ttc = price2num((!empty($line->subprice) ? $line->subprice : 0) * (1 + ((!empty($line->tva_tx) ? $line->tva_tx : 0) / 100)), 'MU');
5348
5349 // Output template part (modules that overwrite templates must declare this into descriptor)
5350 // Use global variables + $dateSelector + $seller and $buyer
5351 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5352 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5353 foreach ($dirtpls as $module => $reldir) {
5354 $res = 0;
5355 if (!empty($module)) {
5356 $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
5357 } else {
5358 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_view.tpl.php';
5359 }
5360 //var_dump($tpl);
5361 if (file_exists($tpl)) {
5362 if (empty($conf->file->strict_mode)) {
5363 $res = @include $tpl;
5364 } else {
5365 $res = include $tpl; // for debug
5366 }
5367 }
5368 if ($res) {
5369 break;
5370 }
5371 }
5372 }
5373
5374 // Line in update mode
5375 if ($this->status == 0 && $action == 'editline' && $selected == $line->id) {
5376 $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
5377
5378 $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
5379
5380 // Output template part (modules that overwrite templates must declare this into descriptor)
5381 // Use global variables + $dateSelector + $seller and $buyer
5382 // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
5383 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5384 foreach ($dirtpls as $module => $reldir) {
5385 if (!empty($module)) {
5386 $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
5387 } else {
5388 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/objectline_edit.tpl.php';
5389 }
5390
5391 if (empty($conf->file->strict_mode)) {
5392 $res = @include $tpl;
5393 } else {
5394 $res = include $tpl; // for debug
5395 }
5396 if ($res) {
5397 break;
5398 }
5399 }
5400 }
5401 }
5402
5403
5404 /* This is to show array of line of details of source object */
5405
5406
5417 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
5418 {
5419 global $langs, $hookmanager, $form, $action;
5420
5421 print '<tr class="liste_titre">';
5422 print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
5423 print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
5424 print '<td class="linecolvat right">'.$langs->trans('VATRate').'</td>';
5425 print '<td class="linecoluht right">'.$langs->trans('PriceUHT').'</td>';
5426 if (isModEnabled("multicurrency")) {
5427 print '<td class="linecoluht_currency right">'.$langs->trans('PriceUHTCurrency').'</td>';
5428 }
5429 print '<td class="linecolqty right">'.$langs->trans('Qty').'</td>';
5430 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5431 print '<td class="linecoluseunit left">'.$langs->trans('Unit').'</td>';
5432 }
5433 print '<td class="linecoldiscount right">'.$langs->trans('ReductionShort').'</td>';
5434 print '<td class="linecolht right">'.$langs->trans('TotalHT').'</td>';
5435 print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
5436 print '</tr>';
5437 $i = 0;
5438
5439 if (!empty($this->lines)) {
5440 foreach ($this->lines as $line) {
5441 $reshook = 0;
5442 //if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line))) {
5443 if (is_object($hookmanager)) { // Old code is commented on preceding line.
5444 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
5445 if (!empty($line->fk_parent_line)) {
5446 $parameters['fk_parent_line'] = $line->fk_parent_line;
5447 }
5448 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5449 }
5450 if (empty($reshook)) {
5451 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
5452 }
5453
5454 $i++;
5455 }
5456 }
5457 }
5458
5472 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
5473 {
5474 global $langs, $conf;
5475
5476 //var_dump($line);
5477 if (!empty($line->date_start)) {
5478 // @phan-suppress-next-line PhanUndeclaredProperty
5479 $date_start = $line->date_start;
5480 } else {
5481 $date_start = $line->date_debut_prevue;
5482 if ($line->date_debut_reel) {
5483 $date_start = $line->date_debut_reel;
5484 }
5485 }
5486 if (!empty($line->date_end)) {
5487 // @phan-suppress-next-line PhanUndeclaredProperty
5488 $date_end = $line->date_end;
5489 } else {
5490 $date_end = $line->date_fin_prevue;
5491 if ($line->date_fin_reel) {
5492 $date_end = $line->date_fin_reel;
5493 }
5494 }
5495
5496 $this->tpl['id'] = $line->id;
5497
5498 $this->tpl['label'] = '';
5499 if (!empty($line->fk_parent_line)) {
5500 $this->tpl['label'] .= img_picto('', 'rightarrow');
5501 }
5502
5503 if (($line->info_bits & 2) == 2) { // TODO Not sure this is used for source object
5504 $discount = new DiscountAbsolute($this->db);
5505 if (property_exists($this, 'socid')) {
5506 $discount->fk_soc = $this->socid;
5507 $discount->socid = $this->socid;
5508 }
5509 $this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
5510 } elseif (!empty($line->fk_product)) {
5511 $productstatic = new Product($this->db);
5512 $productstatic->id = $line->fk_product;
5513 $productstatic->ref = $line->ref;
5514 $productstatic->type = $line->fk_product_type;
5515 if (empty($productstatic->ref)) {
5516 $line->fetch_product();
5517 $productstatic = $line->product;
5518 }
5519
5520 $this->tpl['label'] .= $productstatic->getNomUrl(1);
5521 $this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
5522 // Dates
5523 if ($line->product_type == 1 && ($date_start || $date_end)) {
5524 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5525 }
5526 } else {
5527 $this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
5528 if (!empty($line->desc)) {
5529 $this->tpl['label'] .= $line->desc;
5530 } else {
5531 $this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
5532 }
5533
5534 // Dates
5535 if ($line->product_type == 1 && ($date_start || $date_end)) {
5536 $this->tpl['label'] .= get_date_range($date_start, $date_end);
5537 }
5538 }
5539
5540 if (!empty($line->desc)) {
5541 '@phan-var-force OrderLine|FactureLigne|ContratLigne|FactureFournisseurLigneRec|SupplierInvoiceLine|SupplierProposalLine $line';
5542 if ($line->desc == '(CREDIT_NOTE)') { // TODO Not sure this is used for source object
5543 $discount = new DiscountAbsolute($this->db);
5544 $discount->fetch($line->fk_remise_except);
5545 $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
5546 } elseif ($line->desc == '(DEPOSIT)') { // TODO Not sure this is used for source object
5547 $discount = new DiscountAbsolute($this->db);
5548 $discount->fetch($line->fk_remise_except);
5549 $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
5550 } elseif ($line->desc == '(EXCESS RECEIVED)') {
5551 $discount = new DiscountAbsolute($this->db);
5552 $discount->fetch($line->fk_remise_except);
5553 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
5554 } elseif ($line->desc == '(EXCESS PAID)') {
5555 $discount = new DiscountAbsolute($this->db);
5556 $discount->fetch($line->fk_remise_except);
5557 $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
5558 } else {
5559 $this->tpl['description'] = dol_trunc($line->desc, 60);
5560 }
5561 } else {
5562 $this->tpl['description'] = '&nbsp;';
5563 }
5564
5565 // VAT Rate
5566 $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
5567 $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
5568 if (!empty($line->vat_src_code) && !preg_match('/\‍(/', $this->tpl['vat_rate'])) {
5569 $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
5570 }
5571
5572 $this->tpl['price'] = price($line->subprice);
5573 $this->tpl['total_ht'] = price($line->total_ht);
5574 $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
5575 $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
5576 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5577 $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
5578 }
5579 $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
5580
5581 // Is the line strike or not
5582 $this->tpl['strike'] = 0;
5583 if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
5584 $this->tpl['strike'] = 1;
5585 }
5586
5587 // Output template part (modules that overwrite templates must declare this into descriptor)
5588 // Use global variables + $dateSelector + $seller and $buyer
5589 $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
5590 foreach ($dirtpls as $module => $reldir) {
5591 if (!empty($module)) {
5592 $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
5593 } else {
5594 $tpl = DOL_DOCUMENT_ROOT.$reldir.'/originproductline.tpl.php';
5595 }
5596
5597 if (empty($conf->file->strict_mode)) {
5598 $res = @include $tpl;
5599 } else {
5600 $res = include $tpl; // for debug
5601 }
5602 if ($res) {
5603 break;
5604 }
5605 }
5606 }
5607
5608
5609 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5620 public function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
5621 {
5622 // phpcs:enable
5623 $this->db->begin();
5624
5625 $sql = "INSERT INTO ".$this->db->prefix()."element_resources (";
5626 $sql .= "resource_id";
5627 $sql .= ", resource_type";
5628 $sql .= ", element_id";
5629 $sql .= ", element_type";
5630 $sql .= ", busy";
5631 $sql .= ", mandatory";
5632 $sql .= ") VALUES (";
5633 $sql .= ((int) $resource_id);
5634 $sql .= ", '".$this->db->escape($resource_type)."'";
5635 $sql .= ", '".$this->db->escape($this->id)."'";
5636 $sql .= ", '".$this->db->escape($this->element)."'";
5637 $sql .= ", '".$this->db->escape($busy)."'";
5638 $sql .= ", '".$this->db->escape($mandatory)."'";
5639 $sql .= ")";
5640
5641 dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
5642 if ($this->db->query($sql)) {
5643 $this->db->commit();
5644 return 1;
5645 } else {
5646 $this->error = $this->db->lasterror();
5647 $this->db->rollback();
5648 return 0;
5649 }
5650 }
5651
5652 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5661 public function delete_resource($rowid, $element, $notrigger = 0)
5662 {
5663 // phpcs:enable
5664 global $user;
5665
5666 $this->db->begin();
5667
5668 $sql = "DELETE FROM ".$this->db->prefix()."element_resources";
5669 $sql .= " WHERE rowid = ".((int) $rowid);
5670
5671 dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
5672
5673 $resql = $this->db->query($sql);
5674 if (!$resql) {
5675 $this->error = $this->db->lasterror();
5676 $this->db->rollback();
5677 return -1;
5678 } else {
5679 if (!$notrigger) {
5680 $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
5681 if ($result < 0) {
5682 $this->db->rollback();
5683 return -1;
5684 }
5685 }
5686 $this->db->commit();
5687 return 1;
5688 }
5689 }
5690
5691
5697 public function __clone()
5698 {
5699 // Force a copy of this->lines, otherwise it will point to same object.
5700 if (isset($this->lines) && is_array($this->lines)) {
5701 $nboflines = count($this->lines);
5702 for ($i = 0; $i < $nboflines; $i++) {
5703 if (is_object($this->lines[$i])) {
5704 $this->lines[$i] = clone $this->lines[$i];
5705 }
5706 }
5707 }
5708 }
5709
5723 protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
5724 {
5725 global $conf, $langs, $user, $hookmanager, $action;
5726
5727 $srctemplatepath = '';
5728
5729 $parameters = array('modelspath' => $modelspath, 'modele' => $modele, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'hidedesc' => $hidedesc, 'hideref' => $hideref, 'moreparams' => $moreparams);
5730 $reshook = $hookmanager->executeHooks('commonGenerateDocument', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
5731
5732 if (!empty($reshook)) {
5733 return $reshook;
5734 }
5735
5736 dol_syslog("commonGenerateDocument modele=".$modele." outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null'));
5737
5738 if (empty($modele)) {
5739 $this->error = 'BadValueForParameterModele';
5740 return -1;
5741 }
5742
5743 // Increase limit for PDF build
5744 $err = error_reporting();
5745 error_reporting(0);
5746 @set_time_limit(120);
5747 error_reporting($err);
5748
5749 // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
5750 $tmp = explode(':', $modele, 2);
5751 $saved_model = $modele;
5752 if (!empty($tmp[1])) {
5753 $modele = $tmp[0];
5754 $srctemplatepath = $tmp[1];
5755 }
5756
5757 // Search template files
5758 $file = '';
5759 $classname = '';
5760 $filefound = '';
5761 $dirmodels = array('/');
5762 if (is_array($conf->modules_parts['models'])) {
5763 $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
5764 }
5765 foreach ($dirmodels as $reldir) {
5766 foreach (array('doc', 'pdf') as $prefix) {
5767 if (in_array(get_class($this), array('Adherent'))) {
5768 // Member module use prefix_modele.class.php
5769 $file = $prefix."_".$modele.".class.php";
5770 } else {
5771 // Other module use prefix_modele.modules.php
5772 $file = $prefix."_".$modele.".modules.php";
5773 }
5774
5775 $file = dol_sanitizeFileName($file);
5776
5777 // We check if the file exists
5778 $file = dol_buildpath($reldir.$modelspath.$file, 0);
5779 if (file_exists($file)) {
5780 $filefound = $file;
5781 $classname = $prefix.'_'.$modele;
5782 break;
5783 }
5784 }
5785 if ($filefound) {
5786 break;
5787 }
5788 }
5789
5790 if ($filefound === '' || $classname === '') {
5791 $this->error = $langs->trans("Error").' Failed to load doc generator with modelpaths='.$modelspath.' - modele='.$modele;
5792 $this->errors[] = $this->error;
5793 dol_syslog($this->error, LOG_ERR);
5794 return -1;
5795 }
5796
5797 // Sanitize $filefound
5798 $filefound = dol_sanitizePathName($filefound);
5799
5800 // If generator was found
5801 global $db; // Required to solve a conception error making an include of some code that uses $db instead of $this->db just after.
5802
5803 require_once $filefound;
5804
5805 $obj = new $classname($this->db);
5806
5807 // TODO: Check the following classes that seem possible for $obj, but removed for compatibility:
5808 // ModeleBankAccountDoc|ModeleExpenseReport|ModelePDFBom|ModelePDFCommandes|ModelePDFContract|
5809 // ModelePDFDeliveryOrder|ModelePDFEvaluation|ModelePDFFactures|ModelePDFFicheinter|
5810 // ModelePDFMo|ModelePDFMovement|ModelePDFProduct|ModelePDFProjects|ModelePDFPropales|
5811 // ModelePDFRecruitmentJobPosition|ModelePDFSupplierProposal|ModelePDFSuppliersInvoices|
5812 // ModelePDFSuppliersOrders|ModelePDFSuppliersPayments|ModelePdfExpedition|ModelePdfReception|
5813 // ModelePDFStock|ModelePDFStockTransfer|
5814 // ModeleDon|ModelePDFTask|
5815 // ModelePDFAsset|ModelePDFTicket|ModelePDFUserGroup|ModeleThirdPartyDoc|ModelePDFUser
5816 // Has no write_file: ModeleBarCode|ModeleImports|ModeleExports|
5817 '@phan-var-force ModelePDFMember $obj';
5818 // '@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';
5819
5820 // If generator is ODT, we must have srctemplatepath defined, if not we set it.
5821 if ($obj->type == 'odt' && empty($srctemplatepath)) {
5822 $varfortemplatedir = $obj->scandir;
5823 if ($varfortemplatedir && getDolGlobalString($varfortemplatedir)) {
5824 $dirtoscan = getDolGlobalString($varfortemplatedir);
5825
5826 $listoffiles = array();
5827
5828 // Now we add first model found in directories scanned
5829 $listofdir = explode(',', $dirtoscan);
5830 foreach ($listofdir as $key => $tmpdir) {
5831 $tmpdir = trim($tmpdir);
5832 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
5833 if (!$tmpdir) {
5834 unset($listofdir[$key]);
5835 continue;
5836 }
5837 if (is_dir($tmpdir)) {
5838 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
5839 if (count($tmpfiles)) {
5840 $listoffiles = array_merge($listoffiles, $tmpfiles);
5841 }
5842 }
5843 }
5844
5845 if (count($listoffiles)) {
5846 foreach ($listoffiles as $record) {
5847 $srctemplatepath = $record['fullname'];
5848 break;
5849 }
5850 }
5851 }
5852
5853 if (empty($srctemplatepath)) {
5854 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
5855 return -1;
5856 }
5857 }
5858
5859 if ($obj->type == 'odt' && !empty($srctemplatepath)) {
5860 if (!dol_is_file($srctemplatepath)) {
5861 dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING);
5862 $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
5863 return -1;
5864 }
5865 }
5866
5867 // We save charset_output to restore it because write_file can change it if needed for
5868 // output format that does not support UTF8.
5869 $sav_charset_output = empty($outputlangs->charset_output) ? '' : $outputlangs->charset_output;
5870
5871 // update model_pdf in object
5872 $this->model_pdf = $saved_model;
5873
5874 if ($obj instanceof ModelePDFMember) {
5875 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, 'tmp_cards');
5876 } else {
5877 // TODO: Try to set type above again
5878 '@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';
5879 $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
5880 }
5881 // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
5882
5883 if ($resultwritefile > 0) {
5884 $outputlangs->charset_output = $sav_charset_output;
5885
5886 // We delete old preview
5887 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
5888 dol_delete_preview($this);
5889
5890 // Index file in database
5891 if (!empty($obj->result['fullpath'])) {
5892 $destfull = $obj->result['fullpath'];
5893
5894 // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set)
5895 $update_main_doc_field = 0;
5896 if (!empty($obj->update_main_doc_field)) {
5897 $update_main_doc_field = 1;
5898 }
5899
5900 // Check that the file exists, before indexing it.
5901 // Hint: It does not exist, if we create a PDF and auto delete the ODT File
5902 if (dol_is_file($destfull)) {
5903 $this->indexFile($destfull, $update_main_doc_field);
5904 }
5905 } else {
5906 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);
5907 }
5908
5909 // Success in building document. We build meta file.
5910 dol_meta_create($this);
5911
5912 return 1;
5913 } else {
5914 $outputlangs->charset_output = $sav_charset_output;
5915 $this->error = $obj->error;
5916 $this->errors = $obj->errors;
5917 dol_syslog("Error generating document for ".__CLASS__.". Error: ".$obj->error, LOG_ERR);
5918 return -1;
5919 }
5920 }
5921
5931 public function indexFile($destfull, $update_main_doc_field)
5932 {
5933 global $conf, $user;
5934
5935 $upload_dir = dirname($destfull);
5936 $destfile = basename($destfull);
5937 $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
5938
5939 if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) { // If not a tmp dir
5940 $filename = basename($destfile);
5941 $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
5942 $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
5943
5944 include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
5945 $ecmfile = new EcmFiles($this->db);
5946 $result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
5947
5948 // Set the public "share" key
5949 $setsharekey = false;
5950 if ($this->element == 'propal' || $this->element == 'proposal') {
5951 if (getDolGlobalInt("PROPOSAL_ALLOW_ONLINESIGN")) {
5952 $setsharekey = true; // feature to make online signature is not set or set to on (default)
5953 }
5954 if (getDolGlobalInt("PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
5955 $setsharekey = true;
5956 }
5957 }
5958 if ($this->element == 'commande' && getDolGlobalInt("ORDER_ALLOW_EXTERNAL_DOWNLOAD")) {
5959 $setsharekey = true;
5960 }
5961 if ($this->element == 'facture' && getDolGlobalInt("INVOICE_ALLOW_EXTERNAL_DOWNLOAD")) {
5962 $setsharekey = true;
5963 }
5964 if ($this->element == 'bank_account' && getDolGlobalInt("BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD")) {
5965 $setsharekey = true;
5966 }
5967 if ($this->element == 'product' && getDolGlobalInt("PRODUCT_ALLOW_EXTERNAL_DOWNLOAD")) {
5968 $setsharekey = true;
5969 }
5970 if ($this->element == 'contrat' && getDolGlobalInt("CONTRACT_ALLOW_EXTERNAL_DOWNLOAD")) {
5971 $setsharekey = true;
5972 }
5973 if ($this->element == 'fichinter' && getDolGlobalInt("FICHINTER_ALLOW_EXTERNAL_DOWNLOAD")) {
5974 $setsharekey = true;
5975 }
5976 if ($this->element == 'supplier_proposal' && getDolGlobalInt("SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD")) {
5977 $setsharekey = true;
5978 }
5979 if ($this->element == 'societe_rib' && getDolGlobalInt("SOCIETE_RIB_ALLOW_ONLINESIGN")) {
5980 $setsharekey = true;
5981 }
5982
5983 if ($setsharekey) {
5984 if (empty($ecmfile->share)) { // Because object not found or share not set yet
5985 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5986 $ecmfile->share = getRandomPassword(true);
5987 }
5988 }
5989
5990 if ($result > 0) {
5991 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
5992 $ecmfile->fullpath_orig = '';
5993 $ecmfile->gen_or_uploaded = 'generated';
5994 $ecmfile->description = ''; // indexed content
5995 $ecmfile->keywords = ''; // keyword content
5996 $ecmfile->src_object_type = $this->table_element;
5997 $ecmfile->src_object_id = $this->id;
5998 $result = $ecmfile->update($user);
5999 if ($result < 0) {
6000 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
6001 return -1;
6002 }
6003 } else {
6004 $ecmfile->entity = $conf->entity;
6005 $ecmfile->filepath = $rel_dir;
6006 $ecmfile->filename = $filename;
6007 $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
6008 $ecmfile->fullpath_orig = '';
6009 $ecmfile->gen_or_uploaded = 'generated';
6010 $ecmfile->description = ''; // indexed content
6011 $ecmfile->keywords = ''; // keyword content
6012 $ecmfile->src_object_type = $this->table_element; // $this->table_name is 'myobject' or 'mymodule_myobject'.
6013 $ecmfile->src_object_id = $this->id;
6014
6015 $result = $ecmfile->create($user);
6016 if ($result < 0) {
6017 setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
6018 return -1;
6019 }
6020 }
6021
6022 /*$this->result['fullname']=$destfull;
6023 $this->result['filepath']=$ecmfile->filepath;
6024 $this->result['filename']=$ecmfile->filename;*/
6025 //var_dump($obj->update_main_doc_field);exit;
6026
6027 if ($update_main_doc_field && !empty($this->table_element)) {
6028 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath."/".$ecmfile->filename)."'";
6029 $sql .= " WHERE rowid = ".((int) $this->id);
6030
6031 $resql = $this->db->query($sql);
6032 if (!$resql) {
6033 dol_print_error($this->db);
6034 return -1;
6035 } else {
6036 $this->last_main_doc = $ecmfile->filepath.'/'.$ecmfile->filename;
6037 }
6038 }
6039 }
6040
6041 return 1;
6042 }
6043
6051 public function addThumbs($file)
6052 {
6053 $file_osencoded = dol_osencode($file);
6054
6055 if (file_exists($file_osencoded)) {
6056 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6057
6058 $tmparraysize = getDefaultImageSizes();
6059 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
6060 $maxheightsmall = $tmparraysize['maxheightsmall'];
6061 $maxwidthmini = $tmparraysize['maxwidthmini'];
6062 $maxheightmini = $tmparraysize['maxheightmini'];
6063 //$quality = $tmparraysize['quality'];
6064 $quality = 50; // For thumbs, we force quality to 50
6065
6066 // Create small thumbs for company (Ratio is near 16/9)
6067 // Used on logon for example
6068 vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
6069
6070 // Create mini thumbs for company (Ratio is near 16/9)
6071 // Used on menu or for setup page for example
6072 vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
6073 }
6074 }
6075
6083 public function delThumbs($file)
6084 {
6085 $imgThumbName = getImageFileNameForSize($file, '_small'); // Full path of thumb file
6086 dol_delete_file($imgThumbName);
6087 $imgThumbName = getImageFileNameForSize($file, '_mini'); // Full path of thumb file
6088 dol_delete_file($imgThumbName);
6089 }
6090
6091
6092 /* Functions common to commonobject and commonobjectline */
6093
6094 /* For default values */
6095
6109 public function getDefaultCreateValueFor($fieldname, $alternatevalue = null, $type = 'alphanohtml')
6110 {
6111 // If param here has been posted, we use this value first.
6112 if (GETPOSTISSET($fieldname)) {
6113 return GETPOST($fieldname, $type, 3);
6114 }
6115
6116 if (isset($alternatevalue)) {
6117 return $alternatevalue;
6118 }
6119
6120 $newelement = $this->element;
6121 if ($newelement == 'facture') {
6122 $newelement = 'invoice';
6123 }
6124 if ($newelement == 'commande') {
6125 $newelement = 'order';
6126 }
6127 if (empty($newelement)) {
6128 dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
6129 return '';
6130 }
6131
6132 $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
6133 //var_dump($keyforfieldname);
6134 if (getDolGlobalString($keyforfieldname)) {
6135 return getDolGlobalString($keyforfieldname);
6136 }
6137
6138 // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
6139 // store content into $conf->cache['overwrite_default']
6140
6141 return '';
6142 }
6143
6144
6145 /* For triggers */
6146
6147
6148 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6159 public function call_trigger($triggerName, $user)
6160 {
6161 // phpcs:enable
6162 global $langs, $conf;
6163
6164 if (!empty(self::TRIGGER_PREFIX) && strpos($triggerName, self::TRIGGER_PREFIX . '_') !== 0) {
6165 dol_print_error(null, 'The trigger "' . $triggerName . '" does not start with "' . self::TRIGGER_PREFIX . '_" as required.');
6166 exit;
6167 }
6168 if (!is_object($langs)) { // If lang was not defined, we set it. It is required by run_triggers().
6169 include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
6170 $langs = new Translate('', $conf);
6171 }
6172
6173 include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
6174 $interface = new Interfaces($this->db);
6175 $result = $interface->run_triggers($triggerName, $this, $user, $langs, $conf);
6176
6177 if ($result < 0) {
6178 if (!empty($this->errors)) {
6179 $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.
6180 } else {
6181 $this->errors = $interface->errors;
6182 }
6183 }
6184 return $result;
6185 }
6186
6187
6188 /* Functions for data in other language */
6189
6190
6199 {
6200 // To avoid SQL errors. Probably not the better solution though
6201 if (!$this->element) {
6202 return 0;
6203 }
6204 if (!($this->id > 0)) {
6205 return 0;
6206 }
6207 if (is_array($this->array_languages)) {
6208 return 1;
6209 }
6210
6211 $this->array_languages = array();
6212
6213 $element = $this->element;
6214 if ($element == 'categorie') {
6215 $element = 'categories'; // For compatibility
6216 }
6217
6218 // Request to get translation values for object
6219 $sql = "SELECT rowid, property, lang , value";
6220 $sql .= " FROM ".$this->db->prefix()."object_lang";
6221 $sql .= " WHERE type_object = '".$this->db->escape($element)."'";
6222 $sql .= " AND fk_object = ".((int) $this->id);
6223
6224 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6225 $resql = $this->db->query($sql);
6226 if ($resql) {
6227 $numrows = $this->db->num_rows($resql);
6228 if ($numrows) {
6229 $i = 0;
6230 while ($i < $numrows) {
6231 $obj = $this->db->fetch_object($resql);
6232 $key = $obj->property;
6233 $value = $obj->value;
6234 $codelang = $obj->lang;
6235 $type = $this->fields[$key]['type'];
6236
6237 // we can add this attribute to object
6238 if (preg_match('/date/', $type)) {
6239 $this->array_languages[$key][$codelang] = $this->db->jdate($value);
6240 } else {
6241 $this->array_languages[$key][$codelang] = $value;
6242 }
6243
6244 $i++;
6245 }
6246 }
6247
6248 $this->db->free($resql);
6249
6250 if ($numrows) {
6251 return $numrows;
6252 } else {
6253 return 0;
6254 }
6255 } else {
6256 dol_print_error($this->db);
6257 return -1;
6258 }
6259 }
6260
6267 public function setValuesForExtraLanguages($onlykey = '')
6268 {
6269 // Get extra fields
6270 foreach ($_POST as $postfieldkey => $postfieldvalue) {
6271 $tmparray = explode('-', $postfieldkey);
6272 if ($tmparray[0] != 'field') {
6273 continue;
6274 }
6275
6276 $element = $tmparray[1];
6277 $key = $tmparray[2];
6278 $codelang = $tmparray[3];
6279 //var_dump("postfieldkey=".$postfieldkey." element=".$element." key=".$key." codelang=".$codelang);
6280
6281 if (!empty($onlykey) && $key != $onlykey) {
6282 continue;
6283 }
6284 if ($element != $this->element) {
6285 continue;
6286 }
6287
6288 $key_type = $this->fields[$key]['type'];
6289
6290 $enabled = 1;
6291 if (isset($this->fields[$key]['enabled'])) {
6292 $enabled = (int) dol_eval($this->fields[$key]['enabled'], 1, 1, '1');
6293 }
6294 /*$perms = 1;
6295 if (isset($this->fields[$key]['perms']))
6296 {
6297 $perms = (int) dol_eval($this->fields[$key]['perms'], 1, 1, '1');
6298 }*/
6299 if (empty($enabled)) {
6300 continue;
6301 }
6302 //if (empty($perms)) continue;
6303
6304 if (in_array($key_type, array('date'))) {
6305 // Clean parameters
6306 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6307 $value_key = dol_mktime(0, 0, 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6308 } elseif (in_array($key_type, array('datetime'))) {
6309 // Clean parameters
6310 // TODO GMT date in memory must be GMT so we should add gm=true in parameters
6311 $value_key = dol_mktime(GETPOSTINT($postfieldkey."hour"), GETPOSTINT($postfieldkey."min"), 0, GETPOSTINT($postfieldkey."month"), GETPOSTINT($postfieldkey."day"), GETPOSTINT($postfieldkey."year"));
6312 } elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
6313 $value_arr = GETPOST($postfieldkey, 'array'); // check if an array
6314 if (!empty($value_arr)) {
6315 $value_key = implode(',', $value_arr);
6316 } else {
6317 $value_key = '';
6318 }
6319 } elseif (in_array($key_type, array('price', 'double'))) {
6320 $value_arr = GETPOST($postfieldkey, 'alpha');
6321 $value_key = price2num($value_arr);
6322 } else {
6323 $value_key = GETPOST($postfieldkey);
6324 if (in_array($key_type, array('link')) && $value_key == '-1') {
6325 $value_key = '';
6326 }
6327 }
6328
6329 $this->array_languages[$key][$codelang] = $value_key;
6330
6331 /*if ($nofillrequired) {
6332 $langs->load('errors');
6333 setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
6334 return -1;
6335 }*/
6336 }
6337
6338 return 1;
6339 }
6340
6341
6342 /* Functions for extrafields */
6343
6350 public function fetchNoCompute($id)
6351 {
6352 global $conf;
6353
6354 $savDisableCompute = $conf->disable_compute;
6355 $conf->disable_compute = 1;
6356
6357 $ret = $this->fetch($id); /* @phpstan-ignore-line */
6358
6359 $conf->disable_compute = $savDisableCompute;
6360
6361 return $ret;
6362 }
6363
6364 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6374 public function fetch_optionals($rowid = null, $optionsArray = null)
6375 {
6376 // phpcs:enable
6377 global $conf, $extrafields;
6378
6379 if (empty($rowid)) {
6380 $rowid = $this->id;
6381 }
6382 if (empty($rowid) && isset($this->rowid)) { // @phan-suppress-current-line PhanUndeclaredProperty
6383 $rowid = $this->rowid; // deprecated @phan-suppress-current-line PhanUndeclaredProperty
6384 }
6385
6386 // To avoid SQL errors. Probably not the better solution though
6387 if (!$this->table_element) {
6388 return 0;
6389 }
6390
6391 $this->array_options = array();
6392
6393 if (!is_array($optionsArray)) {
6394 // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
6395 if (!isset($extrafields) || !is_object($extrafields)) {
6396 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6397 $extrafields = new ExtraFields($this->db);
6398 }
6399
6400 // Load array of extrafields for elementype = $this->table_element
6401 if (empty($extrafields->attributes[$this->table_element]['loaded'])) {
6402 $extrafields->fetch_name_optionals_label($this->table_element);
6403 }
6404 $optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
6405 } else {
6406 global $extrafields;
6407 dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
6408 }
6409
6410 $table_element = $this->table_element;
6411 if ($table_element == 'categorie') {
6412 $table_element = 'categories'; // For compatibility
6413 }
6414
6415 // Request to get complementary values
6416 if (is_array($optionsArray) && count($optionsArray) > 0) {
6417 $sql = "SELECT rowid";
6418 foreach ($optionsArray as $name => $label) {
6419 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || (!in_array($extrafields->attributes[$this->table_element]['type'][$name], ['separate', 'point', 'multipts', 'linestrg','polygon']))) {
6420 $sql .= ", ".$name;
6421 }
6422 // use geo sql fonction to read as text
6423 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'point') {
6424 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6425 }
6426 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'multipts') {
6427 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6428 }
6429 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'linestrg') {
6430 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6431 }
6432 if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] == 'polygon') {
6433 $sql .= ", ST_AsWKT(".$name.") as ".$name;
6434 }
6435 }
6436 $sql .= " FROM ".$this->db->prefix().$table_element."_extrafields";
6437 $sql .= " WHERE fk_object = ".((int) $rowid);
6438
6439 //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose
6440 $resql = $this->db->query($sql);
6441 if ($resql) {
6442 $numrows = $this->db->num_rows($resql);
6443 if ($numrows) {
6444 $tab = $this->db->fetch_array($resql);
6445
6446 foreach ($tab as $key => $value) {
6447 // 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)
6448 if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key)) {
6449 // we can add this attribute to object
6450 if (!empty($extrafields->attributes[$this->table_element]) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) {
6451 //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
6452 $this->array_options["options_".$key] = $this->db->jdate($value);
6453 } else {
6454 $this->array_options["options_".$key] = $value;
6455 }
6456
6457 //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
6458 }
6459 if (!empty($extrafields->attributes[$this->table_element]['type'][$key]) && $extrafields->attributes[$this->table_element]['type'][$key] == 'password') {
6460 if (!empty($value) && preg_match('/^dolcrypt:/', $value)) {
6461 $this->array_options["options_".$key] = dolDecrypt($value);
6462 }
6463 }
6464 }
6465 } else {
6470 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6471 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6472 $this->array_options['options_' . $key] = null;
6473 }
6474 }
6475 }
6476
6477 // If field is a computed field, value must become result of compute (regardless of whether a row exists
6478 // in the element's extrafields table)
6479 if (is_array($extrafields->attributes[$this->table_element]['label'])) {
6480 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) {
6481 if (!empty($extrafields->attributes[$this->table_element]) && !empty($extrafields->attributes[$this->table_element]['computed'][$key])) {
6482 //var_dump($conf->disable_compute);
6483 if (empty($conf->disable_compute)) {
6484 global $objectoffield; // We set a global variable to $objectoffield so
6485 $objectoffield = $this; // we can use it inside computed formula
6486 $this->array_options['options_' . $key] = dol_eval($extrafields->attributes[$this->table_element]['computed'][$key], 1, 0, '2');
6487 }
6488 }
6489 }
6490 }
6491
6492 $this->db->free($resql);
6493
6494 if ($numrows) {
6495 return $numrows;
6496 } else {
6497 return 0;
6498 }
6499 } else {
6500 $this->errors[] = $this->db->lasterror;
6501 return -1;
6502 }
6503 }
6504 return 0;
6505 }
6506
6513 public function deleteExtraFields()
6514 {
6515 global $conf;
6516
6517 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6518 return 0;
6519 }
6520
6521 $this->db->begin();
6522
6523 $table_element = $this->table_element;
6524 if ($table_element == 'categorie') {
6525 $table_element = 'categories'; // For compatibility
6526 }
6527
6528 dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
6529
6530 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6531
6532 $resql = $this->db->query($sql_del);
6533 if (!$resql) {
6534 $this->error = $this->db->lasterror();
6535 $this->db->rollback();
6536 return -1;
6537 } else {
6538 $this->db->commit();
6539 return 1;
6540 }
6541 }
6542
6553 public function insertExtraFields($trigger = '', $userused = null)
6554 {
6555 global $conf, $langs, $user;
6556
6557 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
6558 return 0;
6559 }
6560
6561 if (empty($userused)) {
6562 $userused = $user;
6563 }
6564
6565 $error = 0;
6566
6567 if (!empty($this->array_options)) {
6568 // Check parameters
6569 $langs->load('admin');
6570 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
6571 $extrafields = new ExtraFields($this->db);
6572 $target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
6573
6574 // Eliminate copied source object extra fields that do not exist in target object
6575 $new_array_options = array();
6576 foreach ($this->array_options as $key => $value) {
6577 if (in_array(substr($key, 8), array_keys($target_extrafields))) { // We remove the 'options_' from $key for test
6578 $new_array_options[$key] = $value;
6579 } elseif (in_array($key, array_keys($target_extrafields))) { // We test on $key that does not contain the 'options_' prefix
6580 $new_array_options['options_'.$key] = $value;
6581 }
6582 }
6583
6584 foreach ($new_array_options as $key => $value) {
6585 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6586 $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
6587 $attributeLabel = $langs->transnoentities($extrafields->attributes[$this->table_element]['label'][$attributeKey]);
6588 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
6589 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
6590 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
6591 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$attributeKey];
6592
6593 // If we clone, we have to clean unique extrafields to prevent duplicates.
6594 // This behaviour can be prevented by external code by changing $this->context['createfromclone'] value in createFrom hook
6595 if (!empty($this->context['createfromclone']) && $this->context['createfromclone'] == 'createfromclone' && !empty($attributeUnique)) {
6596 $new_array_options[$key] = null;
6597 }
6598
6599 // Similar code than into insertExtraFields
6600 if ($attributeRequired) {
6601 $v = $this->array_options[$key];
6602 if (ExtraFields::isEmptyValue($v, $attributeType)) {
6603 $langs->load("errors");
6604 dol_syslog("Mandatory field '".$key."' is empty during create and set to required into definition of extrafields");
6605 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
6606 return -1;
6607 }
6608 }
6609
6610 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6611 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6612
6613 if (!empty($attrfieldcomputed)) {
6614 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
6615 $value = dol_eval($attrfieldcomputed, 1, 0, '2');
6616 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
6617 $new_array_options[$key] = $value;
6618 } else {
6619 $new_array_options[$key] = null;
6620 }
6621 }
6622
6623 switch ($attributeType) {
6624 case 'int':
6625 if (!is_numeric($value) && $value != '') {
6626 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6627 return -1;
6628 } elseif ($value == '') {
6629 $new_array_options[$key] = null;
6630 }
6631 break;
6632 case 'price':
6633 case 'double':
6634 $value = price2num($value);
6635 if (!is_numeric($value) && $value != '') {
6636 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." for ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6637 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
6638 return -1;
6639 } elseif ($value == '') {
6640 $value = null;
6641 }
6642 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
6643 $new_array_options[$key] = $value;
6644 break;
6645 /*case 'select': // Not required, we chose value='0' for undefined values
6646 if ($value=='-1')
6647 {
6648 $this->array_options[$key] = null;
6649 }
6650 break;*/
6651 case 'password':
6652 $algo = '';
6653 if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
6654 // If there is an encryption choice, we use it to encrypt data before insert
6655 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
6656 $algo = reset($tmparrays);
6657 if ($algo != '') {
6658 //global $action; // $action may be 'create', 'update', 'update_extras'...
6659 //var_dump($action);
6660 //var_dump($this->oldcopy);exit;
6661 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
6662 //var_dump('algo='.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
6663 if (isset($this->oldcopy->array_options[$key]) && $this->array_options[$key] == $this->oldcopy->array_options[$key]) {
6664 // If old value encrypted in database is same than submitted new value, it means we don't change it, so we don't update.
6665 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
6666 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
6667 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6668 } else {
6669 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6670 }
6671 } else {
6672 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6673 }
6674 } else {
6675 // If value has changed
6676 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
6677 if (!preg_match('/^dolcrypt:/', $this->array_options[$key])) {
6678 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6679 } else {
6680 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6681 }
6682 } else {
6683 $new_array_options[$key] = dol_hash($this->array_options[$key], $algo);
6684 }
6685 }
6686 } else {
6687 //var_dump('jjj'.$algo.' '.$this->oldcopy->array_options[$key].' -> '.$this->array_options[$key]);
6688 // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
6689 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options[$key])) { // dolibarr reversible encryption
6690 $new_array_options[$key] = dolEncrypt($this->array_options[$key]); // warning, must be called when on the master
6691 } else {
6692 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6693 }
6694 }
6695 } else {
6696 // No encryption
6697 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6698 }
6699 } else { // Common usage
6700 $new_array_options[$key] = $this->array_options[$key]; // Value is kept
6701 }
6702 break;
6703 case 'date':
6704 case 'datetime':
6705 // If data is a string instead of a timestamp, we convert it
6706 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6707 $this->array_options[$key] = strtotime($this->array_options[$key]);
6708 }
6709 $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
6710 break;
6711 case 'datetimegmt':
6712 // If data is a string instead of a timestamp, we convert it
6713 if (!is_numeric($this->array_options[$key]) || $this->array_options[$key] != intval($this->array_options[$key])) {
6714 $this->array_options[$key] = strtotime($this->array_options[$key]);
6715 }
6716 $new_array_options[$key] = $this->db->idate($this->array_options[$key], 'gmt');
6717 break;
6718 case 'link':
6719 $param_list = array_keys($attributeParam['options']);
6720 // 0 : ObjectName
6721 // 1 : classPath
6722 $InfoFieldList = explode(":", $param_list[0]);
6723 dol_include_once($InfoFieldList[1]);
6724 if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) {
6725 if ($value == '-1') { // -1 is key for no defined in combo list of objects
6726 $new_array_options[$key] = '';
6727 } elseif ($value) {
6728 $object = new $InfoFieldList[0]($this->db);
6729 '@phan-var-force CommonObject $object';
6730 if (is_numeric($value)) {
6731 $res = $object->fetch($value); // Common case
6732 } else {
6733 $res = $object->fetch(0, $value); // For compatibility
6734 }
6735
6736 if ($res > 0) {
6737 $new_array_options[$key] = $object->id;
6738 } else {
6739 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
6740 return -1;
6741 }
6742 }
6743 } else {
6744 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6745 }
6746 break;
6747 case 'checkbox':
6748 case 'chkbxlst':
6749 if (is_array($this->array_options[$key])) {
6750 $new_array_options[$key] = implode(',', $this->array_options[$key]);
6751 } else {
6752 $new_array_options[$key] = $this->array_options[$key];
6753 }
6754 break;
6755 }
6756 }
6757
6758 $this->db->begin();
6759
6760 $table_element = $this->table_element;
6761 if ($table_element == 'categorie') {
6762 $table_element = 'categories'; // For compatibility
6763 }
6764
6765 dol_syslog(get_class($this)."::insertExtraFields delete then insert", LOG_DEBUG);
6766
6767 $sql_del = "DELETE FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
6768 $this->db->query($sql_del);
6769
6770 $sql = "INSERT INTO ".$this->db->prefix().$table_element."_extrafields (fk_object";
6771 foreach ($new_array_options as $key => $value) {
6772 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6773 // Add field of attribute
6774 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') { // Only for other type than separator
6775 $sql .= ",".$attributeKey;
6776 }
6777 }
6778 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6779 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6780 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6781 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6782 $sql .= ",".$tmpkey;
6783 }
6784 }
6785 }
6786 $sql .= ") VALUES (".$this->id;
6787
6788 foreach ($new_array_options as $key => $value) {
6789 $attributeKey = substr($key, 8); // Remove 'options_' prefix
6790 // Add field of attribute
6791 if (!in_array($extrafields->attributes[$this->table_element]['type'][$attributeKey], ['separate', 'point', 'multipts', 'linestrg', 'polygon'])) { // Only for other type than separator)
6792 if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') {
6793 $sql .= ",'".$this->db->escape($new_array_options[$key])."'";
6794 } else {
6795 $sql .= ",null";
6796 }
6797 }
6798 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'point') { // for point type
6799 if (!empty($new_array_options[$key])) {
6800 $sql .= ",ST_PointFromText('".$this->db->escape($new_array_options[$key])."')";
6801 } else {
6802 $sql .= ",null";
6803 }
6804 }
6805 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'multipts') { // for point type
6806 if (!empty($new_array_options[$key])) {
6807 $sql .= ",ST_MultiPointFromText('".$this->db->escape($new_array_options[$key])."')";
6808 } else {
6809 $sql .= ",null";
6810 }
6811 }
6812 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'linestrg') { // for linestring type
6813 if (!empty($new_array_options[$key])) {
6814 $sql .= ",ST_LineFromText('".$this->db->escape($new_array_options[$key])."')";
6815 } else {
6816 $sql .= ",null";
6817 }
6818 }
6819 if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] == 'polygon') { // for polygon type
6820 if (!empty($new_array_options[$key])) {
6821 $sql .= ",ST_PolyFromText('".$this->db->escape($new_array_options[$key])."')";
6822 } else {
6823 $sql .= ",null";
6824 }
6825 }
6826 }
6827 // We must insert a default value for fields for other entities that are mandatory to avoid not null error
6828 if (!empty($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities']) && is_array($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'])) {
6829 foreach ($extrafields->attributes[$this->table_element]['mandatoryfieldsofotherentities'] as $tmpkey => $tmpval) {
6830 if (!isset($extrafields->attributes[$this->table_element]['type'][$tmpkey])) { // If field not already added previously
6831 if (in_array($tmpval, array('int', 'double', 'price'))) {
6832 $sql .= ", 0";
6833 } else {
6834 $sql .= ", ''";
6835 }
6836 }
6837 }
6838 }
6839
6840 $sql .= ")";
6841
6842 $resql = $this->db->query($sql);
6843 if (!$resql) {
6844 $this->error = $this->db->lasterror();
6845 $error++;
6846 }
6847
6848 if (!$error && $trigger) {
6849 // Call trigger
6850 $this->context = array('extrafieldaddupdate' => 1);
6851 $result = $this->call_trigger($trigger, $userused);
6852 if ($result < 0) {
6853 $error++;
6854 }
6855 // End call trigger
6856 }
6857
6858 if ($error) {
6859 $this->db->rollback();
6860 return -1;
6861 } else {
6862 $this->db->commit();
6863 return 1;
6864 }
6865 } else {
6866 return 0;
6867 }
6868 }
6869
6880 public function insertExtraLanguages($trigger = '', $userused = null)
6881 {
6882 global $conf, $langs, $user;
6883
6884 if (empty($userused)) {
6885 $userused = $user;
6886 }
6887
6888 $error = 0;
6889
6890 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
6891 return 0; // For avoid conflicts if trigger used
6892 }
6893
6894 if (is_array($this->array_languages)) {
6895 $new_array_languages = $this->array_languages;
6896
6897 foreach ($new_array_languages as $key => $value) {
6898 $attributeKey = $key;
6899 $attributeType = $this->fields[$attributeKey]['type'];
6900 $attributeLabel = $this->fields[$attributeKey]['label'];
6901
6902 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
6903 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
6904
6905 switch ($attributeType) {
6906 case 'int':
6907 if (is_array($value) || (!is_numeric($value) && $value != '')) {
6908 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6909 return -1;
6910 } elseif ($value == '') { // @phan-suppress-current-line PhanTypeComparisonFromArray
6911 $new_array_languages[$key] = null;
6912 }
6913 break;
6914 case 'double':
6915 $value = price2num((string) $value);
6916 if (!is_numeric($value) && $value != '') {
6917 dol_syslog($langs->trans("ExtraLanguageHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
6918 $this->errors[] = $langs->trans("ExtraLanguageHasWrongValue", $attributeLabel);
6919 return -1;
6920 } elseif ($value == '') {
6921 $new_array_languages[$key] = null;
6922 } else {
6923 $new_array_languages[$key] = $value;
6924 }
6925 break;
6926 /*case 'select': // Not required, we chose value='0' for undefined values
6927 if ($value=='-1')
6928 {
6929 $this->array_options[$key] = null;
6930 }
6931 break;*/
6932 }
6933 }
6934
6935 $this->db->begin();
6936
6937 $table_element = $this->table_element;
6938 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
6939 $table_element = 'categories'; // For compatibility
6940 }
6941
6942 dol_syslog(get_class($this)."::insertExtraLanguages delete then insert", LOG_DEBUG);
6943
6944 foreach ($new_array_languages as $key => $langcodearray) { // $key = 'name', 'town', ...
6945 foreach ($langcodearray as $langcode => $value) {
6946 $sql_del = "DELETE FROM ".$this->db->prefix()."object_lang";
6947 $sql_del .= " WHERE fk_object = ".((int) $this->id)." AND property = '".$this->db->escape($key)."' AND type_object = '".$this->db->escape($table_element)."'";
6948 $sql_del .= " AND lang = '".$this->db->escape($langcode)."'";
6949 $this->db->query($sql_del);
6950
6951 if ($value !== '') {
6952 $sql = "INSERT INTO ".$this->db->prefix()."object_lang (fk_object, property, type_object, lang, value";
6953 $sql .= ") VALUES (".$this->id.", '".$this->db->escape($key)."', '".$this->db->escape($table_element)."', '".$this->db->escape($langcode)."', '".$this->db->escape($value)."'";
6954 $sql .= ")";
6955
6956 $resql = $this->db->query($sql);
6957 if (!$resql) {
6958 $this->error = $this->db->lasterror();
6959 $error++;
6960 break;
6961 }
6962 }
6963 }
6964 }
6965
6966 if (!$error && $trigger) {
6967 // Call trigger
6968 $this->context = array('extralanguagesaddupdate' => 1);
6969 $result = $this->call_trigger($trigger, $userused);
6970 if ($result < 0) {
6971 $error++;
6972 }
6973 // End call trigger
6974 }
6975
6976 if ($error) {
6977 $this->db->rollback();
6978 return -1;
6979 } else {
6980 $this->db->commit();
6981 return 1;
6982 }
6983 } else {
6984 return 0;
6985 }
6986 }
6987
6998 public function updateExtraField($key, $trigger = null, $userused = null)
6999 {
7000 global $conf, $langs, $user, $hookmanager;
7001
7002 if (getDolGlobalString('MAIN_EXTRAFIELDS_DISABLED')) {
7003 return 0;
7004 }
7005
7006 if (empty($userused)) {
7007 $userused = $user;
7008 }
7009
7010 $error = 0;
7011
7012 if (!empty($this->array_options) && isset($this->array_options["options_".$key])) {
7013 // Check parameters
7014 $langs->load('admin');
7015 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
7016 $extrafields = new ExtraFields($this->db);
7017 $extrafields->fetch_name_optionals_label($this->table_element);
7018
7019 $value = $this->array_options["options_".$key];
7020
7021 $attributeKey = $key;
7022 $attributeType = $extrafields->attributes[$this->table_element]['type'][$key];
7023 $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key];
7024 $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key];
7025 $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
7026 $attributeUnique = $extrafields->attributes[$this->table_element]['unique'][$attributeKey];
7027 $attrfieldcomputed = $extrafields->attributes[$this->table_element]['computed'][$key];
7028
7029 // Similar code than into insertExtraFields
7030 if ($attributeRequired) {
7031 $mandatorypb = false;
7032 if ($attributeType == 'link' && $this->array_options["options_".$key] == '-1') {
7033 $mandatorypb = true;
7034 }
7035 if ($this->array_options["options_".$key] === '') {
7036 $mandatorypb = true;
7037 }
7038 if ($mandatorypb) {
7039 $langs->load("errors");
7040 dol_syslog("Mandatory field 'options_".$key."' is empty during update and set to required into definition of extrafields");
7041 $this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
7042 return -1;
7043 }
7044 }
7045
7046 // $new_array_options will be used for direct update, so must contains formatted data for the UPDATE.
7047 $new_array_options = $this->array_options;
7048
7049 //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
7050 //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
7051 if (!empty($attrfieldcomputed)) {
7052 if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) {
7053 $value = dol_eval($attrfieldcomputed, 1, 0, '2');
7054 dol_syslog($langs->trans("Extrafieldcomputed")." on ".$attributeLabel."(".$value.")", LOG_DEBUG);
7055
7056 $new_array_options["options_".$key] = $value;
7057
7058 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7059 } else {
7060 $new_array_options["options_".$key] = null;
7061
7062 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7063 }
7064 }
7065
7066 switch ($attributeType) {
7067 case 'int':
7068 if (!is_numeric($value) && $value != '') {
7069 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7070 return -1;
7071 } elseif ($value === '') {
7072 $new_array_options["options_".$key] = null;
7073
7074 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7075 }
7076 break;
7077 case 'price':
7078 case 'double':
7079 $value = price2num($value);
7080 if (!is_numeric($value) && $value != '') {
7081 dol_syslog($langs->trans("ExtraFieldHasWrongValue")." on ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
7082 $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
7083 return -1;
7084 } elseif ($value === '') {
7085 $value = null;
7086 }
7087 //dol_syslog("double value"." on ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
7088 $new_array_options["options_".$key] = $value;
7089
7090 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7091 break;
7092 /*case 'select': // Not required, we chose value='0' for undefined values
7093 if ($value=='-1')
7094 {
7095 $new_array_options["options_".$key] = $value;
7096
7097 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7098 }
7099 break;*/
7100 case 'password':
7101 $algo = '';
7102 if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) {
7103 // If there is an encryption choice, we use it to encrypt data before insert
7104 $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
7105 $algo = reset($tmparrays);
7106 if ($algo != '') {
7107 //global $action; // $action may be 'create', 'update', 'update_extras'...
7108 //var_dump($action);
7109 //var_dump($this->oldcopy);exit;
7110 //var_dump($key.' '.$this->array_options["options_".$key].' '.$algo);
7111 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
7112 //var_dump($this->oldcopy->array_options["options_".$key]); var_dump($this->array_options["options_".$key]);
7113 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.
7114 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7115 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7116 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7117 } else {
7118 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7119 }
7120 } else {
7121 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7122 }
7123 } else {
7124 if ($algo == 'dolcrypt') { // dolibarr reversible encryption
7125 if (!preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) {
7126 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]);
7127 } else {
7128 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7129 }
7130 } else {
7131 $new_array_options["options_".$key] = dol_hash($this->array_options["options_".$key], $algo);
7132 }
7133 }
7134 } else {
7135 if ($algo == 'dolcrypt' && !preg_match('/^dolcrypt:/', $this->array_options["options_".$key])) { // dolibarr reversible encryption
7136 $new_array_options["options_".$key] = dolEncrypt($this->array_options["options_".$key]); // warning, must be called when on the master
7137 } else {
7138 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7139 }
7140 }
7141 } else {
7142 // No encryption
7143 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7144 }
7145 } else { // Common usage
7146 $new_array_options["options_".$key] = $this->array_options["options_".$key]; // Value is kept
7147 }
7148
7149 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7150 break;
7151 case 'date':
7152 case 'datetime':
7153 if (empty($this->array_options["options_".$key])) {
7154 $new_array_options["options_".$key] = null;
7155
7156 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7157 } else {
7158 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
7159 }
7160 break;
7161 case 'datetimegmt':
7162 if (empty($this->array_options["options_".$key])) {
7163 $new_array_options["options_".$key] = null;
7164
7165 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7166 } else {
7167 $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt');
7168 }
7169 break;
7170 case 'boolean':
7171 if (empty($this->array_options["options_".$key])) {
7172 $new_array_options["options_".$key] = null;
7173
7174 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7175 }
7176 break;
7177 case 'link':
7178 if ($this->array_options["options_".$key] === '') {
7179 $new_array_options["options_".$key] = null;
7180
7181 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7182 }
7183 break;
7184 /*
7185 case 'link':
7186 $param_list = array_keys($attributeParam['options']);
7187 // 0 : ObjectName
7188 // 1 : classPath
7189 $InfoFieldList = explode(":", $param_list[0]);
7190 dol_include_once($InfoFieldList[1]);
7191 if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
7192 {
7193 if ($value == '-1') // -1 is key for no defined in combo list of objects
7194 {
7195 $new_array_options[$key] = '';
7196 } elseif ($value) {
7197 $object = new $InfoFieldList[0]($this->db);
7198 if (is_numeric($value)) $res = $object->fetch($value); // Common case
7199 else $res = $object->fetch(0, $value); // For compatibility
7200
7201 if ($res > 0) $new_array_options[$key] = $object->id;
7202 else {
7203 $this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
7204 $this->db->rollback();
7205 return -1;
7206 }
7207 }
7208 } else {
7209 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
7210 }
7211 break;
7212 */
7213 case 'checkbox':
7214 case 'chkbxlst':
7215 $new_array_options = array();
7216 if (is_array($this->array_options["options_".$key])) {
7217 $new_array_options["options_".$key] = implode(',', $this->array_options["options_".$key]);
7218 } else {
7219 $new_array_options["options_".$key] = $this->array_options["options_".$key];
7220 }
7221
7222 $this->array_options["options_".$key] = $new_array_options["options_".$key];
7223 break;
7224 }
7225
7226 $this->db->begin();
7227
7228 $linealreadyfound = 0;
7229
7230 // 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)
7231 $table_element = $this->table_element;
7232 if ($table_element == 'categorie') { // TODO Rename table llx_categories_extrafields into llx_categorie_extrafields so we can remove this.
7233 $table_element = 'categories'; // For compatibility
7234 }
7235
7236 $sql = "SELECT COUNT(rowid) as nb FROM ".$this->db->prefix().$table_element."_extrafields WHERE fk_object = ".((int) $this->id);
7237 $resql = $this->db->query($sql);
7238 if ($resql) {
7239 $tmpobj = $this->db->fetch_object($resql);
7240 if ($tmpobj) {
7241 $linealreadyfound = $tmpobj->nb;
7242 }
7243 }
7244
7245 //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit;
7246 if ($linealreadyfound) {
7247 if ($this->array_options["options_".$key] === null) {
7248 $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = null";
7249 } else {
7250 $sql = "UPDATE ".$this->db->prefix().$table_element."_extrafields SET ".$key." = '".$this->db->escape($new_array_options["options_".$key])."'";
7251 }
7252 $sql .= " WHERE fk_object = ".((int) $this->id);
7253
7254 $resql = $this->db->query($sql);
7255 if (!$resql) {
7256 $error++;
7257 $this->error = $this->db->lasterror();
7258 }
7259 } else {
7260 $result = $this->insertExtraFields('', $user);
7261 if ($result < 0) {
7262 $error++;
7263 }
7264 }
7265
7266 if (!$error) {
7267 $parameters = array('key' => $key);
7268 global $action;
7269 $reshook = $hookmanager->executeHooks('updateExtraFieldBeforeCommit', $parameters, $this, $action);
7270 if ($reshook < 0) {
7271 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
7272 }
7273 }
7274
7275 if (!$error && $trigger) {
7276 // Call trigger
7277 $this->context = array('extrafieldupdate' => 1);
7278 $result = $this->call_trigger($trigger, $userused);
7279 if ($result < 0) {
7280 $error++;
7281 }
7282 // End call trigger
7283 }
7284
7285 if ($error) {
7286 dol_syslog(__METHOD__.$this->error, LOG_ERR);
7287 $this->db->rollback();
7288 return -1;
7289 } else {
7290 $this->db->commit();
7291 return 1;
7292 }
7293 } else {
7294 return 0;
7295 }
7296 }
7297
7304 public function getExtraField($key)
7305 {
7306 return $this->array_options['options_'.$key] ?? null;
7307 }
7308
7316 public function setExtraField($key, $value)
7317 {
7318 $this->array_options['options_'.$key] = $value;
7319 }
7320
7331 public function updateExtraLanguages($key, $trigger = null, $userused = null)
7332 {
7333 global $conf, $langs, $user;
7334
7335 if (empty($userused)) {
7336 $userused = $user;
7337 }
7338
7339 $error = 0;
7340
7341 if (getDolGlobalString('MAIN_EXTRALANGUAGES_DISABLED')) {
7342 return 0; // For avoid conflicts if trigger used
7343 }
7344
7345 return 0;
7346 }
7347
7348
7364 public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
7365 {
7366 global $conf, $langs, $form;
7367
7368 if (!is_object($form)) {
7369 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
7370 $form = new Form($this->db);
7371 }
7372
7373 if (!empty($this->fields)) {
7374 $val = $this->fields[$key];
7375 }
7376
7377 // Validation tests and output
7378 $fieldValidationErrorMsg = '';
7379 $validationClass = '';
7380 $fieldValidationErrorMsg = $this->getFieldError($key);
7381 if (!empty($fieldValidationErrorMsg)) {
7382 $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
7383 } else {
7384 $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
7385 }
7386
7387 $valuemultiselectinput = array();
7388 $out = '';
7389 $type = '';
7390 $isDependList = 0;
7391 $param = array();
7392 $param['options'] = array();
7393 $reg = array();
7394 // @phan-suppress-next-line PhanTypeMismatchProperty
7395 $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
7396 // Because we work on extrafields
7397 if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7398 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7399 $type = 'link';
7400 } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7401 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7402 $type = 'link';
7403 } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
7404 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7405 $type = 'link';
7406 } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7407 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N');
7408 $type = 'sellist';
7409 } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
7410 $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N');
7411 $type = 'sellist';
7412 } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
7413 $param['options'] = array($reg[2].':'.$reg[3] => 'N');
7414 $type = 'sellist';
7415 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
7416 $param['options'] = array($reg[1] => 'N');
7417 $type = 'chkbxlst';
7418 } elseif (preg_match('/varchar\‍((\d+)\‍)/', $val['type'], $reg)) {
7419 $param['options'] = array();
7420 $type = 'varchar';
7421 $size = $reg[1];
7422 } elseif (preg_match('/varchar/', $val['type'])) {
7423 $param['options'] = array();
7424 $type = 'varchar';
7425 } else {
7426 $param['options'] = array();
7427 $type = $this->fields[$key]['type'];
7428 }
7429 //var_dump($type); var_dump($param['options']);
7430
7431 // Special case that force options and type ($type can be integer, varchar, ...)
7432 if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
7433 $param['options'] = $this->fields[$key]['arrayofkeyval'];
7434 // Special case that prevent to force $type to have multiple input @phan-suppress-next-line PhanTypeMismatchProperty
7435 if (empty($this->fields[$key]['multiinput'])) {
7436 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
7437 }
7438 }
7439
7440 $label = $this->fields[$key]['label'];
7441 //$elementtype=$this->fields[$key]['elementtype']; // Seems not used
7442 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
7443 $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
7444 // @phan-suppress-next-line PhanTypeMismatchProperty
7445 $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
7446 // @phan-suppress-next-line PhanTypeMismatchProperty
7447 $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
7448 // @phan-suppress-next-line PhanTypeMismatchProperty
7449 $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
7450 // @phan-suppress-next-line PhanTypeMismatchProperty
7451 $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);
7452
7453 // @phan-suppress-next-line PhanTypeMismatchProperty
7454 $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
7455 // @phan-suppress-next-line PhanTypeMismatchProperty
7456 $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
7457 $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);
7458
7459 $objectid = $this->id;
7460
7461 if ($computed) {
7462 if (!preg_match('/^search_/', $keyprefix)) {
7463 return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
7464 } else {
7465 return '';
7466 }
7467 }
7468
7469 // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
7470 if (empty($morecss) && !empty($val['css'])) {
7471 $morecss = $val['css'];
7472 } elseif (empty($morecss)) {
7473 if ($type == 'date') {
7474 $morecss = 'minwidth100imp';
7475 } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id
7476 $morecss = 'minwidth200imp';
7477 } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
7478 $morecss = 'maxwidth75';
7479 } elseif ($type == 'url') {
7480 $morecss = 'minwidth400';
7481 } elseif ($type == 'boolean') {
7482 $morecss = '';
7483 } else {
7484 if (is_numeric($size) && round((float) $size) < 12) {
7485 $morecss = 'minwidth100';
7486 } elseif (is_numeric($size) && round((float) $size) <= 48) {
7487 $morecss = 'minwidth200';
7488 } else {
7489 $morecss = 'minwidth400';
7490 }
7491 }
7492 }
7493
7494 // Add validation state class
7495 if (!empty($validationClass)) {
7496 $morecss .= $validationClass;
7497 }
7498
7499 if (in_array($type, array('date'))) {
7500 $tmp = explode(',', $size);
7501 $newsize = $tmp[0];
7502 $showtime = 0;
7503
7504 // Do not show current date when field not required (see selectDate() method)
7505 if (!$required && $value == '') {
7506 $value = '-1';
7507 }
7508
7509 // TODO Must also support $moreparam
7510 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
7511 } elseif (in_array($type, array('datetime'))) {
7512 $tmp = explode(',', $size);
7513 $newsize = $tmp[0];
7514 $showtime = 1;
7515
7516 // Do not show current date when field not required (see selectDate() method)
7517 if (!$required && $value == '') {
7518 $value = '-1';
7519 }
7520
7521 // TODO Must also support $moreparam
7522 $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
7523 } elseif (in_array($type, array('duration'))) {
7524 $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1);
7525 } elseif (in_array($type, array('int', 'integer'))) {
7526 $tmp = explode(',', $size);
7527 $newsize = $tmp[0];
7528 $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' : '').'>';
7529 } elseif (in_array($type, array('real'))) {
7530 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7531 } elseif (preg_match('/varchar/', (string) $type)) {
7532 $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' : '').'>';
7533 } elseif (in_array($type, array('email', 'mail', 'phone', 'url', 'ip'))) {
7534 $out = '<input type="text" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').($autofocusoncreate ? ' autofocus' : '').'>';
7535 } elseif (preg_match('/^text/', (string) $type)) {
7536 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7537 if (!empty($param['options'])) {
7538 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
7539 //var_dump($param['options']);
7540 $out .= $form->selectarray($keyprefix.$key.$keysuffix."_multiinput", $param['options'], '', 1, 0, 0, "flat maxwidthonphone".$morecss);
7541 $out .= '<input id="'.$keyprefix.$key.$keysuffix.'_multiinputadd" type="button" class="button" value="'.$langs->trans("Add").'">';
7542 $out .= "<script>";
7543 $out .= '
7544 function handlemultiinputdisabling(htmlname){
7545 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
7546 multiinput = $("#"+htmlname+"_multiinput");
7547 multiinput.find("option").each(function(){
7548 tmpval = $("#"+htmlname).val();
7549 tmpvalarray = tmpval.split("\n");
7550 valtotest = $(this).val();
7551 if(tmpvalarray.includes(valtotest)){
7552 $(this).prop("disabled",true);
7553 } else {
7554 if($(this).prop("disabled") == true){
7555 console.log(valtotest)
7556 $(this).prop("disabled", false);
7557 }
7558 }
7559 });
7560 }
7561
7562 $(document).ready(function () {
7563 $("#'.$keyprefix.$key.$keysuffix.'_multiinputadd").on("click",function() {
7564 tmpval = $("#'.$keyprefix.$key.$keysuffix.'").val();
7565 tmpvalarray = tmpval.split(",");
7566 valtotest = $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val();
7567 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
7568 console.log("We add the selected value to the text area '.$keyprefix.$key.$keysuffix.'");
7569 if(tmpval == ""){
7570 tmpval = valtotest;
7571 } else {
7572 tmpval = tmpval + "\n" + valtotest;
7573 }
7574 $("#'.$keyprefix.$key.$keysuffix.'").val(tmpval);
7575 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7576 $("#'.$keyprefix.$key.$keysuffix.'_multiinput").val(-1);
7577 } else {
7578 console.log("We add nothing the text area '.$keyprefix.$key.$keysuffix.'");
7579 }
7580 });
7581 $("#'.$keyprefix.$key.$keysuffix.'").on("change",function(){
7582 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7583 });
7584 handlemultiinputdisabling("'.$keyprefix.$key.$keysuffix.'");
7585 })';
7586 $out .= "</script>";
7587 $value = str_replace(',', "\n", $value);
7588 }
7589 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7590 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
7591 $out .= (string) $doleditor->Create(1, '', true, '', '', '', $morecss);
7592 } else {
7593 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7594 }
7595 } elseif (preg_match('/^html/', (string) $type)) {
7596 if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field
7597 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
7598 $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
7599 $out = (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
7600 } else {
7601 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
7602 }
7603 } elseif ($type == 'boolean') {
7604 $checked = '';
7605 if (!empty($value)) {
7606 $checked = ' checked value="1" ';
7607 } else {
7608 $checked = ' value="1" ';
7609 }
7610 $out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
7611 } elseif ($type == 'price') {
7612 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7613 $value = price($value);
7614 }
7615 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
7616 } elseif (preg_match('/^double(\‍([0-9],[0-9]\‍)){0,1}/', (string) $type)) {
7617 if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format.
7618 $value = price($value);
7619 }
7620 $out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
7621 } elseif ($type == 'select') { // combo list
7622 $out = '';
7623 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7624 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7625 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7626 }
7627
7628 $tmpselect = '';
7629 $nbchoice = 0;
7630 foreach ($param['options'] as $keyb => $valb) {
7631 if ((string) $keyb == '') {
7632 continue;
7633 }
7634 if (strpos($valb, "|") !== false) {
7635 list($valb, $parent) = explode('|', $valb);
7636 }
7637 $nbchoice++;
7638 $tmpselect .= '<option value="'.$keyb.'"';
7639 $tmpselect .= (((string) $value == (string) $keyb) ? ' selected' : '');
7640 if (!empty($parent)) {
7641 $isDependList = 1;
7642 }
7643 $tmpselect .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
7644 $tmpselect .= '>'.$langs->trans($valb).'</option>';
7645 }
7646
7647 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7648 if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1) || $nbchoice >= 2) {
7649 $out .= '<option value="0">&nbsp;</option>';
7650 }
7651 $out .= $tmpselect;
7652 $out .= '</select>';
7653 } elseif ($type == 'sellist') {
7654 $out = '';
7655 if (!empty($conf->use_javascript_ajax) && !getDolGlobalString('MAIN_EXTRAFIELDS_DISABLE_SELECT2')) {
7656 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7657 $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
7658 }
7659
7660 $out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
7661 if (is_array($param['options'])) {
7662 $tmpparamoptions = array_keys($param['options']);
7663 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
7664
7665 $InfoFieldList = explode(":", $paramoptions[0], 5);
7666 // 0 : tableName
7667 // 1 : label field name
7668 // 2 : key fields name (if different of rowid)
7669 // optional parameters...
7670 // 3 : key field parent (for dependent lists). How this is used ?
7671 // 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".
7672 // 5 : string category type. This replace the filter.
7673 // 6 : ids categories list separated by comma for category root. This replace the filter.
7674 // 7 : sort field
7675
7676 // If there is filter
7677 if (! empty($InfoFieldList[4])) {
7678 $pos = 0;
7679 $parenthesisopen = 0;
7680 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
7681 if (substr($InfoFieldList[4], $pos, 1) == '(') {
7682 $parenthesisopen++;
7683 }
7684 if (substr($InfoFieldList[4], $pos, 1) == ')') {
7685 $parenthesisopen--;
7686 }
7687 $pos++;
7688 }
7689 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7690 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7691 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
7692 $InfoFieldList[4] = $tmpbefore;
7693 if ($tmpafter !== '') {
7694 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
7695 }
7696 //var_dump($InfoFieldList);
7697
7698 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
7699 $reg = array();
7700 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
7701 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
7702 }
7703
7704 //var_dump($InfoFieldList);
7705 }
7706
7707 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
7708
7709 $parentName = '';
7710 $parentField = '';
7711
7712 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7713
7714 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7715 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7716 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7717 } else {
7718 $keyList = $InfoFieldList[2].' as rowid';
7719 }
7720 }
7721 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7722 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7723 $keyList .= ', '.$parentField;
7724 }
7725
7726 $filter_categorie = false;
7727 if (count($InfoFieldList) > 5) {
7728 if ($InfoFieldList[0] == 'categorie') {
7729 $filter_categorie = true;
7730 }
7731 }
7732
7733 if (!$filter_categorie) {
7734 $fields_label = explode('|', $InfoFieldList[1]);
7735 if (is_array($fields_label)) {
7736 $keyList .= ', ';
7737 $keyList .= implode(', ', $fields_label);
7738 }
7739
7740 $sqlwhere = '';
7741 $sql = "SELECT " . $keyList;
7742 $sql .= " FROM " . $this->db->prefix() . $InfoFieldList[0];
7743
7744 if (!empty($InfoFieldList[4])) {
7745 // can use SELECT request
7746 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7747 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7748 }
7749
7750 // current object id can be use into filter
7751 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7752 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
7753 } else {
7754 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7755 }
7756
7757 // We have to join on extrafield table
7758 $errstr = '';
7759 if (strpos($InfoFieldList[4], 'extra') !== false) {
7760 $sql .= " as main, " . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . "_extrafields as extra";
7761 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7762 $sqlwhere .= " AND " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
7763 } else {
7764 $sqlwhere .= " WHERE " . forgeSQLFromUniversalSearchCriteria($InfoFieldList[4], $errstr, 1);
7765 }
7766 } else {
7767 $sqlwhere .= ' WHERE 1=1';
7768 }
7769
7770 // Add Usf filter on second line
7771 /*
7772 if ($Usf) {
7773 $errorstr = '';
7774 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
7775 if (!$errorstr) {
7776 $sqlwhere .= $sqlusf;
7777 } else {
7778 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
7779 }
7780 }
7781 */
7782
7783 // Some tables may have field, some other not. For the moment we disable it.
7784 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
7785 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
7786 }
7787 $sql .= $sqlwhere;
7788 //print $sql;
7789
7790 // Note: $InfoFieldList can be 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:Sortfield]]]]]]'
7791 if (isset($InfoFieldList[7]) && preg_match('/^[a-z0-9_\-,]+$/i', $InfoFieldList[7])) {
7792 $sql .= " ORDER BY ".$this->db->escape($InfoFieldList[7]);
7793 } else {
7794 $sql .= " ORDER BY ".$this->db->sanitize(implode(', ', $fields_label));
7795 }
7796
7797 dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
7798 $resql = $this->db->query($sql);
7799 if ($resql) {
7800 $out .= '<option value="0">&nbsp;</option>';
7801 $num = $this->db->num_rows($resql);
7802 $i = 0;
7803 while ($i < $num) {
7804 $labeltoshow = '';
7805 $obj = $this->db->fetch_object($resql);
7806
7807 // Several field into label (eq table:code|libelle:rowid)
7808 $notrans = false;
7809 $fields_label = explode('|', $InfoFieldList[1]);
7810 if (count($fields_label) > 1) {
7811 $notrans = true;
7812 foreach ($fields_label as $field_toshow) {
7813 $labeltoshow .= $obj->$field_toshow . ' ';
7814 }
7815 } else {
7816 $labeltoshow = $obj->{$InfoFieldList[1]};
7817 }
7818 $labeltoshow = dol_trunc($labeltoshow, 45);
7819
7820 if ($value == $obj->rowid) {
7821 foreach ($fields_label as $field_toshow) {
7822 $translabel = $langs->trans($obj->$field_toshow);
7823 if ($translabel != $obj->$field_toshow) {
7824 $labeltoshow = dol_trunc($translabel) . ' ';
7825 } else {
7826 $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
7827 }
7828 }
7829 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7830 } else {
7831 if (!$notrans) {
7832 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
7833 if ($translabel != $obj->{$InfoFieldList[1]}) {
7834 $labeltoshow = dol_trunc($translabel, 18);
7835 } else {
7836 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
7837 }
7838 }
7839 if (empty($labeltoshow)) {
7840 $labeltoshow = '(not defined)';
7841 }
7842 if ($value == $obj->rowid) {
7843 $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
7844 }
7845
7846 if (!empty($InfoFieldList[3]) && $parentField) {
7847 $parent = $parentName . ':' . $obj->{$parentField};
7848 $isDependList = 1;
7849 }
7850
7851 $out .= '<option value="' . $obj->rowid . '"';
7852 $out .= ($value == $obj->rowid ? ' selected' : '');
7853 $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
7854 $out .= '>' . $labeltoshow . '</option>';
7855 }
7856
7857 $i++;
7858 }
7859 $this->db->free($resql);
7860 } else {
7861 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
7862 }
7863 } else {
7864 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
7865 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[$InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
7866 $out .= '<option value="0">&nbsp;</option>';
7867 foreach ($data as $data_key => $data_value) {
7868 $out .= '<option value="' . $data_key . '"';
7869 $out .= ($value == $data_key ? ' selected' : '');
7870 $out .= '>' . $data_value . '</option>';
7871 }
7872 }
7873 }
7874 $out .= '</select>';
7875 } elseif ($type == 'checkbox') {
7876 $value_arr = explode(',', $value);
7877 $out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, 0, 0, $morecss, 0, '100%');
7878 } elseif ($type == 'radio') {
7879 $out = '';
7880 foreach ($param['options'] as $keyopt => $valopt) {
7881 $out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
7882 $out .= ' value="'.$keyopt.'"';
7883 $out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
7884 $out .= ($value == $keyopt ? 'checked' : '');
7885 $out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$valopt.'</label><br>';
7886 }
7887 } elseif ($type == 'chkbxlst') {
7888 if (is_array($value)) {
7889 $value_arr = $value;
7890 } else {
7891 $value_arr = explode(',', $value);
7892 }
7893
7894 if (is_array($param['options'])) {
7895 $tmpparamoptions = array_keys($param['options']);
7896 $paramoptions = preg_split('/[\r\n]+/', $tmpparamoptions[0]);
7897
7898 $InfoFieldList = explode(":", $paramoptions[0], 5);
7899 // 0 : tableName
7900 // 1 : label field name
7901 // 2 : key fields name (if different of rowid)
7902 // optional parameters...
7903 // 3 : key field parent (for dependent lists). How this is used ?
7904 // 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".
7905 // 5 : string category type. This replace the filter.
7906 // 6 : ids categories list separated by comma for category root. This replace the filter.
7907 // 7 : sort field
7908
7909 // If there is a filter
7910 if (! empty($InfoFieldList[4])) {
7911 $pos = 0;
7912 $parenthesisopen = 0;
7913 while (substr($InfoFieldList[4], $pos, 1) !== '' && ($parenthesisopen || $pos == 0 || substr($InfoFieldList[4], $pos, 1) != ':')) {
7914 if (substr($InfoFieldList[4], $pos, 1) == '(') {
7915 $parenthesisopen++;
7916 }
7917 if (substr($InfoFieldList[4], $pos, 1) == ')') {
7918 $parenthesisopen--;
7919 }
7920 $pos++;
7921 }
7922 $tmpbefore = substr($InfoFieldList[4], 0, $pos);
7923 $tmpafter = substr($InfoFieldList[4], $pos + 1);
7924 //var_dump($InfoFieldList[4].' -> '.$pos); var_dump($tmpafter);
7925 $InfoFieldList[4] = $tmpbefore;
7926 if ($tmpafter !== '') {
7927 $InfoFieldList = array_merge($InfoFieldList, explode(':', $tmpafter));
7928 }
7929
7930 // Fix better compatibility with some old extrafield syntax filter "(field=123)"
7931 $reg = array();
7932 if (preg_match('/^\‍(?([a-z0-9]+)([=<>]+)(\d+)\‍)?$/i', $InfoFieldList[4], $reg)) {
7933 $InfoFieldList[4] = '('.$reg[1].':'.$reg[2].':'.$reg[3].')';
7934 }
7935
7936 //var_dump($InfoFieldList);
7937 }
7938
7939 //$Usf = empty($paramoptions[1]) ? '' :$paramoptions[1];
7940
7941 '@phan-var-force array{0:string,1:string,2:string,3:string,3:string,5:string,6:string} $InfoFieldList';
7942
7943 $parentName = '';
7944 $parentField = '';
7945
7946 $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
7947
7948 if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
7949 list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
7950 $keyList .= ', '.$parentField;
7951 }
7952 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
7953 if (strpos($InfoFieldList[4], 'extra.') !== false) {
7954 $keyList = 'main.'.$InfoFieldList[2].' as rowid';
7955 } else {
7956 $keyList = $InfoFieldList[2].' as rowid';
7957 }
7958 }
7959
7960 $filter_categorie = false;
7961 if (count($InfoFieldList) > 5) {
7962 if ($InfoFieldList[0] == 'categorie') {
7963 $filter_categorie = true;
7964 }
7965 }
7966
7967 // Common filter
7968 if (!$filter_categorie) {
7969 $fields_label = explode('|', $InfoFieldList[1]);
7970 if (is_array($fields_label)) {
7971 $keyList .= ', ';
7972 $keyList .= implode(', ', $fields_label);
7973 }
7974
7975 $sqlwhere = '';
7976 $sql = "SELECT " . $keyList;
7977 $sql .= ' FROM ' . $this->db->prefix() . $InfoFieldList[0];
7978
7979 if (!empty($InfoFieldList[4])) {
7980 // can use SELECT request
7981 if (strpos($InfoFieldList[4], '$SEL$') !== false) {
7982 $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
7983 }
7984
7985 // current object id can be use into filter
7986 if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
7987 $InfoFieldList[4] = str_replace('$ID$', (string) $objectid, $InfoFieldList[4]);
7988 } else {
7989 $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
7990 }
7991
7992 // We have to join on extrafield table
7993 $errstr = '';
7994 if (strpos($InfoFieldList[4], 'extra') !== false) {
7995 $sql .= ' as main, ' . $this->db->sanitize($this->db->prefix() . $InfoFieldList[0]) . '_extrafields as extra';
7996 $sqlwhere .= " WHERE extra.fk_object = main." . $this->db->sanitize($InfoFieldList[2]);
7997 $sqlwhere .= " AND " . $InfoFieldList[4];
7998 } else {
7999 $sqlwhere .= " WHERE " . $InfoFieldList[4];
8000 }
8001 } else {
8002 $sqlwhere .= ' WHERE 1=1';
8003 }
8004
8005 // Add Usf filter on second line
8006 /*
8007 if ($Usf) {
8008 $errorstr = '';
8009 $sqlusf .= forgeSQLFromUniversalSearchCriteria($Usf, $errorstr);
8010 if (!$errorstr) {
8011 $sqlwhere .= $sqlusf;
8012 } else {
8013 $sqlwhere .= " AND invalid_usf_filter_of_extrafield";
8014 }
8015 }
8016 */
8017
8018 // Some tables may have field, some other not. For the moment we disable it.
8019 if (in_array($InfoFieldList[0], array('tablewithentity'))) {
8020 $sqlwhere .= " AND entity = " . ((int) $conf->entity);
8021 }
8022 // $sql.=preg_replace('/^ AND /','',$sqlwhere);
8023 // print $sql;
8024
8025 $sql .= $sqlwhere;
8026
8027 dol_syslog(get_class($this) . '::showInputField type=chkbxlst', LOG_DEBUG);
8028
8029 $resql = $this->db->query($sql);
8030 if ($resql) {
8031 $num = $this->db->num_rows($resql);
8032 $i = 0;
8033
8034 $data = array();
8035
8036 while ($i < $num) {
8037 $labeltoshow = '';
8038 $obj = $this->db->fetch_object($resql);
8039
8040 $notrans = false;
8041 // Several field into label (eq table:code|libelle:rowid)
8042 $fields_label = explode('|', $InfoFieldList[1]);
8043 if (count($fields_label) > 1) {
8044 $notrans = true;
8045 foreach ($fields_label as $field_toshow) {
8046 $labeltoshow .= $obj->$field_toshow . ' ';
8047 }
8048 } else {
8049 $labeltoshow = $obj->{$InfoFieldList[1]};
8050 }
8051 $labeltoshow = dol_trunc($labeltoshow, 45);
8052
8053 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8054 foreach ($fields_label as $field_toshow) {
8055 $translabel = $langs->trans($obj->$field_toshow);
8056 if ($translabel != $obj->$field_toshow) {
8057 $labeltoshow = dol_trunc($translabel, 18) . ' ';
8058 } else {
8059 $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
8060 }
8061 }
8062
8063 $data[$obj->rowid] = $labeltoshow;
8064 } else {
8065 if (!$notrans) {
8066 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8067 if ($translabel != $obj->{$InfoFieldList[1]}) {
8068 $labeltoshow = dol_trunc($translabel, 18);
8069 } else {
8070 $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
8071 }
8072 }
8073 if (empty($labeltoshow)) {
8074 $labeltoshow = '(not defined)';
8075 }
8076
8077 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8078 $data[$obj->rowid] = $labeltoshow;
8079 }
8080
8081 if (!empty($InfoFieldList[3]) && $parentField) {
8082 $parent = $parentName . ':' . $obj->{$parentField};
8083 $isDependList = 1;
8084 }
8085
8086 $data[(int) $obj->rowid] = $labeltoshow;
8087 }
8088
8089 $i++;
8090 }
8091 $this->db->free($resql);
8092
8093 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
8094 } else {
8095 print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
8096 }
8097 } else {
8098 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
8099 $data = $form->select_all_categories(Categorie::$MAP_ID_TO_CODE[(int) $InfoFieldList[5]], '', 'parent', 64, $InfoFieldList[6], 1, 1);
8100 $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, 0, 0, $morecss, 0, '100%');
8101 }
8102 }
8103 } elseif ($type == 'link') {
8104 // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
8105 // Filter can contains some ':' inside.
8106 $param_list = array_keys($param['options']);
8107 $param_list_array = explode(':', $param_list[0], 4);
8108
8109 $showempty = (($required && $default != '') ? 0 : 1);
8110
8111 if (!preg_match('/search_/', $keyprefix)) {
8112 if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button
8113 // @phan-suppress-next-line PhanTypeMismatchProperty
8114 if (!empty($this->fields[$key]['picto'])) {
8115 $morecss .= ' widthcentpercentminusxx';
8116 } else {
8117 $morecss .= ' widthcentpercentminusx';
8118 }
8119 } else {
8120 // @phan-suppress-next-line PhanTypeMismatchProperty
8121 if (!empty($this->fields[$key]['picto'])) {
8122 $morecss .= ' widthcentpercentminusx';
8123 }
8124 }
8125 }
8126 $objectfield = $this->element.($this->module ? '@'.$this->module : '').':'.$key.$keysuffix;
8127 $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), '', $objectfield);
8128
8129 if (!empty($param_list_array[2])) { // If the entry into $fields is set, we must add a create button
8130 if ((!GETPOSTISSET('backtopage') || strpos(GETPOST('backtopage'), $_SERVER['PHP_SELF']) === 0) // // To avoid to open several times the 'Plus' button (we accept only one level)
8131 && empty($val['disabled']) && empty($nonewbutton)) { // and to avoid to show the button if the field is protected by a "disabled".
8132 list($class, $classfile) = explode(':', $param_list[0]);
8133 if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
8134 $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
8135 } else {
8136 $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.strtolower($class).'_card.php', 1);
8137 }
8138 $paramforthenewlink = '';
8139 $paramforthenewlink .= (GETPOSTISSET('action') ? '&action='.GETPOST('action', 'aZ09') : '');
8140 $paramforthenewlink .= (GETPOSTISSET('id') ? '&id='.GETPOSTINT('id') : '');
8141 $paramforthenewlink .= (GETPOSTISSET('origin') ? '&origin='.GETPOST('origin', 'aZ09') : '');
8142 $paramforthenewlink .= (GETPOSTISSET('originid') ? '&originid='.GETPOSTINT('originid') : '');
8143 $paramforthenewlink .= '&fk_'.strtolower($class).'=--IDFORBACKTOPAGE--';
8144 // TODO Add JavaScript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
8145 $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>';
8146 }
8147 }
8148 } elseif ($type == 'password') {
8149 // If prefix is 'search_', field is used as a filter, we use a common text field.
8150 if ($keyprefix.$key.$keysuffix == 'pass_crypted') {
8151 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="pass" id="pass" value="" '.($moreparam ? $moreparam : '').'>';
8152 $out .= '<input type="hidden" name="pass_crypted" id="pass_crypted" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
8153 } else {
8154 $out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
8155 }
8156 } elseif ($type == 'array') {
8157 $newval = $val;
8158 $newval['type'] = 'varchar(256)';
8159
8160 $out = '';
8161 if (!empty($value)) {
8162 foreach ($value as $option) {
8163 $out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8164 $out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $morecss).'<br></span>';
8165 }
8166 }
8167 $out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
8168
8169 $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
8170 $newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $morecss).'<br></span>';
8171
8172 if (!empty($conf->use_javascript_ajax)) {
8173 $out .= '
8174 <script nonce="'.getNonce().'">
8175 $(document).ready(function() {
8176 $("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
8177 $("'.dol_escape_js($newInput).'").insertBefore(this);
8178 });
8179
8180 $(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
8181 $(this).parent().remove();
8182 });
8183 });
8184 </script>';
8185 }
8186 }
8187 if (!empty($hidden)) {
8188 $out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
8189 }
8190
8191 if ($isDependList == 1) {
8192 $out .= $this->getJSListDependancies('_common');
8193 }
8194 /* Add comments
8195 if ($type == 'date') $out.=' (YYYY-MM-DD)';
8196 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
8197 */
8198
8199 // Display error message for field
8200 if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
8201 $out .= ' '.getFieldErrorIcon($fieldValidationErrorMsg);
8202 }
8203
8204 return $out;
8205 }
8206
8220 public function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '')
8221 {
8222 global $conf, $langs, $form;
8223
8224 if (!is_object($form)) {
8225 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
8226 $form = new Form($this->db);
8227 }
8228
8229 //$label = empty($val['label']) ? '' : $val['label'];
8230 $type = empty($val['type']) ? '' : $val['type'];
8231 $size = empty($val['css']) ? '' : $val['css'];
8232 $reg = array();
8233
8234 // Convert var to be able to share same code than showOutputField of extrafields
8235 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8236 $type = 'varchar'; // convert varchar(xx) int varchar
8237 $size = $reg[1];
8238 } elseif (preg_match('/varchar/', $type)) {
8239 $type = 'varchar'; // convert varchar(xx) int varchar
8240 }
8241 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8242 // @phan-suppress-next-line PhanTypeMismatchProperty
8243 if (empty($this->fields[$key]['multiinput'])) {
8244 $type = (($this->fields[$key]['type'] == 'checkbox') ? $this->fields[$key]['type'] : 'select');
8245 }
8246 }
8247 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8248 $type = 'link';
8249 }
8250
8251 $default = empty($val['default']) ? '' : $val['default'];
8252 $computed = empty($val['computed']) ? '' : $val['computed'];
8253 $unique = empty($val['unique']) ? '' : $val['unique'];
8254 $required = empty($val['required']) ? '' : $val['required'];
8255 $param = array();
8256 $param['options'] = array();
8257
8258 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8259 $param['options'] = $val['arrayofkeyval'];
8260 }
8261 if (preg_match('/^integer:([^:]*):([^:]*)/i', $val['type'], $reg)) { // ex: integer:User:user/class/user.class.php
8262 $type = 'link';
8263 $stringforoptions = $reg[1].':'.$reg[2];
8264 // Special case: Force addition of getnomurlparam1 to -1 for users
8265 if ($reg[1] == 'User') {
8266 $stringforoptions .= ':#getnomurlparam1=-1';
8267 }
8268 $param['options'] = array($stringforoptions => $stringforoptions);
8269 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8270 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8271 $type = 'sellist';
8272 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8273 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8274 $type = 'sellist';
8275 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8276 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8277 $type = 'sellist';
8278 } elseif (preg_match('/^chkbxlst:(.*)/i', $val['type'], $reg)) {
8279 $param['options'] = array($reg[1] => 'N');
8280 $type = 'chkbxlst';
8281 }
8282
8283 $langfile = empty($val['langfile']) ? '' : $val['langfile'];
8284 $list = (empty($val['list']) ? '' : $val['list']);
8285 $help = (empty($val['help']) ? '' : $val['help']);
8286 $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)
8287
8288 if ($hidden) {
8289 return '';
8290 }
8291
8292 // If field is a computed field, value must become result of compute
8293 if ($computed) {
8294 // Make the eval of compute string
8295 //var_dump($computed);
8296 $value = dol_eval($computed, 1, 0, '2');
8297 }
8298
8299 if (empty($morecss)) {
8300 if ($type == 'date') {
8301 $morecss = 'minwidth100imp';
8302 } elseif ($type == 'datetime' || $type == 'timestamp') {
8303 $morecss = 'minwidth200imp';
8304 } elseif (in_array($type, array('int', 'double', 'price'))) {
8305 $morecss = 'maxwidth75';
8306 } elseif ($type == 'url') {
8307 $morecss = 'minwidth400';
8308 } elseif ($type == 'boolean') {
8309 $morecss = '';
8310 } else {
8311 if (is_numeric($size) && round((float) $size) < 12) {
8312 $morecss = 'minwidth100';
8313 } elseif (is_numeric($size) && round((float) $size) <= 48) {
8314 $morecss = 'minwidth200';
8315 } else {
8316 $morecss = 'minwidth400';
8317 }
8318 }
8319 }
8320
8321 // Format output value differently according to properties of field
8322 if (in_array($key, array('rowid', 'ref')) && method_exists($this, 'getNomUrl')) {
8323 // @phan-suppress-next-line PhanTypeMismatchProperty
8324 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.
8325 $value = $this->getNomUrl(1, '', 0, '', 1);
8326 }
8327 } elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
8328 $value = $this->getLibStatut(3);
8329 } elseif ($type == 'date') {
8330 if (!empty($value)) {
8331 $value = dol_print_date($value, 'day'); // We suppose dates without time are always gmt (storage of course + output)
8332 } else {
8333 $value = '';
8334 }
8335 } elseif ($type == 'datetime' || $type == 'timestamp') {
8336 if (!empty($value)) {
8337 $value = dol_print_date($value, 'dayhour', 'tzuserrel');
8338 } else {
8339 $value = '';
8340 }
8341 } elseif ($type == 'duration') {
8342 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
8343 if (!is_null($value) && $value !== '') {
8344 $value = convertSecondToTime((int) $value, 'allhourmin');
8345 }
8346 } elseif ($type == 'double' || $type == 'real') {
8347 if (!is_null($value) && $value !== '') {
8348 $value = price($value);
8349 }
8350 } elseif ($type == 'boolean') {
8351 $checked = '';
8352 if (!empty($value)) {
8353 $checked = ' checked ';
8354 }
8355 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
8356 $value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
8357 } else {
8358 $value = yn($value ? 1 : 0);
8359 }
8360 } elseif ($type == 'mail' || $type == 'email') {
8361 $value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
8362 } elseif ($type == 'url') {
8363 $value = dol_print_url($value, '_blank', 32, 1);
8364 } elseif ($type == 'phone') {
8365 $value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 'phone');
8366 } elseif ($type == 'ip') {
8367 $value = dol_print_ip($value, 0);
8368 } elseif ($type == 'price') {
8369 if (!is_null($value) && $value !== '') {
8370 $value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
8371 }
8372 } elseif ($type == 'select') {
8373 $value = isset($param['options'][(string) $value]) ? $param['options'][(string) $value] : '';
8374 if (strpos($value, "|") !== false) {
8375 $value = $langs->trans(explode('|', $value)[0]);
8376 } elseif (! is_numeric($value)) {
8377 $value = $langs->trans($value);
8378 }
8379 } elseif ($type == 'sellist') {
8380 $param_list = array_keys($param['options']);
8381 $InfoFieldList = explode(":", $param_list[0]);
8382
8383 $selectkey = "rowid";
8384 $keyList = 'rowid';
8385
8386 if (count($InfoFieldList) > 2 && !empty($InfoFieldList[2])) {
8387 $selectkey = $InfoFieldList[2];
8388 $keyList = $InfoFieldList[2].' as rowid';
8389 }
8390
8391 $fields_label = explode('|', $InfoFieldList[1]);
8392 if (is_array($fields_label)) {
8393 $keyList .= ', ';
8394 $keyList .= implode(', ', $fields_label);
8395 }
8396
8397 $filter_categorie = false;
8398 if (count($InfoFieldList) > 5) {
8399 if ($InfoFieldList[0] == 'categorie') {
8400 $filter_categorie = true;
8401 }
8402 }
8403
8404 $sql = "SELECT ".$keyList;
8405 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
8406 if (isset($InfoFieldList[4]) && strpos($InfoFieldList[4], 'extra') !== false) {
8407 $sql .= ' as main';
8408 }
8409 if ($selectkey == 'rowid' && empty($value)) {
8410 $sql .= " WHERE ".$selectkey." = 0";
8411 } elseif ($selectkey == 'rowid') {
8412 $sql .= " WHERE ".$selectkey." = ".((int) $value);
8413 } else {
8414 $sql .= " WHERE ".$selectkey." = '".$this->db->escape($value)."'";
8415 }
8416
8417 //$sql.= ' AND entity = '.$conf->entity;
8418
8419 dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
8420 $resql = $this->db->query($sql);
8421 if ($resql) {
8422 if (!$filter_categorie) {
8423 $value = ''; // value was used, so now we reset it to use it to build final output
8424 $numrows = $this->db->num_rows($resql);
8425 if ($numrows) {
8426 $obj = $this->db->fetch_object($resql);
8427
8428 // Several field into label (eq table:code|libelle:rowid)
8429 $fields_label = explode('|', $InfoFieldList[1]);
8430
8431 if (is_array($fields_label) && count($fields_label) > 1) {
8432 foreach ($fields_label as $field_toshow) {
8433 $translabel = '';
8434 if (!empty($obj->$field_toshow)) {
8435 $translabel = $langs->trans($obj->$field_toshow);
8436 }
8437 if ($translabel != $field_toshow) {
8438 $value .= dol_trunc($translabel, 18) . ' ';
8439 } else {
8440 $value .= $obj->$field_toshow . ' ';
8441 }
8442 }
8443 } else {
8444 $translabel = '';
8445 if (!empty($obj->{$InfoFieldList[1]})) {
8446 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8447 }
8448 if ($translabel != $obj->{$InfoFieldList[1]}) {
8449 $value = dol_trunc($translabel, 18);
8450 } else {
8451 $value = $obj->{$InfoFieldList[1]};
8452 }
8453 }
8454 }
8455 } else {
8456 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
8457
8458 $toprint = array();
8459 $obj = $this->db->fetch_object($resql);
8460 $c = new Categorie($this->db);
8461 $c->fetch($obj->rowid);
8462 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
8463 foreach ($ways as $way) {
8464 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
8465 }
8466 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
8467 }
8468 } else {
8469 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8470 }
8471 } elseif ($type == 'radio') {
8472 $value = $param['options'][(string) $value];
8473 } elseif ($type == 'checkbox') {
8474 $value_arr = explode(',', (string) $value);
8475 $value = '';
8476 if (is_array($value_arr) && count($value_arr) > 0) {
8477 $toprint = array();
8478 foreach ($value_arr as $keyval => $valueval) {
8479 if (!empty($valueval)) {
8480 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $param['options'][$valueval] . '</li>';
8481 }
8482 }
8483 if (!empty($toprint)) {
8484 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
8485 }
8486 }
8487 } elseif ($type == 'chkbxlst') {
8488 $value_arr = (isset($value) ? explode(',', $value) : array());
8489
8490 $param_list = array_keys($param['options']);
8491 $InfoFieldList = explode(":", $param_list[0]);
8492
8493 $selectkey = "rowid";
8494 $keyList = 'rowid';
8495
8496 if (count($InfoFieldList) >= 3) {
8497 $selectkey = $InfoFieldList[2];
8498 $keyList = $InfoFieldList[2].' as rowid';
8499 }
8500
8501 $fields_label = explode('|', $InfoFieldList[1]);
8502 if (is_array($fields_label)) {
8503 $keyList .= ', ';
8504 $keyList .= implode(', ', $fields_label);
8505 }
8506
8507 $filter_categorie = false;
8508 if (count($InfoFieldList) > 5) {
8509 if ($InfoFieldList[0] == 'categorie') {
8510 $filter_categorie = true;
8511 }
8512 }
8513
8514 $sql = "SELECT ".$keyList;
8515 $sql .= ' FROM '.$this->db->prefix().$InfoFieldList[0];
8516 if (strpos($InfoFieldList[4], 'extra') !== false) {
8517 $sql .= ' as main';
8518 }
8519 // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
8520 // $sql.= ' AND entity = '.$conf->entity;
8521
8522 dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
8523 $resql = $this->db->query($sql);
8524 if ($resql) {
8525 if (!$filter_categorie) {
8526 $value = ''; // value was used, so now we reset it to use it to build final output
8527 $toprint = array();
8528 while ($obj = $this->db->fetch_object($resql)) {
8529 // Several field into label (eq table:code|libelle:rowid)
8530 $fields_label = explode('|', $InfoFieldList[1]);
8531 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8532 if (is_array($fields_label) && count($fields_label) > 1) {
8533 foreach ($fields_label as $field_toshow) {
8534 $translabel = '';
8535 if (!empty($obj->$field_toshow)) {
8536 $translabel = $langs->trans($obj->$field_toshow);
8537 }
8538 if ($translabel != $field_toshow) {
8539 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
8540 } else {
8541 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->$field_toshow . '</li>';
8542 }
8543 }
8544 } else {
8545 $translabel = '';
8546 if (!empty($obj->{$InfoFieldList[1]})) {
8547 $translabel = $langs->trans($obj->{$InfoFieldList[1]});
8548 }
8549 if ($translabel != $obj->{$InfoFieldList[1]}) {
8550 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . dol_trunc($translabel, 18) . '</li>';
8551 } else {
8552 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $obj->{$InfoFieldList[1]} . '</li>';
8553 }
8554 }
8555 }
8556 }
8557 } else {
8558 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
8559
8560 $toprint = array();
8561 while ($obj = $this->db->fetch_object($resql)) {
8562 if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
8563 $c = new Categorie($this->db);
8564 $c->fetch($obj->rowid);
8565 $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
8566 foreach ($ways as $way) {
8567 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #aaa"') . '>' . img_object('', 'category') . ' ' . $way . '</li>';
8568 }
8569 }
8570 }
8571 }
8572 $value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
8573 } else {
8574 dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
8575 }
8576 } elseif ($type == 'link') {
8577 $out = '';
8578
8579 // only if something to display (perf)
8580 if ($value) {
8581 $param_list = array_keys($param['options']);
8582 // Example: $param_list='ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
8583 // Example: $param_list='ObjectClass:PathToClass:#getnomurlparam1=-1#getnomurlparam2=customer'
8584
8585 $InfoFieldList = explode(":", $param_list[0]);
8586
8587 $classname = $InfoFieldList[0];
8588 $classpath = $InfoFieldList[1];
8589
8590 // Set $getnomurlparam1 et getnomurlparam2
8591 $getnomurlparam = 3;
8592 $getnomurlparam2 = '';
8593 $regtmp = array();
8594 if (preg_match('/#getnomurlparam1=([^#]*)/', $param_list[0], $regtmp)) {
8595 $getnomurlparam = $regtmp[1];
8596 }
8597 if (preg_match('/#getnomurlparam2=([^#]*)/', $param_list[0], $regtmp)) {
8598 $getnomurlparam2 = $regtmp[1];
8599 }
8600
8601 if (!empty($classpath)) {
8602 dol_include_once($InfoFieldList[1]);
8603
8604 if ($classname && !class_exists($classname)) {
8605 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
8606 // TODO use newObjectByElement() introduce in V20 by PR #30036 for better errors management
8607 $element_prop = getElementProperties($classname);
8608 if ($element_prop) {
8609 $classname = $element_prop['classname'];
8610 }
8611 }
8612
8613
8614 if ($classname && class_exists($classname)) {
8615 $object = new $classname($this->db);
8616 '@phan-var-force CommonObject $object';
8617 if ($object->element === 'product') { // Special case for product because default valut of fetch are wrong
8618 '@phan-var-force Product $object';
8619 $result = $object->fetch($value, '', '', '', 0, 1, 1);
8620 } else {
8621 $result = $object->fetch($value);
8622 }
8623 if ($result > 0) {
8624 if ($object->element === 'product') {
8625 '@phan-var-force Product $object';
8626 $get_name_url_param_arr = array($getnomurlparam, $getnomurlparam2, 0, -1, 0, '', 0);
8627 if (isset($val['get_name_url_params'])) {
8628 $get_name_url_params = explode(':', $val['get_name_url_params']);
8629 if (!empty($get_name_url_params)) {
8630 $param_num_max = count($get_name_url_param_arr) - 1;
8631 foreach ($get_name_url_params as $param_num => $param_value) {
8632 if ($param_num > $param_num_max) {
8633 break;
8634 }
8635 $get_name_url_param_arr[$param_num] = $param_value;
8636 }
8637 }
8638 }
8639
8643 $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]);
8644 } else {
8645 $value = $object->getNomUrl($getnomurlparam, $getnomurlparam2);
8646 }
8647 } else {
8648 $value = '';
8649 }
8650 }
8651 } else {
8652 dol_syslog('Error bad setup of extrafield', LOG_WARNING);
8653 return 'Error bad setup of extrafield';
8654 }
8655 } else {
8656 $value = '';
8657 }
8658 } elseif ($type == 'password') {
8659 $value = '<span class="opacitymedium">'.$langs->trans("Encrypted").'</span>';
8660 //$value = preg_replace('/./i', '*', $value);
8661 } elseif ($type == 'array') {
8662 if (is_array($value)) {
8663 $value = implode('<br>', $value);
8664 } else {
8665 dol_syslog(__METHOD__.' Expected array from dol_eval, but got '.gettype($value), LOG_ERR);
8666 return 'Error unexpected result from code evaluation';
8667 }
8668 } else { // text|html|varchar
8669 if (!empty($value) && preg_match('/^text/', (string) $type) && !preg_match('/search_/', $keyprefix) && !empty($param['options'])) {
8670 $value = str_replace(',', "\n", $value);
8671 }
8672 $value = dol_htmlentitiesbr($value);
8673 }
8674
8675 //print $type.'-'.$size.'-'.$value;
8676 $out = $value;
8677
8678 return is_null($out) ? '' : $out;
8679 }
8680
8687 public function clearFieldError($fieldKey)
8688 {
8689 $this->error = '';
8690 unset($this->validateFieldsErrors[$fieldKey]);
8691 }
8692
8700 public function setFieldError($fieldKey, $msg = '')
8701 {
8702 global $langs;
8703 if (empty($msg)) {
8704 $msg = $langs->trans("UnknownError");
8705 }
8706
8707 $this->error = $this->validateFieldsErrors[$fieldKey] = $msg;
8708 }
8709
8716 public function getFieldError($fieldKey)
8717 {
8718 if (!empty($this->validateFieldsErrors[$fieldKey])) {
8719 return $this->validateFieldsErrors[$fieldKey];
8720 }
8721 return '';
8722 }
8723
8732 public function validateField($fields, $fieldKey, $fieldValue)
8733 {
8734 global $langs;
8735
8736 if (!class_exists('Validate')) {
8737 require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php';
8738 }
8739
8740 $this->clearFieldError($fieldKey);
8741
8742 if (!array_key_exists($fieldKey, $fields) || !is_array($fields[$fieldKey])) {
8743 $this->setFieldError($fieldKey, $langs->trans('FieldNotFoundInObject'));
8744 return false;
8745 }
8746
8747 $val = $fields[$fieldKey];
8748
8749 $param = array();
8750 $param['options'] = array();
8751 $type = $val['type'];
8752
8753 $required = false;
8754 if (isset($val['notnull']) && $val['notnull'] === 1) {
8755 // 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
8756 $required = true;
8757 }
8758
8759 $maxSize = 0;
8760 $minSize = 0;
8761
8762 //
8763 // PREPARE Elements
8764 //
8765 $reg = array();
8766
8767 // Convert var to be able to share same code than showOutputField of extrafields
8768 if (preg_match('/varchar\‍((\d+)\‍)/', $type, $reg)) {
8769 $type = 'varchar'; // convert varchar(xx) int varchar
8770 $maxSize = $reg[1];
8771 } elseif (preg_match('/varchar/', $type)) {
8772 $type = 'varchar'; // convert varchar(xx) int varchar
8773 }
8774
8775 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8776 $type = 'select';
8777 }
8778
8779 if (!empty($val['type']) && preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8780 $type = 'link';
8781 }
8782
8783 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
8784 $param['options'] = $val['arrayofkeyval'];
8785 }
8786
8787 if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
8788 $type = 'link';
8789 $param['options'] = array($reg[1].':'.$reg[2] => $reg[1].':'.$reg[2]);
8790 } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
8791 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
8792 $type = 'sellist';
8793 } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
8794 $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
8795 $type = 'sellist';
8796 } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
8797 $param['options'] = array($reg[1].':'.$reg[2] => 'N');
8798 $type = 'sellist';
8799 }
8800
8801 //
8802 // TEST Value
8803 //
8804
8805 // Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring) or just for reuse
8806 $validate = new Validate($this->db, $langs);
8807
8808
8809 // little trick : to perform tests with good performances sort tests by quick to low
8810
8811 //
8812 // COMMON TESTS
8813 //
8814
8815 // Required test and empty value
8816 if ($required && !$validate->isNotEmptyString($fieldValue)) {
8817 $this->setFieldError($fieldKey, $validate->error);
8818 return false;
8819 } elseif (!$required && !$validate->isNotEmptyString($fieldValue)) {
8820 // if no value sent and the field is not mandatory, no need to perform tests
8821 return true;
8822 }
8823
8824 // MAX Size test
8825 if (!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)) {
8826 $this->setFieldError($fieldKey, $validate->error);
8827 return false;
8828 }
8829
8830 // MIN Size test
8831 if (!empty($minSize) && !$validate->isMinLength($fieldValue, $minSize)) {
8832 $this->setFieldError($fieldKey, $validate->error);
8833 return false;
8834 }
8835
8836 //
8837 // TESTS for TYPE
8838 //
8839
8840 if (in_array($type, array('date', 'datetime', 'timestamp'))) {
8841 if (!$validate->isTimestamp($fieldValue)) {
8842 $this->setFieldError($fieldKey, $validate->error);
8843 return false;
8844 } else {
8845 return true;
8846 }
8847 } elseif ($type == 'duration') {
8848 if (!$validate->isDuration($fieldValue)) {
8849 $this->setFieldError($fieldKey, $validate->error);
8850 return false;
8851 } else {
8852 return true;
8853 }
8854 } elseif (in_array($type, array('double', 'real', 'price'))) {
8855 // is numeric
8856 if (!$validate->isNumeric($fieldValue)) {
8857 $this->setFieldError($fieldKey, $validate->error);
8858 return false;
8859 } else {
8860 return true;
8861 }
8862 } elseif ($type == 'boolean') {
8863 if (!$validate->isBool($fieldValue)) {
8864 $this->setFieldError($fieldKey, $validate->error);
8865 return false;
8866 } else {
8867 return true;
8868 }
8869 } elseif ($type == 'mail') {
8870 if (!$validate->isEmail($fieldValue)) {
8871 $this->setFieldError($fieldKey, $validate->error);
8872 return false;
8873 }
8874 } elseif ($type == 'url') {
8875 if (!$validate->isUrl($fieldValue)) {
8876 $this->setFieldError($fieldKey, $validate->error);
8877 return false;
8878 } else {
8879 return true;
8880 }
8881 } elseif ($type == 'phone') {
8882 if (!$validate->isPhone($fieldValue)) {
8883 $this->setFieldError($fieldKey, $validate->error);
8884 return false;
8885 } else {
8886 return true;
8887 }
8888 } elseif ($type == 'select' || $type == 'radio') {
8889 if (!isset($param['options'][$fieldValue])) {
8890 $this->error = $langs->trans('RequireValidValue');
8891 return false;
8892 } else {
8893 return true;
8894 }
8895 } elseif ($type == 'sellist' || $type == 'chkbxlst') {
8896 $param_list = array_keys($param['options']);
8897 $InfoFieldList = explode(":", $param_list[0]);
8898 $value_arr = explode(',', $fieldValue);
8899 $value_arr = array_map(array($this->db, 'escape'), $value_arr);
8900
8901 $selectkey = "rowid";
8902 if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
8903 $selectkey = $InfoFieldList[2];
8904 }
8905
8906 if (!$validate->isInDb($value_arr, $InfoFieldList[0], $selectkey)) {
8907 $this->setFieldError($fieldKey, $validate->error);
8908 return false;
8909 } else {
8910 return true;
8911 }
8912 } elseif ($type == 'link') {
8913 $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
8914 $InfoFieldList = explode(":", $param_list[0]);
8915 $classname = $InfoFieldList[0];
8916 $classpath = $InfoFieldList[1];
8917 if (!$validate->isFetchable($fieldValue, $classname, $classpath)) {
8918 $lastIsFetchableError = $validate->error;
8919
8920 // from V19 of Dolibarr, In some cases link use element instead of class, example project_task
8921 if ($validate->isFetchableElement($fieldValue, $classname)) {
8922 return true;
8923 }
8924
8925 $this->setFieldError($fieldKey, $lastIsFetchableError);
8926 return false;
8927 } else {
8928 return true;
8929 }
8930 }
8931
8932 // if no test failed all is ok
8933 return true;
8934 }
8935
8949 public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = '', $display_type = 'card')
8950 {
8951 global $db, $conf, $langs, $action, $form, $hookmanager;
8952
8953 if (!is_object($form)) {
8954 $form = new Form($db);
8955 }
8956 if (!is_object($extrafields)) {
8957 dol_syslog('Bad parameter extrafields for showOptionals', LOG_ERR);
8958 return 'Bad parameter extrafields for showOptionals';
8959 }
8960 if (!is_array($extrafields->attributes[$this->table_element])) {
8961 dol_syslog("extrafields->attributes was not loaded with extrafields->fetch_name_optionals_label(table_element);", LOG_WARNING);
8962 }
8963
8964 $out = '';
8965
8966 $parameters = array('mode' => $mode, 'params' => $params, 'keysuffix' => $keysuffix, 'keyprefix' => $keyprefix, 'display_type' => $display_type);
8967 $reshook = $hookmanager->executeHooks('showOptionals', $parameters, $this, $action); // Note that $action and $object may have been modified by hook
8968
8969 if (empty($reshook)) {
8970 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) {
8971 $out .= "\n";
8972 $out .= '<!-- commonobject:showOptionals --> ';
8973 $out .= "\n";
8974
8975 $nbofextrafieldsshown = 0;
8976 $e = 0; // var to manage the modulo (odd/even)
8977
8978 $lastseparatorkeyfound = '';
8979 $extrafields_collapse_num = '';
8980 $extrafields_collapse_num_old = '';
8981 $i = 0;
8982
8983 foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $label) {
8984 $i++;
8985
8986 // Show only the key field in params @phan-suppress-next-line PhanTypeArraySuspiciousNullable
8987 if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) {
8988 continue;
8989 }
8990
8991 // Test on 'enabled' ('enabled' is different than 'list' = 'visibility')
8992 $enabled = 1;
8993 if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) {
8994 $enabled = (int) dol_eval((string) $extrafields->attributes[$this->table_element]['enabled'][$key], 1, 1, '2');
8995 }
8996 if (empty($enabled)) {
8997 continue;
8998 }
8999
9000 $visibility = 1;
9001 if (isset($extrafields->attributes[$this->table_element]['list'][$key])) {
9002 $visibility = (int) dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1, 1, '2');
9003 }
9004
9005 $perms = 1;
9006 if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) {
9007 $perms = (int) dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1, 1, '2');
9008 }
9009
9010 if (($mode == 'create') && !in_array(abs($visibility), array(1, 3))) {
9011 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
9012 } elseif (($mode == 'edit') && !in_array(abs($visibility), array(1, 3, 4))) {
9013 continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list and <> 4 = not visible at the creation
9014 } elseif ($mode == 'view' && empty($visibility)) {
9015 continue;
9016 }
9017 if (empty($perms)) {
9018 continue;
9019 }
9020
9021 // Load language if required
9022 if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
9023 $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
9024 }
9025
9026 $colspan = 0;
9027 $value = null;
9028 if (is_array($params) && count($params) > 0 && $display_type == 'card') {
9029 if (array_key_exists('cols', $params)) {
9030 $colspan = $params['cols'];
9031 } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now.
9032 $reg = array();
9033 if (preg_match('/colspan="(\d+)"/', $params['colspan'], $reg)) {
9034 $colspan = $reg[1];
9035 } else {
9036 $colspan = $params['colspan'];
9037 }
9038 }
9039 }
9040 $colspan = intval($colspan);
9041
9042 switch ($mode) {
9043 case "view":
9044 $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
9045 break;
9046 case "create":
9047 case "edit":
9048 // We get the value of property found with GETPOST so it takes into account:
9049 // default values overwrite, restore back to list link, ... (but not 'default value in database' of field)
9050 $check = 'alphanohtml';
9051 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text'))) {
9052 $check = 'restricthtml';
9053 }
9054 $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, $check, 3); // GETPOST can get value from GET, POST or setup of default values overwrite.
9055 // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
9056 if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) {
9057 if (is_array($getposttemp)) {
9058 // $getposttemp is an array but following code expects a comma separated string
9059 $value = implode(",", $getposttemp);
9060 } else {
9061 $value = $getposttemp;
9062 }
9063 } elseif (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('int'))) {
9064 $value = (!empty($this->array_options["options_".$key]) || (isset($this->array_options["options_".$key]) && $this->array_options["options_".$key] === '0')) ? $this->array_options["options_".$key] : '';
9065 } else {
9066 $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.
9067 }
9068 //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
9069 break;
9070 }
9071
9072 $nbofextrafieldsshown++;
9073
9074 // Output value of the current field
9075 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') {
9076 $extrafields_collapse_num = $key;
9077 /*
9078 $extrafield_param = $extrafields->attributes[$this->table_element]['param'][$key];
9079 if (!empty($extrafield_param) && is_array($extrafield_param)) {
9080 $extrafield_param_list = array_keys($extrafield_param['options']);
9081
9082 if (count($extrafield_param_list) > 0) {
9083 $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
9084
9085 if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
9086 //$extrafields_collapse_num = $extrafields->attributes[$this->table_element]['pos'][$key];
9087 $extrafields_collapse_num = $key;
9088 }
9089 }
9090 }
9091 */
9092
9093 // if colspan=0 or 1, the second column is not extended, so the separator must be on 2 columns
9094 $out .= $extrafields->showSeparator($key, $this, ($colspan ? $colspan + 1 : 2), $display_type, $mode);
9095
9096 $lastseparatorkeyfound = $key;
9097 } else {
9098 $collapse_group = $extrafields_collapse_num.(!empty($this->id) ? '_'.$this->id : '');
9099
9100 $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
9101 $csstyle = '';
9102 if (is_array($params) && count($params) > 0) {
9103 if (array_key_exists('class', $params)) {
9104 $class .= $params['class'].' ';
9105 }
9106 if (array_key_exists('style', $params)) {
9107 $csstyle = $params['style'];
9108 }
9109 }
9110
9111 // add html5 elements
9112 $domData = ' data-element="extrafield"';
9113 $domData .= ' data-targetelement="'.$this->element.'"';
9114 $domData .= ' data-targetid="'.$this->id.'"';
9115
9116 $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id);
9117 if ($display_type == 'card') {
9118 if (getDolGlobalString('MAIN_EXTRAFIELDS_USE_TWO_COLUMS') && ($e % 2) == 0) {
9119 $colspan = 0;
9120 }
9121
9122 if ($action == 'selectlines') {
9123 $colspan++;
9124 }
9125 }
9126
9127 // Convert date into timestamp format (value in memory must be a timestamp)
9128 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date'))) {
9129 $datenotinstring = null;
9130 if (array_key_exists('options_'.$key, $this->array_options)) {
9131 $datenotinstring = $this->array_options['options_'.$key];
9132 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
9133 $datenotinstring = $this->db->jdate($datenotinstring);
9134 }
9135 }
9136 $datekey = $keyprefix.'options_'.$key.$keysuffix;
9137 $value = (GETPOSTISSET($datekey)) ? dol_mktime(12, 0, 0, GETPOSTINT($datekey.'month', 3), GETPOSTINT($datekey.'day', 3), GETPOSTINT($datekey.'year', 3)) : $datenotinstring;
9138 }
9139 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('datetime'))) {
9140 $datenotinstring = null;
9141 if (array_key_exists('options_'.$key, $this->array_options)) {
9142 $datenotinstring = $this->array_options['options_'.$key];
9143 if (!is_numeric($this->array_options['options_'.$key])) { // For backward compatibility
9144 $datenotinstring = $this->db->jdate($datenotinstring);
9145 }
9146 }
9147 $timekey = $keyprefix.'options_'.$key.$keysuffix;
9148 $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;
9149 }
9150 // Convert float submitted string into real php numeric (value in memory must be a php numeric)
9151 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double'))) {
9152 if (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) {
9153 $value = price2num($value);
9154 } elseif (isset($this->array_options['options_'.$key])) {
9155 $value = $this->array_options['options_'.$key];
9156 }
9157 }
9158
9159 // HTML, text, select, integer and varchar: take into account default value in database if in create mode
9160 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('html', 'text', 'varchar', 'select', 'radio', 'int', 'boolean'))) {
9161 if ($action == 'create' || $mode == 'create') {
9162 $value = (GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) || $value) ? $value : $extrafields->attributes[$this->table_element]['default'][$key];
9163 }
9164 }
9165
9166 $labeltoshow = $langs->trans($label);
9167 $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]);
9168 if ($display_type == 'card') {
9169 $out .= '<tr '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="field_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9170 if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER') && ($action == 'view' || $action == 'valid' || $action == 'editline' || $action == 'confirm_valid' || $action == 'confirm_cancel')) {
9171 $out .= '<td></td>';
9172 }
9173 $out .= '<td class="'.(empty($params['tdclass']) ? 'titlefieldmax45' : $params['tdclass']).' wordbreak';
9174 if ($extrafields->attributes[$this->table_element]['type'][$key] == 'text') {
9175 $out .= ' tdtop';
9176 }
9177 } elseif ($display_type == 'line') {
9178 $out .= '<div '.($html_id ? 'id="'.$html_id.'" ' : '').$csstyle.' class="fieldline_options_'.$key.' '.$class.$this->element.'_extras_'.$key.' trextrafields_collapse'.$collapse_group.'" '.$domData.' >';
9179 $out .= '<div style="display: inline-block; padding-right:4px" class="wordbreak';
9180 }
9181 //$out .= "titlefield";
9182 //if (GETPOST('action', 'restricthtml') == 'create') $out.='create';
9183 // BUG #11554 : For public page, use red dot for required fields, instead of bold label
9184 $tpl_context = isset($params["tpl_context"]) ? $params["tpl_context"] : "none";
9185 if ($tpl_context != "public") { // Public page : red dot instead of fieldrequired characters
9186 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9187 $out .= ' fieldrequired';
9188 }
9189 }
9190 $out .= '">';
9191 if ($tpl_context == "public") { // Public page : red dot instead of fieldrequired characters
9192 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9193 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9194 } else {
9195 $out .= $labeltoshow;
9196 }
9197 if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) {
9198 $out .= '&nbsp;<span style="color: red">*</span>';
9199 }
9200 } else {
9201 if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) {
9202 $out .= $form->textwithpicto($labeltoshow, $helptoshow);
9203 } else {
9204 $out .= $labeltoshow;
9205 }
9206 }
9207
9208 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9209
9210 // Second column
9211 $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
9212 if ($display_type == 'card') {
9213 // 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
9214 $out .= '<td '.($html_id ? 'id="'.$html_id.'" ' : '').' class="valuefieldcreate '.$this->element.'_extras_'.$key;
9215 $out .= '" '.($colspan ? ' colspan="'.$colspan.'"' : '');
9216 $out .= '>';
9217 } elseif ($display_type == 'line') {
9218 $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].'">';
9219 }
9220
9221 switch ($mode) {
9222 case "view":
9223 $out .= $extrafields->showOutputField($key, $value, '', $this->table_element);
9224 break;
9225 case "create":
9226 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICOT', 'email,phone,ip,password'));
9227 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9228 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9229 }
9230 //$out .= '<!-- type = '.$extrafields->attributes[$this->table_element]['type'][$key].' -->';
9231 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
9232 break;
9233 case "edit":
9234 $listoftypestoshowpicto = explode(',', getDolGlobalString('MAIN_TYPES_TO_SHOW_PICOT', 'email,phone,ip,password'));
9235 if (in_array($extrafields->attributes[$this->table_element]['type'][$key], $listoftypestoshowpicto)) {
9236 $out .= getPictoForType($extrafields->attributes[$this->table_element]['type'][$key], ($extrafields->attributes[$this->table_element]['type'][$key] == 'text' ? 'tdtop' : ''));
9237 }
9238 $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id, $this->table_element);
9239 break;
9240 }
9241
9242 $out .= ($display_type == 'card' ? '</td>' : '</div>');
9243 $out .= ($display_type == 'card' ? '</tr>'."\n" : '</div>');
9244 $e++;
9245 }
9246 }
9247 $out .= "\n";
9248 // Add code to manage list depending on others
9249 if (!empty($conf->use_javascript_ajax)) {
9250 $out .= $this->getJSListDependancies();
9251 }
9252
9253 $out .= '<!-- commonobject:showOptionals end --> '."\n";
9254
9255 if (empty($nbofextrafieldsshown)) {
9256 $out = '';
9257 }
9258 }
9259 }
9260
9261 $out .= $hookmanager->resPrint;
9262
9263 return $out;
9264 }
9265
9270 public function getJSListDependancies($type = '_extra')
9271 {
9272 $out = '
9273 <script nonce="'.getNonce().'">
9274 jQuery(document).ready(function() {
9275 function showOptions'.$type.'(child_list, parent_list, orig_select)
9276 {
9277 var val = $("select[name=\""+parent_list+"\"]").val();
9278 var parentVal = parent_list + ":" + val;
9279 if(typeof val == "string"){
9280 if(val != "") {
9281 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9282 $("select[name=\""+child_list+"\"] option[parent]").remove();
9283 $("select[name=\""+child_list+"\"]").append(options);
9284 } else {
9285 var options = orig_select.find("option[parent]").clone();
9286 $("select[name=\""+child_list+"\"] option[parent]").remove();
9287 $("select[name=\""+child_list+"\"]").append(options);
9288 }
9289 } else if(val > 0) {
9290 var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone();
9291 $("select[name=\""+child_list+"\"] option[parent]").remove();
9292 $("select[name=\""+child_list+"\"]").append(options);
9293 } else {
9294 var options = orig_select.find("option[parent]").clone();
9295 $("select[name=\""+child_list+"\"] option[parent]").remove();
9296 $("select[name=\""+child_list+"\"]").append(options);
9297 }
9298 }
9299 function setListDependencies'.$type.'() {
9300 jQuery("select option[parent]").parent().each(function() {
9301 var orig_select = {};
9302 var child_list = $(this).attr("name");
9303 orig_select[child_list] = $(this).clone();
9304 var parent = $(this).find("option[parent]:first").attr("parent");
9305 var infos = parent.split(":");
9306 var parent_list = infos[0];
9307
9308 //Hide daughters lists
9309 if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){
9310 $("#"+child_list).hide();
9311 //Show mother lists
9312 } else if ($("#"+parent_list).val() != 0){
9313 $("#"+parent_list).show();
9314 }
9315 //Show the child list if the parent list value is selected
9316 $("select[name=\""+parent_list+"\"]").click(function() {
9317 if ($(this).val() != 0){
9318 $("#"+child_list).show()
9319 }
9320 });
9321
9322 //When we change parent list
9323 $("select[name=\""+parent_list+"\"]").change(function() {
9324 showOptions'.$type.'(child_list, parent_list, orig_select[child_list]);
9325 //Select the value 0 on child list after a change on the parent list
9326 $("#"+child_list).val(0).trigger("change");
9327 //Hide child lists if the parent value is set to 0
9328 if ($(this).val() == 0){
9329 $("#"+child_list).hide();
9330 }
9331 });
9332 });
9333 }
9334
9335 setListDependencies'.$type.'();
9336 });
9337 </script>'."\n";
9338 return $out;
9339 }
9340
9346 public function getRights()
9347 {
9348 global $user;
9349
9350 $module = empty($this->module) ? '' : $this->module;
9351 $element = $this->element;
9352
9353 if ($element == 'facturerec') {
9354 $element = 'facture';
9355 } elseif ($element == 'invoice_supplier_rec') {
9356 return !$user->hasRight('fournisseur', 'facture') ? null : $user->hasRight('fournisseur', 'facture');
9357 } elseif ($module && $user->hasRight($module, $element)) {
9358 // for modules built with ModuleBuilder
9359 return $user->hasRight($module, $element);
9360 }
9361
9362 return $user->rights->$element;
9363 }
9364
9377 public static function commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
9378 {
9379 global $hookmanager;
9380
9381 $parameters = array(
9382 'origin_id' => $origin_id,
9383 'dest_id' => $dest_id,
9384 'tables' => $tables,
9385 );
9386 $reshook = $hookmanager->executeHooks('commonReplaceThirdparty', $parameters);
9387 if ($reshook) {
9388 return true; // replacement code
9389 } elseif ($reshook < 0) {
9390 return $ignoreerrors === 1; // failure
9391 } // reshook = 0 => execute normal code
9392
9393 foreach ($tables as $table) {
9394 $sql = 'UPDATE '.$dbs->prefix().$table.' SET fk_soc = '.((int) $dest_id).' WHERE fk_soc = '.((int) $origin_id);
9395
9396 if (!$dbs->query($sql)) {
9397 if ($ignoreerrors) {
9398 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.
9399 }
9400 //$this->errors = $db->lasterror();
9401 return false;
9402 }
9403 }
9404
9405 return true;
9406 }
9407
9420 public static function commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
9421 {
9422 foreach ($tables as $table) {
9423 $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_product = '.((int) $dest_id).' WHERE fk_product = '.((int) $origin_id);
9424
9425 if (!$dbs->query($sql)) {
9426 if ($ignoreerrors) {
9427 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.
9428 }
9429 //$this->errors = $db->lasterror();
9430 return false;
9431 }
9432 }
9433
9434 return true;
9435 }
9436
9449 public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
9450 {
9451 global $conf;
9452
9453 $buyPrice = 0;
9454
9455 if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && getDolGlobalInt('ForceBuyingPriceIfNull') > 0)) {
9456 // When ForceBuyingPriceIfNull is set
9457 $buyPrice = $unitPrice * (1 - $discountPercent / 100);
9458 } else {
9459 // Get cost price for margin calculation
9460 if (!empty($fk_product) && $fk_product > 0) {
9461 $result = 0;
9462 if (getDolGlobalString('MARGIN_TYPE') == 'costprice') {
9463 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
9464 $product = new Product($this->db);
9465 $result = $product->fetch($fk_product);
9466 if ($result <= 0) {
9467 $this->errors[] = 'ErrorProductIdDoesNotExists';
9468 return -1;
9469 }
9470 if ($product->cost_price > 0) {
9471 $buyPrice = $product->cost_price;
9472 } elseif ($product->pmp > 0) {
9473 $buyPrice = $product->pmp;
9474 }
9475 } elseif (getDolGlobalString('MARGIN_TYPE') == 'pmp') {
9476 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
9477 $product = new Product($this->db);
9478 $result = $product->fetch($fk_product);
9479 if ($result <= 0) {
9480 $this->errors[] = 'ErrorProductIdDoesNotExists';
9481 return -1;
9482 }
9483 if ($product->pmp > 0) {
9484 $buyPrice = $product->pmp;
9485 }
9486 }
9487
9488 if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
9489 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
9490 $productFournisseur = new ProductFournisseur($this->db);
9491 if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0) {
9492 $buyPrice = $productFournisseur->fourn_unitprice;
9493 } elseif ($result < 0) {
9494 $this->errors[] = $productFournisseur->error;
9495 return -2;
9496 }
9497 }
9498 }
9499 }
9500 return $buyPrice;
9501 }
9502
9510 public function getDataToShowPhoto($modulepart, $imagesize)
9511 {
9512 // See getDataToShowPhoto() implemented by Product for example.
9513 return array('dir' => '', 'file' => '', 'originalfile' => '', 'altfile' => '', 'email' => '', 'capture' => '');
9514 }
9515
9516
9517 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
9537 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')
9538 {
9539 // phpcs:enable
9540 global $user, $langs;
9541
9542 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
9543 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
9544
9545 $sortfield = 'position_name';
9546 $sortorder = 'asc';
9547
9548 $dir = $sdir.'/';
9549 $pdir = '/';
9550
9551 $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
9552 $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart);
9553
9554 // For backward compatibility
9555 if ($modulepart == 'product') {
9556 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
9557 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9558 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9559 }
9560 }
9561 if ($modulepart == 'category') {
9562 $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9563 $pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
9564 }
9565
9566 // Defined relative dir to DOL_DATA_ROOT
9567 $relativedir = '';
9568 if ($dir) {
9569 $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
9570 $relativedir = preg_replace('/^[\\/]/', '', $relativedir);
9571 $relativedir = preg_replace('/[\\/]$/', '', $relativedir);
9572 }
9573
9574 $dirthumb = $dir.'thumbs/';
9575 $pdirthumb = $pdir.'thumbs/';
9576
9577 $return = '<!-- Photo -->'."\n";
9578 $nbphoto = 0;
9579
9580 $filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
9581
9582 /*if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) // For backward compatibility, we scan also old dirs
9583 {
9584 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
9585 $filearray=array_merge($filearray, $filearrayold);
9586 }*/
9587
9588 completeFileArrayWithDatabaseInfo($filearray, $relativedir);
9589
9590 if (count($filearray)) {
9591 if ($sortfield && $sortorder) {
9592 $filearray = dol_sort_array($filearray, $sortfield, $sortorder);
9593 }
9594
9595 foreach ($filearray as $key => $val) {
9596 $photo = '';
9597 $file = $val['name'];
9598
9599 //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
9600 if (image_format_supported($file) >= 0) {
9601 $nbphoto++;
9602 $photo = $file;
9603 $viewfilename = $file;
9604
9605 if ($size == 1 || $size == 'small') { // Format vignette
9606 // Find name of thumb file
9607 $photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
9608 if (!dol_is_file($dirthumb.$photo_vignette)) {
9609 // The thumb does not exists, so we will use the original file
9610 $dirthumb = $dir;
9611 $pdirthumb = $pdir;
9612 $photo_vignette = basename($file);
9613 }
9614
9615 // Get filesize of original file
9616 $imgarray = dol_getImageSize($dir.$photo);
9617
9618 if ($nbbyrow > 0) {
9619 if ($nbphoto == 1) {
9620 $return .= '<table class="valigntop center centpercent" style="border: 0; padding: 2px; border-spacing: 2px; border-collapse: separate;">';
9621 }
9622
9623 if ($nbphoto % $nbbyrow == 1) {
9624 $return .= '<tr class="center valignmiddle" style="border: 1px">';
9625 }
9626 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%" class="photo">'."\n";
9627 } elseif ($nbbyrow < 0) {
9628 $return .= '<div class="inline-block">'."\n";
9629 }
9630
9631 $relativefile = preg_replace('/^\//', '', $pdir.$photo);
9632 if (empty($nolink)) {
9633 $urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
9634 if ($urladvanced) {
9635 $return .= '<a href="'.$urladvanced.'">';
9636 } else {
9637 $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank" rel="noopener noreferrer">';
9638 }
9639 }
9640
9641 // Show image (width height=$maxHeight)
9642 // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
9643 $alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
9644 $alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
9645 if ($overwritetitle) {
9646 if (is_numeric($overwritetitle)) {
9647 $alt = '';
9648 } else {
9649 $alt = $overwritetitle;
9650 }
9651 }
9652 if (empty($cache) && !empty($val['label'])) {
9653 // label is md5 of file
9654 // use it in url to say we want to cache this version of the file
9655 $cache = $val['label'];
9656 }
9657 if ($usesharelink) {
9658 if (array_key_exists('share', $val) && $val['share']) {
9659 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
9660 $return .= '<!-- Show original file (thumb not yet available with shared links) -->';
9661 $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).'">';
9662 } else {
9663 $return .= '<!-- Show original file -->';
9664 $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).'">';
9665 }
9666 } else {
9667 $return .= '<!-- Show nophoto file (because file is not shared) -->';
9668 $return .= '<img class="photo photowithmargin'.($addphotorefcss ? ' '.$addphotorefcss : '').'" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
9669 }
9670 } else {
9671 if (empty($maxHeight) || ($photo_vignette && $imgarray['height'] > $maxHeight)) {
9672 $return .= '<!-- Show thumb -->';
9673 $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).'">';
9674 } else {
9675 $return .= '<!-- Show original file -->';
9676 $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).'">';
9677 }
9678 }
9679
9680 if (empty($nolink)) {
9681 $return .= '</a>';
9682 }
9683
9684 if ($showfilename) {
9685 $return .= '<br>'.$viewfilename;
9686 }
9687 if ($showaction) {
9688 $return .= '<br>';
9689 // If $photo_vignette set, we add a link to generate thumbs if file is an image and width or height higher than limits
9690 if ($photo_vignette && (image_format_supported($photo) > 0) && ((isset($imgarray['width']) && $imgarray['width'] > $maxWidth) || (isset($imgarray['width']) && $imgarray['width'] > $maxHeight))) {
9691 $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>';
9692 }
9693 // Special case for product
9694 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
9695 // Link to resize
9696 $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; ';
9697
9698 // Link to delete
9699 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
9700 $return .= img_delete().'</a>';
9701 }
9702 }
9703 $return .= "\n";
9704
9705 if ($nbbyrow > 0) {
9706 $return .= '</td>';
9707 if (($nbphoto % $nbbyrow) == 0) {
9708 $return .= '</tr>';
9709 }
9710 } elseif ($nbbyrow < 0) {
9711 $return .= '</div>'."\n";
9712 }
9713 }
9714
9715 if (empty($size)) { // Format origine
9716 $return .= '<img class="photo photowithmargin" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
9717
9718 if ($showfilename) {
9719 $return .= '<br>'.$viewfilename;
9720 }
9721 if ($showaction) {
9722 // Special case for product
9723 if ($modulepart == 'product' && ($user->hasRight('produit', 'creer') || $user->hasRight('service', 'creer'))) {
9724 // Link to resize
9725 $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; ';
9726
9727 // Link to delete
9728 $return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&action=delete&token='.newToken().'&file='.urlencode($pdir.$viewfilename).'">';
9729 $return .= img_delete().'</a>';
9730 }
9731 }
9732 }
9733
9734 // On continue ou on arrete de boucler ?
9735 if ($nbmax && $nbphoto >= $nbmax) {
9736 break;
9737 }
9738 }
9739 }
9740
9741 if ($size == 1 || $size == 'small') {
9742 if ($nbbyrow > 0) {
9743 // Ferme tableau
9744 while ($nbphoto % $nbbyrow) {
9745 $return .= '<td style="width: '.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
9746 $nbphoto++;
9747 }
9748
9749 if ($nbphoto) {
9750 $return .= '</table>';
9751 }
9752 }
9753 }
9754 }
9755
9756 $this->nbphoto = $nbphoto;
9757
9758 return $return;
9759 }
9760
9761
9768 protected function isArray($info)
9769 {
9770 if (is_array($info)) {
9771 if (isset($info['type']) && $info['type'] == 'array') {
9772 return true;
9773 } else {
9774 return false;
9775 }
9776 }
9777 return false;
9778 }
9779
9786 public function isDate($info)
9787 {
9788 if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) {
9789 return true;
9790 }
9791 return false;
9792 }
9793
9800 public function isDuration($info)
9801 {
9802 if (is_array($info)) {
9803 if (isset($info['type']) && ($info['type'] == 'duration')) {
9804 return true;
9805 } else {
9806 return false;
9807 }
9808 } else {
9809 return false;
9810 }
9811 }
9812
9819 public function isInt($info)
9820 {
9821 if (is_array($info)) {
9822 if (isset($info['type']) && (preg_match('/(^int|int$)/i', $info['type']))) {
9823 return true;
9824 } else {
9825 return false;
9826 }
9827 } else {
9828 return false;
9829 }
9830 }
9831
9838 public function isFloat($info)
9839 {
9840 if (is_array($info)) {
9841 if (isset($info['type']) && (preg_match('/^(double|real|price)/i', $info['type']))) {
9842 return true;
9843 } else {
9844 return false;
9845 }
9846 }
9847 return false;
9848 }
9849
9856 public function isText($info)
9857 {
9858 if (is_array($info)) {
9859 if (isset($info['type']) && $info['type'] == 'text') {
9860 return true;
9861 } else {
9862 return false;
9863 }
9864 }
9865 return false;
9866 }
9867
9874 protected function canBeNull($info)
9875 {
9876 if (is_array($info)) {
9877 if (array_key_exists('notnull', $info) && $info['notnull'] != '1') {
9878 return true;
9879 } else {
9880 return false;
9881 }
9882 }
9883 return true;
9884 }
9885
9892 protected function isForcedToNullIfZero($info)
9893 {
9894 if (is_array($info)) {
9895 if (array_key_exists('notnull', $info) && $info['notnull'] == '-1') {
9896 return true;
9897 } else {
9898 return false;
9899 }
9900 }
9901 return false;
9902 }
9903
9910 protected function isIndex($info)
9911 {
9912 if (is_array($info)) {
9913 if (array_key_exists('index', $info) && $info['index'] == true) {
9914 return true;
9915 } else {
9916 return false;
9917 }
9918 }
9919 return false;
9920 }
9921
9922
9931 protected function setSaveQuery()
9932 {
9933 global $conf;
9934
9935 $queryarray = array();
9936 foreach ($this->fields as $field => $info) { // Loop on definition of fields
9937 // Depending on field type ('datetime', ...)
9938 if ($this->isDate($info)) {
9939 if (empty($this->{$field})) {
9940 $queryarray[$field] = null;
9941 } else {
9942 $queryarray[$field] = $this->db->idate($this->{$field});
9943 }
9944 } elseif ($this->isDuration($info)) {
9945 // $this->{$field} may be null, '', 0, '0', 123, '123'
9946 if ((isset($this->{$field}) && $this->{$field} != '') || !empty($info['notnull'])) {
9947 if (!isset($this->{$field})) {
9948 if (!empty($info['default'])) {
9949 $queryarray[$field] = $info['default'];
9950 } else {
9951 $queryarray[$field] = 0;
9952 }
9953 } else {
9954 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9955 }
9956 } else {
9957 $queryarray[$field] = null;
9958 }
9959 } elseif ($this->isInt($info) || $this->isFloat($info)) {
9960 if ($field == 'entity' && is_null($this->{$field})) {
9961 $queryarray[$field] = ((int) $conf->entity);
9962 } else {
9963 // $this->{$field} may be null, '', 0, '0', 123, '123'
9964 if ((isset($this->{$field}) && ((string) $this->{$field}) != '') || !empty($info['notnull'])) {
9965 if (!isset($this->{$field})) {
9966 $queryarray[$field] = 0;
9967 } elseif ($this->isInt($info)) {
9968 $queryarray[$field] = (int) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9969 } elseif ($this->isFloat($info)) {
9970 $queryarray[$field] = (float) $this->{$field}; // If '0', it may be set to null later if $info['notnull'] == -1
9971 }
9972 } else {
9973 $queryarray[$field] = null;
9974 }
9975 }
9976 } else {
9977 // Note: If $this->{$field} is not defined, it means there is a bug into definition of ->fields or a missing declaration of property
9978 // We should keep the warning generated by this because it is a bug somewhere else in code, not here.
9979 $queryarray[$field] = $this->{$field};
9980 }
9981
9982 if (array_key_exists('type', $info) && $info['type'] == 'timestamp' && empty($queryarray[$field])) {
9983 unset($queryarray[$field]);
9984 }
9985 if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
9986 $queryarray[$field] = null; // May force 0 to null
9987 }
9988 }
9989
9990 return $queryarray;
9991 }
9992
9999 public function setVarsFromFetchObj(&$obj)
10000 {
10001 global $db;
10002
10003 foreach ($this->fields as $field => $info) {
10004 if ($this->isDate($info)) {
10005 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') {
10006 $this->$field = '';
10007 } else {
10008 $this->$field = $db->jdate($obj->$field);
10009 }
10010 } elseif ($this->isInt($info)) {
10011 if ($field == 'rowid') {
10012 $this->id = (int) $obj->$field;
10013 } else {
10014 if ($this->isForcedToNullIfZero($info)) {
10015 if (empty($obj->$field)) {
10016 $this->$field = null;
10017 } else {
10018 $this->$field = (int) $obj->$field;
10019 }
10020 } else {
10021 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
10022 $this->$field = (int) $obj->$field;
10023 } else {
10024 $this->$field = null;
10025 }
10026 }
10027 }
10028 } elseif ($this->isFloat($info)) {
10029 if ($this->isForcedToNullIfZero($info)) {
10030 if (empty($obj->$field)) {
10031 $this->$field = null;
10032 } else {
10033 $this->$field = (float) $obj->$field;
10034 }
10035 } else {
10036 if (isset($obj->$field) && (!is_null($obj->$field) || (array_key_exists('notnull', $info) && $info['notnull'] == 1))) {
10037 $this->$field = (float) $obj->$field;
10038 } else {
10039 $this->$field = null;
10040 }
10041 }
10042 } else {
10043 $this->$field = isset($obj->$field) ? $obj->$field : null;
10044 }
10045 }
10046
10047 // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
10048 if (!isset($this->fields['ref']) && isset($this->id)) {
10049 $this->ref = (string) $this->id;
10050 }
10051 }
10052
10057 public function emtpyObjectVars()
10058 {
10059 foreach ($this->fields as $field => $arr) {
10060 $this->$field = null;
10061 }
10062 }
10063
10071 public function getFieldList($alias = '', $excludefields = array())
10072 {
10073 $keys = array_keys($this->fields);
10074 if (!empty($alias)) {
10075 $keys_with_alias = array();
10076 foreach ($keys as $fieldname) {
10077 if (!empty($excludefields)) {
10078 if (in_array($fieldname, $excludefields)) { // The field is excluded and must not be in output
10079 continue;
10080 }
10081 }
10082 $keys_with_alias[] = $alias . '.' . $fieldname;
10083 }
10084 return implode(',', $keys_with_alias);
10085 } else {
10086 return implode(',', $keys);
10087 }
10088 }
10089
10097 protected function quote($value, $fieldsentry)
10098 {
10099 if (is_null($value)) {
10100 return 'NULL';
10101 } elseif (preg_match('/^(int|double|real|price)/i', $fieldsentry['type'])) {
10102 return price2num((string) $value);
10103 } elseif (preg_match('/int$/i', $fieldsentry['type'])) {
10104 return (int) $value;
10105 } elseif ($fieldsentry['type'] == 'boolean') {
10106 if ($value) {
10107 return 'true';
10108 } else {
10109 return 'false';
10110 }
10111 } else {
10112 return "'".$this->db->escape($value)."'";
10113 }
10114 }
10115
10116
10124 public function createCommon(User $user, $notrigger = 0)
10125 {
10126 global $langs;
10127
10128 dol_syslog(get_class($this)."::createCommon create", LOG_DEBUG);
10129
10130 $error = 0;
10131
10132 $now = dol_now();
10133
10134 $fieldvalues = $this->setSaveQuery();
10135
10136 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
10137
10138 if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
10139 $fieldvalues['date_creation'] = $this->db->idate($now);
10140 }
10141 if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) {
10142 $fieldvalues['fk_user_creat'] = $user->id;
10143 $this->fk_user_creat = $user->id;
10144 }
10145 if (array_key_exists('user_creation_id', $fieldvalues) && !($fieldvalues['user_creation_id'] > 0)) {
10146 $fieldvalues['user_creation_id'] = $user->id;
10147 $this->user_creation_id = $user->id;
10148 }
10149 if (array_key_exists('pass_crypted', $fieldvalues) && property_exists($this, 'pass')) {
10150 // @phan-suppress-next-line PhanUndeclaredProperty
10151 $fieldvalues['pass_crypted'] = dol_hash($this->pass);
10152 }
10153 if (array_key_exists('ref', $fieldvalues)) {
10154 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
10155 }
10156
10157 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
10158
10159 $keys = array();
10160 $values = array(); // Array to store string forged for SQL syntax
10161 foreach ($fieldvalues as $k => $v) {
10162 $keys[$k] = $k;
10163 $value = $this->fields[$k];
10164 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10165 $values[$k] = $this->quote($v, $value); // May return string 'NULL' if $value is null
10166 }
10167
10168 // Clean and check mandatory
10169 foreach ($keys as $key) {
10170 if (!isset($this->fields[$key])) {
10171 continue;
10172 }
10173 $key_fields = $this->fields[$key];
10174
10175 // If field is an implicit foreign key field (so type = 'integer:...')
10176 if (preg_match('/^integer:/i', $key_fields['type']) && $values[$key] == '-1') {
10177 $values[$key] = '';
10178 }
10179 if (!empty($key_fields['foreignkey']) && $values[$key] == '-1') {
10180 $values[$key] = '';
10181 }
10182
10183 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && (!isset($key_fields['default']) || is_null($key_fields['default']))) {
10184 $error++;
10185 $langs->load("errors");
10186 dol_syslog("Mandatory field '".$key."' is empty and required into ->fields definition of class");
10187 $this->errors[] = $langs->trans("ErrorFieldRequired", isset($key_fields['label']) ? $key_fields['label'] : $key);
10188 }
10189
10190 // If value is null and there is a default value for field @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10191 if (isset($key_fields['notnull']) && $key_fields['notnull'] == 1 && (!isset($values[$key]) || $values[$key] === 'NULL') && !is_null($key_fields['default'])) {
10192 $values[$key] = $this->quote($key_fields['default'], $key_fields);
10193 }
10194
10195 // If field is an implicit foreign key field (so type = 'integer:...')
10196 if (isset($key_fields['type']) && preg_match('/^integer:/i', $key_fields['type']) && empty($values[$key])) {
10197 if (isset($key_fields['default'])) {
10198 $values[$key] = ((int) $key_fields['default']);
10199 } else {
10200 $values[$key] = 'null';
10201 }
10202 }
10203 if (!empty($key_fields['foreignkey']) && empty($values[$key])) {
10204 $values[$key] = 'null';
10205 }
10206 }
10207
10208 if ($error) {
10209 return -1;
10210 }
10211
10212 $this->db->begin();
10213
10214 if (!$error) {
10215 $sql = "INSERT INTO ".$this->db->prefix().$this->table_element;
10216 $sql .= " (".implode(", ", $keys).')';
10217 $sql .= " VALUES (".implode(", ", $values).")"; // $values can contains 'abc' or 123
10218
10219 $res = $this->db->query($sql);
10220 if (!$res) {
10221 $error++;
10222 if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
10223 $this->errors[] = "ErrorRefAlreadyExists";
10224 } else {
10225 $this->errors[] = $this->db->lasterror();
10226 }
10227 }
10228 }
10229
10230 if (!$error) {
10231 $this->id = $this->db->last_insert_id($this->db->prefix().$this->table_element);
10232 }
10233
10234 // If we have a field ref with a default value of (PROV)
10235 if (!$error) {
10236 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10237 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)') {
10238 $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ref = '(PROV".((int) $this->id).")' WHERE (ref = '(PROV)' OR ref = '') AND rowid = ".((int) $this->id);
10239 $resqlupdate = $this->db->query($sql);
10240
10241 if ($resqlupdate === false) {
10242 $error++;
10243 $this->errors[] = $this->db->lasterror();
10244 } else {
10245 $this->ref = '(PROV'.$this->id.')';
10246 }
10247 }
10248 }
10249
10250 // Create extrafields
10251 if (!$error) {
10252 $result = $this->insertExtraFields();
10253 if ($result < 0) {
10254 $error++;
10255 }
10256 }
10257
10258 // Create lines
10259 if (!empty($this->table_element_line) && !empty($this->fk_element)) {
10260 foreach ($this->lines as $line) {
10261 $keyforparent = $this->fk_element;
10262 $line->$keyforparent = $this->id;
10263
10264 // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
10265 //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
10266 if (!is_object($line)) {
10267 $line = (object) $line;
10268 }
10269
10270 $result = 0;
10271 if (method_exists($line, 'insert')) {
10272 $result = $line->insert($user, 1);
10273 } elseif (method_exists($line, 'create')) {
10274 $result = $line->create($user, 1);
10275 }
10276 if ($result < 0) {
10277 $this->error = $line->error;
10278 $this->db->rollback();
10279 return -1;
10280 }
10281 }
10282 }
10283
10284 // Triggers
10285 if (!$error && !$notrigger) {
10286 // Call triggers
10287 $result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
10288 if ($result < 0) {
10289 $error++;
10290 }
10291 // End call triggers
10292 }
10293
10294 // Commit or rollback
10295 if ($error) {
10296 $this->db->rollback();
10297 return -1;
10298 } else {
10299 $this->db->commit();
10300 return $this->id;
10301 }
10302 }
10303
10304
10314 public function fetchCommon($id, $ref = null, $morewhere = '', $noextrafields = 0)
10315 {
10316 if (empty($id) && empty($ref) && empty($morewhere)) {
10317 return -1;
10318 }
10319
10320 $fieldlist = $this->getFieldList('t');
10321 if (empty($fieldlist)) {
10322 return 0;
10323 }
10324
10325 $sql = "SELECT ".$fieldlist;
10326 $sql .= " FROM ".$this->db->prefix().$this->table_element.' as t';
10327
10328 if (!empty($id)) {
10329 $sql .= ' WHERE t.rowid = '.((int) $id);
10330 } elseif (!empty($ref)) {
10331 $sql .= " WHERE t.ref = '".$this->db->escape($ref)."'";
10332 } else {
10333 $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
10334 }
10335 if (empty($id) && isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
10336 $sql .= ' AND t.entity IN ('.getEntity($this->element).')';
10337 }
10338 if ($morewhere) {
10339 $sql .= $morewhere;
10340 }
10341 $sql .= ' LIMIT 1'; // This is a fetch, to be certain to get only one record
10342
10343 $res = $this->db->query($sql);
10344 if ($res) {
10345 $obj = $this->db->fetch_object($res);
10346 if ($obj) {
10347 $this->setVarsFromFetchObj($obj);
10348
10349 // Retrieve all extrafield
10350 // fetch optionals attributes and labels
10351 if (empty($noextrafields)) {
10352 $result = $this->fetch_optionals();
10353 if ($result < 0) {
10354 $this->error = $this->db->lasterror();
10355 $this->errors[] = $this->error;
10356 return -4;
10357 }
10358 }
10359
10360 return $this->id;
10361 } else {
10362 return 0;
10363 }
10364 } else {
10365 $this->error = $this->db->lasterror();
10366 $this->errors[] = $this->error;
10367 return -1;
10368 }
10369 }
10370
10378 public function fetchLinesCommon($morewhere = '', $noextrafields = 0)
10379 {
10380 $objectlineclassname = get_class($this).'Line';
10381 if (!class_exists($objectlineclassname)) {
10382 $this->error = 'Error, class '.$objectlineclassname.' not found during call of fetchLinesCommon';
10383 return -1;
10384 }
10385
10386 $objectline = new $objectlineclassname($this->db);
10387 '@phan-var-force CommonObjectLine $objectline';
10388
10389 $sql = "SELECT ".$objectline->getFieldList('l');
10390 $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
10391 $sql .= " WHERE l.fk_".$this->db->escape($this->element)." = ".((int) $this->id);
10392 if ($morewhere) {
10393 $sql .= $morewhere;
10394 }
10395 if (isset($objectline->fields['position'])) {
10396 $sql .= $this->db->order('position', 'ASC');
10397 }
10398
10399 $resql = $this->db->query($sql);
10400 if ($resql) {
10401 $num_rows = $this->db->num_rows($resql);
10402 $i = 0;
10403 $this->lines = array();
10404 while ($i < $num_rows) {
10405 $obj = $this->db->fetch_object($resql);
10406 if ($obj) {
10407 $newline = new $objectlineclassname($this->db);
10408 '@phan-var-force CommonObjectLine $newline';
10409 $newline->setVarsFromFetchObj($obj);
10410
10411 // Note: extrafields load of line not yet supported
10412 /*
10413 if (empty($noextrafields)) {
10414 // Load extrafields of line
10415 }*/
10416
10417 $this->lines[] = $newline;
10418 }
10419 $i++;
10420 }
10421
10422 return 1;
10423 } else {
10424 $this->error = $this->db->lasterror();
10425 $this->errors[] = $this->error;
10426 return -1;
10427 }
10428 }
10429
10437 public function updateCommon(User $user, $notrigger = 0)
10438 {
10439 dol_syslog(get_class($this)."::updateCommon update", LOG_DEBUG);
10440
10441 $error = 0;
10442
10443 $now = dol_now();
10444
10445 // $this->oldcopy should have been set by the caller of update
10446 //if (empty($this->oldcopy)) {
10447 // dol_syslog("this->oldcopy should have been set by the caller of update (here properties were already modified)", LOG_WARNING);
10448 // $this->oldcopy = dol_clone($this, 2);
10449 //}
10450
10451 $fieldvalues = $this->setSaveQuery();
10452
10453 // Note: Here, $fieldvalues contains same keys (or less) that are inside ->fields
10454
10455 if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
10456 $fieldvalues['date_modification'] = $this->db->idate($now);
10457 }
10458 if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) {
10459 $fieldvalues['fk_user_modif'] = $user->id;
10460 }
10461 if (array_key_exists('user_modification_id', $fieldvalues) && !($fieldvalues['user_modification_id'] > 0)) {
10462 $fieldvalues['user_modification_id'] = $user->id;
10463 }
10464 if (array_key_exists('ref', $fieldvalues)) {
10465 $fieldvalues['ref'] = dol_string_nospecial($fieldvalues['ref']); // If field is a ref, we sanitize data
10466 }
10467
10468 unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
10469
10470 // Add quotes and escape on fields with type string
10471 $keys = array();
10472 $values = array();
10473 $tmp = array();
10474 foreach ($fieldvalues as $k => $v) {
10475 $keys[$k] = $k;
10476 $value = $this->fields[$k];
10477 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10478 $values[$k] = $this->quote($v, $value);
10479 if (($value["type"] == "text") && !empty($value['arrayofkeyval']) && is_array($value['arrayofkeyval'])) {
10480 // Clean values for text with selectbox
10481 $v = preg_replace('/\s/', ',', $v);
10482 $v = preg_replace('/,+/', ',', $v);
10483 }
10484 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
10485 $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
10486 }
10487
10488 // Clean and check mandatory fields
10489 foreach ($keys as $key) {
10490 if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
10491 $values[$key] = ''; // This is an implicit foreign key field
10492 }
10493 if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
10494 $values[$key] = ''; // This is an explicit foreign key field
10495 }
10496
10497 //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
10498 /*
10499 if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
10500 {
10501 $error++;
10502 $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
10503 }*/
10504 }
10505
10506 $sql = 'UPDATE '.$this->db->prefix().$this->table_element.' SET '.implode(', ', $tmp).' WHERE rowid='.((int) $this->id);
10507
10508 $this->db->begin();
10509
10510 if (!$error) {
10511 $res = $this->db->query($sql);
10512 if (!$res) {
10513 $error++;
10514 $this->errors[] = $this->db->lasterror();
10515 }
10516 }
10517
10518 // Update extrafield
10519 if (!$error) {
10520 $result = $this->insertExtraFields(); // This delete and reinsert extrafields
10521 if ($result < 0) {
10522 $error++;
10523 }
10524 }
10525
10526 // Triggers
10527 if (!$error && !$notrigger) {
10528 // Call triggers
10529 $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
10530 if ($result < 0) {
10531 $error++;
10532 } //Do also here what you must do to rollback action if trigger fail
10533 // End call triggers
10534 }
10535
10536 // Commit or rollback
10537 if ($error) {
10538 $this->db->rollback();
10539 return -1;
10540 } else {
10541 $this->db->commit();
10542 return $this->id;
10543 }
10544 }
10545
10554 public function deleteCommon(User $user, $notrigger = 0, $forcechilddeletion = 0)
10555 {
10556 dol_syslog(get_class($this)."::deleteCommon delete", LOG_DEBUG);
10557
10558 $error = 0;
10559
10560 $this->db->begin();
10561
10562 if ($forcechilddeletion) { // Force also delete of childtables that should lock deletion in standard case when option force is off
10563 foreach ($this->childtables as $table) {
10564 $sql = "DELETE FROM ".$this->db->prefix().$table." WHERE ".$this->fk_element." = ".((int) $this->id);
10565 $resql = $this->db->query($sql);
10566 if (!$resql) {
10567 $this->error = $this->db->lasterror();
10568 $this->errors[] = $this->error;
10569 $this->db->rollback();
10570 return -1;
10571 }
10572 }
10573 } elseif (!empty($this->childtables)) { // If object has children linked with a foreign key field, we check all child tables.
10574 $objectisused = $this->isObjectUsed($this->id);
10575 if (!empty($objectisused)) {
10576 dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
10577 $this->error = 'ErrorRecordHasChildren';
10578 $this->errors[] = $this->error;
10579 $this->db->rollback();
10580 return 0;
10581 }
10582 }
10583
10584 // Delete cascade first
10585 if (is_array($this->childtablesoncascade) && !empty($this->childtablesoncascade)) {
10586 foreach ($this->childtablesoncascade as $tabletodelete) {
10587 $deleteFromObject = explode(':', $tabletodelete, 4);
10588 if (count($deleteFromObject) >= 2) {
10589 $className = str_replace('@', '', $deleteFromObject[0]);
10590 $filePath = $deleteFromObject[1];
10591 $columnName = $deleteFromObject[2];
10592 $filter = '';
10593 if (!empty($deleteFromObject[3])) {
10594 $filter = $deleteFromObject[3];
10595 }
10596 if (dol_include_once($filePath)) {
10597 $childObject = new $className($this->db);
10598 if (method_exists($childObject, 'deleteByParentField')) {
10599 '@phan-var-force CommonObject $childObject';
10600 $result = $childObject->deleteByParentField($this->id, $columnName, $filter);
10601 if ($result < 0) {
10602 $error++;
10603 $this->errors[] = $childObject->error;
10604 break;
10605 }
10606 } else {
10607 $error++;
10608 $this->errors[] = "You defined a cascade delete on an object $className/$this->id but there is no method deleteByParentField for it";
10609 break;
10610 }
10611 } else {
10612 $error++;
10613 $this->errors[] = 'Cannot include child class file '.$filePath;
10614 break;
10615 }
10616 } else {
10617 // Delete record in child table
10618 $sql = "DELETE FROM ".$this->db->prefix().$tabletodelete." WHERE ".$this->fk_element." = ".((int) $this->id);
10619
10620 $resql = $this->db->query($sql);
10621 if (!$resql) {
10622 $error++;
10623 $this->error = $this->db->lasterror();
10624 $this->errors[] = $this->error;
10625 break;
10626 }
10627 }
10628 }
10629 }
10630
10631 if (!$error) {
10632 if (!$notrigger) {
10633 // Call triggers
10634 $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
10635 if ($result < 0) {
10636 $error++;
10637 } // Do also here what you must do to rollback action if trigger fail
10638 // End call triggers
10639 }
10640 }
10641
10642 // Delete llx_ecm_files
10643 if (!$error) {
10644 $res = $this->deleteEcmFiles(1); // Deleting files physically is done later with the dol_delete_dir_recursive
10645 if (!$res) {
10646 $error++;
10647 }
10648 }
10649
10650 // Delete linked object
10651 $res = $this->deleteObjectLinked();
10652 if ($res < 0) {
10653 $error++;
10654 }
10655
10656 if (!$error && !empty($this->isextrafieldmanaged)) {
10657 $result = $this->deleteExtraFields();
10658 if ($result < 0) {
10659 $error++;
10660 }
10661 }
10662
10663 if (!$error) {
10664 $sql = 'DELETE FROM '.$this->db->prefix().$this->table_element.' WHERE rowid='.((int) $this->id);
10665
10666 $resql = $this->db->query($sql);
10667 if (!$resql) {
10668 $error++;
10669 $this->errors[] = $this->db->lasterror();
10670 }
10671 }
10672
10673 // Commit or rollback
10674 if ($error) {
10675 $this->db->rollback();
10676 return -1;
10677 } else {
10678 $this->db->commit();
10679 return 1;
10680 }
10681 }
10682
10694 public function deleteByParentField($parentId = 0, $parentField = '', $filter = '', $filtermode = "AND")
10695 {
10696 global $user;
10697
10698 $error = 0;
10699 $deleted = 0;
10700
10701 if (!empty($parentId) && !empty($parentField)) {
10702 $this->db->begin();
10703
10704 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element;
10705 $sql .= " WHERE ".$this->db->sanitize($parentField)." = ".(int) $parentId;
10706
10707 // Manage filter
10708 $errormessage = '';
10709 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
10710 if ($errormessage) {
10711 $this->errors[] = $errormessage;
10712 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
10713 return -1;
10714 }
10715
10716 $resql = $this->db->query($sql);
10717 if (!$resql) {
10718 $this->errors[] = $this->db->lasterror();
10719 $error++;
10720 } else {
10721 while ($obj = $this->db->fetch_object($resql)) {
10722 $result = $this->fetch($obj->rowid); // @phpstan-ignore-line
10723 if ($result < 0) {
10724 $error++;
10725 $this->errors[] = $this->error;
10726 } else {
10727 $result = $this->delete($user); // @phpstan-ignore-line
10728 if ($result < 0) {
10729 $error++;
10730 $this->errors[] = $this->error;
10731 } else {
10732 $deleted++;
10733 }
10734 }
10735 }
10736 }
10737
10738 if (empty($error)) {
10739 $this->db->commit();
10740 return $deleted;
10741 } else {
10742 $this->error = implode(', ', $this->errors);
10743 $this->db->rollback();
10744 return $error * -1;
10745 }
10746 }
10747
10748 return $deleted;
10749 }
10750
10759 public function deleteLineCommon(User $user, $idline, $notrigger = 0)
10760 {
10761 $error = 0;
10762
10763 $tmpforobjectclass = get_class($this);
10764 $tmpforobjectlineclass = ucfirst($tmpforobjectclass).'Line';
10765
10766 $this->db->begin();
10767
10768 // Call trigger
10769 $result = $this->call_trigger('LINE'.strtoupper($tmpforobjectclass).'_DELETE', $user);
10770 if ($result < 0) {
10771 $error++;
10772 }
10773 // End call triggers
10774
10775 if (empty($error)) {
10776 $sql = "DELETE FROM ".$this->db->prefix().$this->table_element_line;
10777 $sql .= " WHERE rowid = ".((int) $idline);
10778
10779 $resql = $this->db->query($sql);
10780 if (!$resql) {
10781 $this->error = "Error ".$this->db->lasterror();
10782 $error++;
10783 }
10784 }
10785
10786 if (empty($error)) {
10787 // Remove extrafields
10788 $tmpobjectline = new $tmpforobjectlineclass($this->db);
10789 '@phan-var-force CommonObjectLine $tmpobjectline';
10790 if (!isset($tmpobjectline->isextrafieldmanaged) || !empty($tmpobjectline->isextrafieldmanaged)) {
10791 $tmpobjectline->id = $idline;
10792 $result = $tmpobjectline->deleteExtraFields();
10793 if ($result < 0) {
10794 $error++;
10795 $this->error = "Error ".get_class($this)."::deleteLineCommon deleteExtraFields error -4 ".$tmpobjectline->error;
10796 }
10797 }
10798 }
10799
10800 if (empty($error)) {
10801 $this->db->commit();
10802 return 1;
10803 } else {
10804 dol_syslog(get_class($this)."::deleteLineCommon ERROR:".$this->error, LOG_ERR);
10805 $this->db->rollback();
10806 return -1;
10807 }
10808 }
10809
10810
10820 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
10821 {
10822 $error = 0;
10823
10824 $this->db->begin();
10825
10826 $statusfield = 'status';
10827 if (in_array($this->element, array('don', 'donation', 'shipping'))) {
10828 $statusfield = 'fk_statut';
10829 }
10830
10831 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
10832 $sql .= " SET ".$statusfield." = ".((int) $status);
10833 $sql .= " WHERE rowid = ".((int) $this->id);
10834
10835 if ($this->db->query($sql)) {
10836 if (!$error) {
10837 $this->oldcopy = clone $this;
10838 }
10839
10840 if (!$error && !$notrigger) {
10841 // Call trigger
10842 $result = $this->call_trigger($triggercode, $user);
10843 if ($result < 0) {
10844 $error++;
10845 }
10846 }
10847
10848 if (!$error) {
10849 $this->status = $status;
10850 if (property_exists($this, 'statut')) { // For backward compatibility
10851 $this->statut = $status;
10852 }
10853 $this->db->commit();
10854 return 1;
10855 } else {
10856 $this->db->rollback();
10857 return -1;
10858 }
10859 } else {
10860 $this->error = $this->db->error();
10861 $this->db->rollback();
10862 return -1;
10863 }
10864 }
10865
10872 public function initAsSpecimenCommon()
10873 {
10874 global $user;
10875
10876 $this->id = 0;
10877 $this->specimen = 1;
10878 $fields = array(
10879 'label' => 'This is label',
10880 'ref' => 'ABCD1234',
10881 'description' => 'This is a description',
10882 'qty' => 123.12,
10883 'note_public' => 'Public note',
10884 'note_private' => 'Private note',
10885 'date_creation' => (dol_now() - 3600 * 48),
10886 'date_modification' => (dol_now() - 3600 * 24),
10887 'fk_user_creat' => $user->id,
10888 'fk_user_modif' => $user->id,
10889 'date' => dol_now(),
10890 );
10891 foreach ($fields as $key => $value) {
10892 if (array_key_exists($key, $this->fields)) {
10893 $this->{$key} = $value; // @phpstan-ignore-line
10894 }
10895 }
10896
10897 // Force values to default values when known
10898 if (property_exists($this, 'fields')) {
10899 foreach ($this->fields as $key => $value) {
10900 // If fields are already set, do nothing
10901 if (array_key_exists($key, $fields)) {
10902 continue;
10903 }
10904
10905 if (!empty($value['default'])) {
10906 $this->$key = $value['default'];
10907 }
10908 }
10909 }
10910
10911 return 1;
10912 }
10913
10914
10915 /* Part for comments */
10916
10922 public function fetchComments()
10923 {
10924 require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
10925
10926 $comment = new Comment($this->db);
10927 $result = $comment->fetchAllFor($this->element, $this->id);
10928 if ($result < 0) {
10929 $this->errors = array_merge($this->errors, $comment->errors);
10930 return -1;
10931 } else {
10932 $this->comments = $comment->comments;
10933 }
10934 return count($this->comments);
10935 }
10936
10942 public function getNbComments()
10943 {
10944 return count($this->comments);
10945 }
10946
10953 public function trimParameters($parameters)
10954 {
10955 if (!is_array($parameters)) {
10956 return;
10957 }
10958 foreach ($parameters as $parameter) {
10959 if (isset($this->$parameter)) {
10960 $this->$parameter = trim($this->$parameter);
10961 }
10962 }
10963 }
10964
10965 /* Part for categories/tags */
10966
10977 public function getCategoriesCommon($type_categ)
10978 {
10979 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
10980
10981 // Get current categories
10982 $c = new Categorie($this->db);
10983 $existing = $c->containing($this->id, $type_categ, 'id');
10984
10985 return $existing;
10986 }
10987
11000 public function setCategoriesCommon($categories, $type_categ = '', $remove_existing = true)
11001 {
11002 // Handle single category
11003 if (!is_array($categories)) {
11004 $categories = array($categories);
11005 }
11006
11007 dol_syslog(get_class($this)."::setCategoriesCommon Object Id:".$this->id.' type_categ:'.$type_categ.' nb tag add:'.count($categories), LOG_DEBUG);
11008
11009 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11010
11011 if (empty($type_categ)) {
11012 dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown category type. Done nothing.', LOG_ERR);
11013 return -1;
11014 }
11015
11016 // Get current categories
11017 $c = new Categorie($this->db);
11018 $existing = $c->containing($this->id, $type_categ, 'id');
11019 if ($remove_existing) {
11020 // Diff
11021 if (is_array($existing)) {
11022 $to_del = array_diff($existing, $categories);
11023 $to_add = array_diff($categories, $existing);
11024 } else {
11025 $to_del = array(); // Nothing to delete
11026 $to_add = $categories;
11027 }
11028 } else {
11029 $to_del = array(); // Nothing to delete
11030 $to_add = array_diff($categories, $existing);
11031 }
11032
11033 $error = 0;
11034 $ok = 0;
11035
11036 // Process
11037 foreach ($to_del as $del) {
11038 if ($c->fetch($del) > 0) {
11039 $result = $c->del_type($this, $type_categ);
11040 if ($result < 0) {
11041 $error++;
11042 $this->error = $c->error;
11043 $this->errors = $c->errors;
11044 break;
11045 } else {
11046 $ok += $result;
11047 }
11048 }
11049 }
11050 foreach ($to_add as $add) {
11051 if ($c->fetch($add) > 0) {
11052 $result = $c->add_type($this, $type_categ);
11053 if ($result < 0) {
11054 $error++;
11055 $this->error = $c->error;
11056 $this->errors = $c->errors;
11057 break;
11058 } else {
11059 $ok += $result;
11060 }
11061 }
11062 }
11063
11064 return $error ? (-1 * $error) : $ok;
11065 }
11066
11075 public function cloneCategories($fromId, $toId, $type = '')
11076 {
11077 $this->db->begin();
11078
11079 if (empty($type)) {
11080 $type = $this->table_element;
11081 }
11082
11083 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
11084 $categorystatic = new Categorie($this->db);
11085
11086 $sql = "INSERT INTO ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type])." (fk_categorie, fk_product)";
11087 $sql .= " SELECT fk_categorie, $toId FROM ".$this->db->prefix()."categorie_".(empty($categorystatic->MAP_CAT_TABLE[$type]) ? $type : $categorystatic->MAP_CAT_TABLE[$type]);
11088 $sql .= " WHERE fk_product = ".((int) $fromId);
11089
11090 if (!$this->db->query($sql)) {
11091 $this->error = $this->db->lasterror();
11092 $this->db->rollback();
11093 return -1;
11094 }
11095
11096 $this->db->commit();
11097 return 1;
11098 }
11099
11106 public function deleteEcmFiles($mode = 0)
11107 {
11108 global $conf;
11109
11110 $this->db->begin();
11111
11112 // Delete in database with mode 0
11113 if ($mode == 0) {
11114 switch ($this->element) {
11115 case 'propal':
11116 $element = 'propale';
11117 break;
11118 case 'product':
11119 $element = 'produit';
11120 break;
11121 case 'order_supplier':
11122 $element = 'fournisseur/commande';
11123 break;
11124 case 'invoice_supplier':
11125 // Special cases that need to use get_exdir to get real dir of object
11126 // In future, all object should use this to define path of documents.
11127 $element = 'fournisseur/facture/'.get_exdir($this->id, 2, 0, 1, $this, 'invoice_supplier');
11128 break;
11129 case 'shipping':
11130 $element = 'expedition/sending';
11131 break;
11132 case 'task':
11133 case 'project_task':
11134 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
11135
11136 $project_result = $this->fetch_projet();
11137 if ($project_result >= 0) {
11138 $element = 'projet/'.dol_sanitizeFileName($this->project->ref).'/';
11139 }
11140 // no break
11141 default:
11142 $element = $this->element;
11143 }
11144 '@phan-var-force string $element';
11145
11146 // Delete ecm_files_extrafields with mode 0 (using name)
11147 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files_extrafields WHERE fk_object IN (";
11148 $sql .= " SELECT rowid FROM ".$this->db->prefix()."ecm_files WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
11149 $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
11150 $sql .= ")";
11151
11152 if (!$this->db->query($sql)) {
11153 $this->error = $this->db->lasterror();
11154 $this->db->rollback();
11155 return false;
11156 }
11157
11158 // Delete ecm_files with mode 0 (using name)
11159 $sql = "DELETE FROM ".$this->db->prefix()."ecm_files";
11160 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%'";
11161 $sql .= " AND filepath = '".$this->db->escape($element)."/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity); // No need of getEntity here
11162
11163 if (!$this->db->query($sql)) {
11164 $this->error = $this->db->lasterror();
11165 $this->db->rollback();
11166 return false;
11167 }
11168 }
11169
11170 // Delete in database with mode 1
11171 if ($mode == 1) {
11172 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files_extrafields";
11173 $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).")";
11174 $resql = $this->db->query($sql);
11175 if (!$resql) {
11176 $this->error = $this->db->lasterror();
11177 $this->db->rollback();
11178 return false;
11179 }
11180
11181 $sql = 'DELETE FROM '.$this->db->prefix()."ecm_files";
11182 $sql .= " WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
11183 $resql = $this->db->query($sql);
11184 if (!$resql) {
11185 $this->error = $this->db->lasterror();
11186 $this->db->rollback();
11187 return false;
11188 }
11189 }
11190
11191 $this->db->commit();
11192 return true;
11193 }
11194}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
print $langs trans("AuditedSecurityEvents").'</strong >< span class="opacitymedium"></span >< br > status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition security.php:640
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.
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.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
getState($id, $withcode='0', $dbtouse=null, $withregion=0, $outputlangs=null, $entconv=1)
Return state translated from an id.
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:241
dol_meta_create($object)
Create a meta file with document file into same directory.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
completeFileArrayWithDatabaseInfo(&$filearray, $relativedir)
Complete $filearray with data from database.
dol_delete_preview($object)
Delete all preview files linked to object instance.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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.
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
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.
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='AES-256-CTR', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
publicphonebutton2 phonegreen basiclayout basiclayout TotalHT VATCode TotalVAT TotalLT1 TotalLT2 TotalTTC TotalHT clearboth nowraponall TAKEPOS_SHOW_SUBPRICE right right right takeposterminal SELECT e rowid
Definition invoice.php:2002