-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathcommoninjectionlib.class.php
More file actions
2331 lines (2008 loc) · 84.5 KB
/
commoninjectionlib.class.php
File metadata and controls
2331 lines (2008 loc) · 84.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* -------------------------------------------------------------------------
* DataInjection plugin for GLPI
* -------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of DataInjection.
*
* DataInjection is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* DataInjection is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DataInjection. If not, see <http://www.gnu.org/licenses/>.
* -------------------------------------------------------------------------
* @copyright Copyright (C) 2007-2023 by DataInjection plugin team.
* @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html
* @link https://github.com/pluginsGLPI/datainjection
* -------------------------------------------------------------------------
*/
use Glpi\Exception\Http\HttpException;
use Glpi\Features\AssignableItem;
use function Safe\preg_match;
use function Safe\preg_replace;
class PluginDatainjectionCommonInjectionLib
{
//Injection results
private $results = [];
//Values to inject
private $values = [];
//Fields mandatory for injection
private $mandatory_fields = [];
private $optional_infos = [];
//Injection class to use
private $injectionClass;
//Primary type to inject
private $primary_type;
//Store checks to perform on values
private $checks = [];
//Store rights
private $rights = [];
//Store specific fields formats
private $formats = [];
//Entity in which data will be inserted
private $entity = 0;
public const ACTION_CHECK = 0;
//Type of action to perform
public const IMPORT_ADD = 0;
public const IMPORT_UPDATE = 1;
public const IMPORT_DELETE = 2;
//Action return constants
public const SUCCESS = 10; //Injection OK
public const FAILED = 11; //Error during injection
public const WARNING = 12; //Injection ok but partial
//Field check return constants
public const TYPE_MISMATCH = 22;
public const MANDATORY = 23;
public const ITEM_NOT_FOUND = 24;
//Injection Message
public const ERROR_CANNOT_IMPORT = 31;
public const ERROR_CANNOT_UPDATE = 32;
public const WARNING_NOTFOUND = 33;
public const ERROR_FIELDSIZE_EXCEEDED = 37;
public const ERROR_IMPORT_REFUSED = 39; //Dictionnary explicitly refuse import
//Empty values
public const EMPTY_VALUE = '';
public const DROPDOWN_EMPTY_VALUE = 0;
//Format constants
public const FLOAT_TYPE_COMMA = 0; //xxxx,xx
public const FLOAT_TYPE_DOT = 1; //xxxx.xx
public const FLOAT_TYPE_DOT_AND_COM = 2; //xx,xxx.xx
//Date management constants
public const DATE_TYPE_DDMMYYYY = "dd-mm-yyyy";
public const DATE_TYPE_MMDDYYYY = "mm-dd-yyyy";
public const DATE_TYPE_YYYYMMDD = "yyyy-mm-dd";
//Port unicity constants
public const UNICITY_NETPORT_LOGICAL_NUMBER = 0;
public const UNICITY_NETPORT_NAME = 1;
public const UNICITY_NETPORT_MACADDRESS = 2;
public const UNICITY_NETPORT_LOGICAL_NUMBER_NAME = 3;
public const UNICITY_NETPORT_LOGICAL_NUMBER_MAC = 4;
public const UNICITY_NETPORT_LOGICAL_NUMBER_NAME_MAC = 5;
//Field status must evolve when ticket #2216 will be resolved
public const FIELD_INJECTABLE = 1;
public const FIELD_VIRTUAL = 2;
/**
* Set default values for injection parameters
*
* @return void nothing
**/
public function setDefaultValues(): void
{
$this->checks = ['ip' => false, 'mac' => false,
'integer' => false, 'yes' => false,
'bool' => false, 'date' => false,
'float' => false, 'string' => false,
'right_r' => false, 'right_rw' => false,
'interface' => false, 'auth_method' => false,
'port_unicity' => false,
];
//Rights options
$this->rights = ['add_dropdown' => false,
'overwrite_notempty_fields' => false,
'can_add' => false,
'can_update' => false,
'can_delete' => false,
'replace_multiline_value' => false,
];
//Field format options
$this->formats = ['date_format' => self::DATE_TYPE_YYYYMMDD,
'float_format' => self::FLOAT_TYPE_COMMA,
];
}
/**
* Constructor : store all needed options into the library
*
* @param PluginDatainjectionInjectionInterface $injectionClass class which represents the itemtype to injection
* (in 0.80, will be directly the itemtype class)
* @param array|null $values array values to injection into GLPI
* @param array|null $injection_options array options that can be used during the injection
* (maybe an empty array)
*
* @return void nothing
**/
public function __construct($injectionClass, $values = [], $injection_options = [])
{
$this->setDefaultValues();
if (isset($injection_options['checks'])) {
foreach ($injection_options['checks'] as $key => $value) {
$this->checks[$key] = $value;
}
}
if (isset($injection_options['checks'])) {
foreach ($injection_options['checks'] as $key => $value) {
$this->checks[$key] = $value;
}
}
if (isset($injection_options['rights'])) {
foreach ($injection_options['rights'] as $key => $value) {
$this->rights[$key] = $value;
}
}
if (isset($injection_options['mandatory_fields'])) {
$this->mandatory_fields = $injection_options['mandatory_fields'];
}
if (isset($injection_options['optional_data'])) {
$this->optional_infos = $injection_options['optional_data'];
}
//Split $injection_options array and store data into the rights internal arrays
if (isset($injection_options['formats'])) {
$this->formats = $injection_options['formats'];
} else {
$this->formats = ['date_format' => self::DATE_TYPE_YYYYMMDD,
'float_format' => self::FLOAT_TYPE_DOT,
];
}
//Store values to inject
$this->values = $values;
//Store injectClass & primary_type
$this->injectionClass = $injectionClass;
$this->primary_type = self::getItemtypeByInjectionClass($injectionClass);
//If entity is given stores it, then use root entity
$this->entity = $injection_options['entities_id'] ?? 0;
}
/**
* Check and add fields for itemtype which depend on other itemtypes
* (for example SoftwareLicense needs to be linked to a Software)
*
* @param PluginDatainjectionInjectionInterface $injectionClass class to use for injection
**/
public function areTypeMandatoryFieldsOK($injectionClass)
{
$itemtype = self::getItemtypeByInjectionClass($injectionClass);
//Add more values needed for mandatory fields management
if (method_exists($injectionClass, 'getValueForAdditionalMandatoryFields')) {
$this->values = $injectionClass->getValueForAdditionalMandatoryFields($this->values);
}
//Add new mandatory fields to check, needed by other itemtypes to inject
if (method_exists($injectionClass, 'addSpecificMandatoryFields')) {
$fields = $injectionClass->addSpecificMandatoryFields();
foreach ($fields as $key => $value) {
$this->mandatory_fields[$itemtype][$key] = $value;
}
}
$status_check = true;
$mandatory_fields = $this->mandatory_fields[$itemtype] ?? [];
if ($mandatory_fields !== []) {
foreach ($mandatory_fields as $field => $value) {
//Get value associated with the mandatory field
$value = $this->getValueByItemtypeAndName($itemtype, $field);
//Get search option associated with the mandatory field
$option = self::findSearchOption($injectionClass->getOptions($itemtype), $field);
//If field not defined, or if value is the dropdown's default value
//If no value found or value is 0 and field is a dropdown,
//then mandatory field management failed
if (
($value === false)
|| (($value == self::DROPDOWN_EMPTY_VALUE)
&& self::isFieldADropdown($option['displaytype']))
) {
$status_check = false;
$this->results[self::ACTION_CHECK][] = [self::MANDATORY, $option['name']];
}
}
} else {
$status_check = false;
$this->results[self::ACTION_CHECK][] = [
self::FAILED,
__('No mandatory field is defined for this model', 'datainjection'),
];
}
return $status_check;
}
/**
* Check if a field type represents a dropdown or not
*
* @param string $field_type the type of field
*
* @return boolean true if it's a dropdown type, false if not
**/
public static function isFieldADropdown($field_type)
{
return !in_array(
$field_type,
['integer', 'decimal', 'tree',
'text', 'multiline_text', 'date',
],
);
}
/**
* Return an the class of an item by giving his injection class
*
* @param string $injectionClassName the injection class name
*
* @return CommonDBTM instance of the itemtype associated to the injection class name
*/
public static function getItemtypeInstanceByInjection($injectionClassName)
{
if (!is_a($injectionClassName, PluginDatainjectionInjectionInterface::class, true)) {
throw new HttpException(500, 'Class ' . $injectionClassName . ' is not a valid class');
}
$injection = self::getItemtypeByInjectionClass(new $injectionClassName());
if (!is_a($injection, CommonDBTM::class, true)) {
throw new HttpException(500, 'Class ' . $injection . ' is not a valid class');
}
return new $injection();
}
/**
* Get an itemtype name by giving his injection class name
*
* @param string $injectionClassName the injection class name
*
* @return string the itemtype associated
*/
public static function getItemtypeByInjection($injectionClassName)
{
if (!is_a($injectionClassName, CommonDBTM::class, true)) {
throw new HttpException(500, 'Class ' . $injectionClassName . ' is not a valid class');
}
return self::getItemtypeByInjectionClass(new $injectionClassName());
}
/**
* Get an itemtype by giving an injection class object
*
* @param object $injectionClass Name the injection class object
*
* @return string instance of the itemtype associated to the injection class
*/
public static function getItemtypeByInjectionClass($injectionClass)
{
return Toolbox::ucfirst(getItemTypeForTable($injectionClass->getTable()));
}
/**
* Get an injection class instance for an itemtype
*
* @param string $itemtype the itemtype
*
* @return PluginDatainjectionInjectionInterface the injection class instance
*/
public static function getInjectionClassInstance($itemtype)
{
if (!isPluginItemType($itemtype)) {
$itemtype = (new ReflectionClass($itemtype))->getShortName(); // get shortname of class when full namespaced class given (from GLPI)
$injectionClass = 'PluginDatainjection' . ucfirst($itemtype) . 'Injection';
} else {
$injectionClass = ucfirst($itemtype) . 'Injection';
}
if (!is_a($injectionClass, PluginDatainjectionInjectionInterface::class, true)) {
throw new HttpException(500, 'Class ' . $injectionClass . ' is not a valid class');
}
return new $injectionClass();
}
/**
* Add blacklisted fields for an itemtype
*
* @param string $itemtype the itemtype
*
* @return array the array of all blacklisted fields
*/
public static function getBlacklistedOptions($itemtype)
{
/** @var array $CFG_GLPI */
global $CFG_GLPI;
// 2 : id
// 19 : date_mod
// 80 : entity
// 121 : date_creation
// 200 : notepad
$blacklist = [
2, // id
19, // last update
80, // completename
121, // creation date
200, // notepad - content
201, // notepad - creation date
202, // notepad - writer
203, // notepad - last update
204, // notepad - last updater
];
$raw_options_to_blacklist = [];
//add document fields
if (in_array($itemtype, $CFG_GLPI["document_types"])) {
$raw_options_to_blacklist = array_merge(
$raw_options_to_blacklist,
Document::rawSearchOptionsToAdd($itemtype),
);
}
//add infocoms fields
if (in_array($itemtype, $CFG_GLPI["infocom_types"])) {
$raw_options_to_blacklist = array_merge(
$raw_options_to_blacklist,
Infocom::rawSearchOptionsToAdd($itemtype),
);
}
//add contract fields
if (in_array($itemtype, $CFG_GLPI["contract_types"])) {
$raw_options_to_blacklist = array_merge(
$raw_options_to_blacklist,
Contract::rawSearchOptionsToAdd(),
);
}
//add networkport fields
if (in_array($itemtype, $CFG_GLPI["networkport_types"])) {
$raw_options_to_blacklist = array_merge(
$raw_options_to_blacklist,
NetworkPort::rawSearchOptionsToAdd($itemtype),
);
}
foreach ($raw_options_to_blacklist as $raw_option) {
if (!is_numeric($raw_option['id'])) {
continue;
}
$blacklist[] = $raw_option['id'];
}
//add ticket_types fields
if (in_array($itemtype, $CFG_GLPI["ticket_types"])) {
$blacklist[] = 60;
$blacklist[] = 140;
}
return $blacklist;
}
/**
* Find and return the right search option
*
* @param array $options the search options array
* @param string $lookfor the search option we're looking for
*
* @return array the search option matching lookfor parameter or false it not found
**/
public static function findSearchOption($options, $lookfor)
{
$found = false;
foreach ($options as $option) {
if (
isset($option['injectable']) && ($option['injectable'] == self::FIELD_INJECTABLE)
&& isset($option['linkfield']) && ($option['linkfield'] == $lookfor)
) {
$found = $option;
}
}
return $found;
}
//--------------------------------------------------//
//----------- Injection options getters -----------//
//------------------------------------------------//
/**
* Get date format used for injection
*
* @return string date format used
**/
private function getDateFormat()
{
return $this->formats['date_format'];
}
/**
* Get date format used for injection
*
* @return string date format used
**/
private function getFloatFormat()
{
return $this->formats['float_format'];
}
/**
* Get itemtype associated to the injectionClass
*
* @return CommonDBTM an itemtype
**/
private function getItemInstance()
{
$classname = get_class($this->injectionClass);
return self::getItemtypeInstanceByInjection($classname);
}
/**
* Return injection results
*
* @return array which contains the reformat/check/injection logs
**/
public function getInjectionResults()
{
return $this->results;
}
/**
* Get ID associate to the value from the CSV file is needed (for example for dropdown tables)
*
* @return void nothing
**/
private function manageFieldValues()
{
$blacklisted_fields = ['id'];
foreach ($this->values as $itemtype => $data) {
$injectionClass = self::getInjectionClassInstance($itemtype);
$searchOptions = $injectionClass->getOptions($this->primary_type);
foreach ($data as $field => $value) {
if (!in_array($field, $blacklisted_fields)) {
$searchOption = self::findSearchOption($searchOptions, $field);
//searchoption relation type is already manage by manageRelations()
//skip it
if (
!empty($searchOption)
&& ((isset($searchOption['displaytype']) && $searchOption['displaytype'] != 'relation')
|| !isset($searchOption['displaytype']))
) {
$this->getFieldValue($injectionClass, $itemtype, $searchOption, $field, $value);
}
}
}
//TODO : This is ugly, need to find why it adds an empty value to the array
foreach ($this->values[$itemtype] as $field => $value) {
if ($field == '') {
unset($this->values[$itemtype][$field]);
}
}
}
}
/**
* Get the ID associated with a value from the CSV file
*
* @param PluginDatainjectionInjectionInterface|null $injectionClass
* @param string $itemtype itemtype of the values to inject
* @param array $searchOption option associated with the field to check
* @param string $field the field to check
* @param string $value the value coming from the CSV file
* @param boolean $add is insertion (true) or update (false) (true by default)
*
* @return void nothing
**/
private function getFieldValue(
$injectionClass,
$itemtype,
$searchOption,
$field,
$value,
$add = true
) {
$linkfield = $searchOption['storevaluein'] ?? $searchOption['linkfield'];
switch ($searchOption['displaytype']) {
case 'tree':
$this->setValueForItemtype($itemtype, $linkfield, $value);
break;
case 'decimal':
case 'text':
$this->setValueForItemtype($itemtype, $linkfield, $value);
break;
case 'password':
//To add a user password, it's mandatory is give a password and it's confirmation
//Here we cannot detect if it's an add or update. We'll handle updates later in the process
if ($add && $itemtype == 'User') {
$this->setValueForItemtype($itemtype, $linkfield, $value);
//Add field password2 is not already present
//(can be present if password was an addtional information)
if (!isset($this->values[$itemtype][$field])) {
$this->setValueForItemtype($itemtype, $linkfield . "2", $value);
}
}
break;
case 'dropdown':
case 'relation':
$tmptype = getItemTypeForTable($searchOption['table']);
if (!is_a($tmptype, CommonDBTM::class, true)) {
return;
}
$item = new $tmptype();
if ($item instanceof CommonTreeDropdown) {
// use findID instead of getID
$input = [
'completename' => $value,
'entities_id' => $this->entity,
];
if ($item->getType() == 'Entity') {
// Blocks entity creation. The findID method only searches for direct sub-entities of the root, not deeper levels.
$crit = 'name';
if (strpos($input['completename'], '>')) {
$crit = 'completename';
}
$entity = new Entity();
$result = $entity->getFromDBByCrit(
[
$crit => $input['completename'],
'entities_id' => $input['entities_id'],
],
);
if ($result !== false) {
$input['entities_id'] = $entity->fields['id'];
}
$sons = getSonsOf('glpi_entities', $input['entities_id']);
if ($result === false && !empty($sons)) {
foreach ($sons as $son_id) {
$result = $entity->getFromDBByCrit(
[
$crit => $input['completename'],
'entities_id' => $son_id,
],
);
if ($result !== false) {
$input['entities_id'] = $entity->fields['id'];
break;
}
}
}
$id = $input['entities_id'];
} elseif ($item->canCreate() && $this->rights['add_dropdown']) {
$id = $item->import($input);
} else {
$id = $item->findID($input);
}
} elseif ($item instanceof CommonDropdown) {
$canadd = $item->canCreate() && $this->rights['add_dropdown'];
$id = $item->importExternal(
$value,
$this->entity,
$this->addExternalDropdownParameters($itemtype),
'',
$canadd,
);
} else {
$id = self::findSingle($item, $searchOption, $this->entity, $value);
}
// Use EMPTY_VALUE for Mandatory field check
$this->setValueForItemtype($itemtype, $linkfield, ($id > 0 ? $id : self::EMPTY_VALUE));
if ($value && $id <= 0) {
$this->results['status'] = self::WARNING;
$this->results[self::ACTION_CHECK]['status'] = self::WARNING;
$this->results[self::ACTION_CHECK][] = [self::WARNING_NOTFOUND,
$searchOption['name'] . "='$value'",
];
}
break;
case 'template':
$id = self::getTemplateIDByName($itemtype, $value);
if ($id) {
//Template id is stored into the item's id : when adding the object
//glpi will understand that it needs to take fields from the template
$this->setValueForItemtype($itemtype, '_oldID', $id);
}
break;
case 'contact':
if ($value === self::EMPTY_VALUE || $value == self::DROPDOWN_EMPTY_VALUE || $value === Dropdown::EMPTY_VALUE) {
$id = self::DROPDOWN_EMPTY_VALUE;
} else {
$id = self::findContact($value, $this->entity);
}
$this->setValueForItemtype($itemtype, $linkfield, $id);
break;
case 'user':
if ($value === self::EMPTY_VALUE || $value == self::DROPDOWN_EMPTY_VALUE || $value === Dropdown::EMPTY_VALUE) {
$id = self::DROPDOWN_EMPTY_VALUE;
} else {
$id = self::findUser($value, $this->entity);
}
$this->setValueForItemtype($itemtype, $linkfield, $id);
break;
default:
if (method_exists($injectionClass, 'getSpecificFieldValue')) {
$id = $injectionClass->getSpecificFieldValue(
$itemtype,
$searchOption,
$field,
$this->values,
);
$this->setValueForItemtype($itemtype, $linkfield, $id);
} else {
$this->setValueForItemtype($itemtype, $linkfield, $value);
}
}
}
/**
* Add additional parameters needed for dropdown import
*
* @param string $itemtype dropdrown's itemtype
*
* @return array with additional options to be added
**/
private function addExternalDropdownParameters($itemtype)
{
/** @var DBmysql $DB */
global $DB;
$external = [];
$values = $this->getValuesForItemtype($itemtype);
$toadd = ['manufacturers_id' => 'manufacturer'];
foreach ($toadd as $field => $addvalue) {
if (isset($values[$field])) {
switch ($addvalue) {
case 'manufacturer':
if (intval($values[$field]) > 0) {
$external[$addvalue]
= $DB->escape(
Dropdown::getDropdownName(
'glpi_manufacturers',
$values[$field],
),
);
break;
}
// TODO: is fall-through intentional here ?
// no break
default:
$external[$addvalue] = $values[$field];
}
} else {
$external[$addvalue] = '';
}
}
return $external;
}
/**
* Find a user. Look for login OR firstname + lastname OR lastname + firstname
*
* @param string $value the user to look for
* @param int|string $entity the entity where the user should have right
*
* @return int|string the user ID if found or ''
**/
private static function findUser($value, $entity)
{
/** @var DBmysql $DB */
global $DB;
$sql = "SELECT `id`
FROM `glpi_users`
WHERE LOWER(`name`) = '" . strtolower($value) . "'
OR (CONCAT(LOWER(`realname`),' ',LOWER(`firstname`)) = '" . strtolower($value) . "'
OR CONCAT(LOWER(`firstname`),' ',LOWER(`realname`)) = '" . strtolower($value) . "')";
$result = $DB->doQuery($sql);
if ($DB->numrows($result) > 0) {
//check if user has right on the current entity
$ID = $DB->result($result, 0, "id");
$entities = Profile_User::getUserEntities($ID, true);
if (in_array($entity, $entities)) {
return $ID;
}
return self::DROPDOWN_EMPTY_VALUE;
}
return self::DROPDOWN_EMPTY_VALUE;
}
/**
* Find a user. Look for login OR firstname + lastname OR lastname + firstname
*
* @param string $value the user to look for
* @param int|string $entity the entity where the user should have right
*
* @return int|string the user ID if found or ''
*/
private static function findContact($value, $entity)
{
/** @var DBmysql $DB */
global $DB;
$sql = "SELECT `id`
FROM `glpi_contacts`
WHERE `entities_id` = '" . $entity . "'
AND (LOWER(`name`) = '" . strtolower($value) . "'
OR (CONCAT(LOWER(`name`),' ',LOWER(`firstname`)) = '" . strtolower($value) . "'
OR CONCAT(LOWER(`firstname`),' ',LOWER(`name`)) = '" . strtolower($value) . "'))";
$result = $DB->doQuery($sql);
if ($DB->numrows($result) > 0) {
//check if user has right on the current entity
return $DB->result($result, 0, "id");
}
return self::DROPDOWN_EMPTY_VALUE;
}
/**
* Find id for a single type
*
* @param CommonDBTM $item the CommonDBTM item representing an itemtype
* @param array $searchOption searchOption related to the item
* @param int|string $entity the current entity
* @param string $value the name of the item for which id must be returned
*
* @return int|string the id of the item found
**/
private static function findSingle($item, $searchOption, $entity, $value)
{
/** @var DBmysql $DB */
global $DB;
$query = "SELECT `id`
FROM `" . $item->getTable() . "`
WHERE 1";
if ($item->maybeTemplate()) {
$query .= " AND `is_template` = '0'";
}
if ($item->isEntityAssign()) {
$query .= getEntitiesRestrictRequest(
" AND",
$item->getTable(),
'entities_id',
$entity,
$item->maybeRecursive(),
);
}
$query .= " AND `" . $searchOption['field'] . "` = '$value'";
$result = $DB->doQuery($query);
if ($DB->numrows($result) > 0) {
//check if user has right on the current entity
return $DB->result($result, 0, "id");
} else {
return self::DROPDOWN_EMPTY_VALUE;
}
}
/**
* Get values to inject for an itemtype
*
* @param string $itemtype
*
* @return string|false an array with all values for this itemtype
**/
public function getValuesForItemtype($itemtype)
{
return $this->values[$itemtype] ?? false;
}
/**
* Get values to inject for an itemtype
*
* @param string $itemtype
*
* @return string|false an array with all values for this itemtype
**/
private function getValueByItemtypeAndName($itemtype, $field)
{
$values = $this->getValuesForItemtype($itemtype);
if ($values) {
return ($values[$field] ?? false);
}
return false;
}
/**
* Unset a value to inject for an itemtype
*
* @param string $itemtype
*
* @return void nothing
**/
private function unsetValue($itemtype, $field)
{
if ($this->getValueByItemtypeAndName($itemtype, $field)) {
unset($this->values[$itemtype][$field]);
}
}
/**
* Set values to inject for an itemtype
*
* @param string $itemtype
* @param string $field name
* @param string|int $value of the field
* @param boolean $fromdb boolean
**/
private function setValueForItemtype($itemtype, $field, $value, $fromdb = false)
{
if ($itemtype === User::class && $field === "pdffont" && $fromdb) {
return;
}
$injectionClass = self::getInjectionClassInstance($itemtype);
// TODO awfull hack, text ftom CSV set more than once, so check if "another" value
if (isset($this->values[$itemtype][$field]) && $this->values[$itemtype][$field] != $value) {
// Data set twice (probably CSV + Additional info)
$option = self::findSearchOption($injectionClass->getOptions($itemtype), $field);
if (isset($option['displaytype']) && $option['displaytype'] == 'multiline_text') {
// If replace_multiline_value is true, the old value is replaced with the new value
// else, the new value is added to the old value
if (!$this->rights['replace_multiline_value']) {
if ($fromdb) {
$this->values[$itemtype][$field] = $value . "\n" . $this->values[$itemtype][$field];
} else {
$this->values[$itemtype][$field] = $this->values[$itemtype][$field] . "\n" . $value;
}
}
} elseif (
($fromdb && $value && !$this->rights['overwrite_notempty_fields'])
|| !$fromdb
) {
// Overwrite value in DB (from CSV) if allowed in the model option.
$this->values[$itemtype][$field] = $value;
}
} else { // First value
$booleanFields = [
'is_dynamic',
'is_recursive',
'is_template',
'is_deleted',
'is_active',
];
if (empty($value) && $value !== 0 && $value !== '0') {
if (isForeignKeyField($field) || (str_contains($field, 'is_')) || (method_exists($injectionClass, 'isNullable') && !$injectionClass->isNullable($field))) {
//If the field concernes groupds, unseting it instead of setting it to 0 in order to avoid associating the item to a non existing group (id 0)
$group_fields = ['groups_id_tech', 'groups_id', 'groups_id_normal'];
if (in_array($field, $group_fields) && Toolbox::hasTrait($itemtype, AssignableItem::class)) {
unset($this->values[$itemtype][$field]);
} else {
// If the field is an id, we set it to 0
$this->values[$itemtype][$field] = self::DROPDOWN_EMPTY_VALUE;
}
} else {
// Else we set it to NULL
$this->values[$itemtype][$field] = self::EMPTY_VALUE;
}
} else {
$this->values[$itemtype][$field] = $value;
}
}
}
/**
* Get a template name by giving his ID
*
* @param string $itemtype the objet's type
* @param string $name the template's name
*
* @return string|false name of the template or false is no template found
**/
private static function getTemplateIDByName($itemtype, $name)
{
/** @var DBmysql $DB */
global $DB;
if (!is_a($itemtype, CommonDBTM::class, true)) {
throw new HttpException(500, 'Class ' . $itemtype . ' is not a valid class');
}