Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CItemGeneral.php « services « api « classes « include « ui - github.com/zabbix/zabbix.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6c5746e16cecfe779b7e37138661e3c857a12557 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
<?php
/*
** Zabbix
** Copyright (C) 2001-2022 Zabbix SIA
**
** This program 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.
**
** This program 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 this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


/**
 * Class containing methods for operations with item general.
 */
abstract class CItemGeneral extends CApiService {

	public const ACCESS_RULES = [
		'get' => ['min_user_type' => USER_TYPE_ZABBIX_USER],
		'create' => ['min_user_type' => USER_TYPE_ZABBIX_ADMIN],
		'update' => ['min_user_type' => USER_TYPE_ZABBIX_ADMIN],
		'delete' => ['min_user_type' => USER_TYPE_ZABBIX_ADMIN]
	];

	public const INTERFACE_TYPES_BY_PRIORITY = [
		INTERFACE_TYPE_AGENT,
		INTERFACE_TYPE_SNMP,
		INTERFACE_TYPE_JMX,
		INTERFACE_TYPE_IPMI
	];

	/**
	 * A list of supported preprocessing types.
	 *
	 * @var array
	 */
	public const SUPPORTED_PREPROCESSING_TYPES = [];

	/**
	 * A list of preprocessing types that supports the "params" field.
	 *
	 * @var array
	 */
	protected const PREPROC_TYPES_WITH_PARAMS = [];

	/**
	 * A list of preprocessing types that supports the error handling.
	 *
	 * @var array
	 */
	protected const PREPROC_TYPES_WITH_ERR_HANDLING = [];

	/**
	 * A list of supported item types.
	 *
	 * @var array
	 */
	protected const SUPPORTED_ITEM_TYPES = [];

	/**
	 * A list of field names for each of value types.
	 *
	 * @var array
	 */
	protected const VALUE_TYPE_FIELD_NAMES = [];

	/**
	 * Maximum number of inheritable items per iteration.
	 *
	 * @var int
	 */
	protected const INHERIT_CHUNK_SIZE = 1000;

	/**
	 * @abstract
	 *
	 * @param array $options
	 *
	 * @return array
	 */
	abstract public function get($options = []);

	/**
	 * @param array      $field_names
	 * @param array      $items
	 * @param array|null $db_items
	 *
	 * @throws APIException
	 */
	protected static function validateByType(array $field_names, array &$items, array $db_items = null): void {
		$checked_fields = array_fill_keys($field_names, ['type' => API_ANY]);

		foreach ($items as $i => &$item) {
			$api_input_rules = ['type' => API_OBJECT, 'fields' => $checked_fields];
			$db_item = ($db_items === null) ? null : $db_items[$item['itemid']];
			$item_type = CItemTypeFactory::getObject($item['type']);

			if ($db_item === null) {
				$api_input_rules['fields'] += $item_type::getCreateValidationRules($item);
			}
			elseif ($db_item['templateid'] != 0) {
				if ($item['type'] == ITEM_TYPE_HTTPAGENT) {
					$item += array_intersect_key($db_item, array_flip(['allow_traps']));
				}
				elseif ($item['type'] == ITEM_TYPE_SSH) {
					$item += array_intersect_key($db_item, array_flip(['authtype']));
				}

				if ($item['type'] === ITEM_TYPE_SSH && $item['authtype'] == ITEM_AUTHTYPE_PUBLICKEY
						&& $db_item['authtype'] != ITEM_AUTHTYPE_PUBLICKEY) {
					$item += array_intersect_key($db_item, array_flip(['publickey', 'privatekey']));
				}

				$api_input_rules['fields'] += $item_type::getUpdateValidationRulesInherited($db_item);
			}
			elseif ($db_item['flags'] == ZBX_FLAG_DISCOVERY_CREATED) {
				$api_input_rules['fields'] += $item_type::getUpdateValidationRulesDiscovered();
			}
			else {
				if ($item['type'] == ITEM_TYPE_HTTPAGENT) {
					$item += array_intersect_key($db_item, array_flip(
						['request_method', 'post_type', 'authtype', 'allow_traps']
					));
				}
				elseif ($item['type'] == ITEM_TYPE_SSH) {
					$item += array_intersect_key($db_item, array_flip(['authtype']));
				}

				$interfaceid_types = [ITEM_TYPE_ZABBIX, ITEM_TYPE_SIMPLE, ITEM_TYPE_EXTERNAL, ITEM_TYPE_IPMI,
					ITEM_TYPE_SSH, ITEM_TYPE_TELNET, ITEM_TYPE_JMX, ITEM_TYPE_SNMPTRAP, ITEM_TYPE_HTTPAGENT,
					ITEM_TYPE_SNMP
				];

				if (in_array($item['type'], $interfaceid_types)) {
					$opt_interface_types = [ITEM_TYPE_SIMPLE, ITEM_TYPE_EXTERNAL, ITEM_TYPE_SSH, ITEM_TYPE_TELNET,
						ITEM_TYPE_HTTPAGENT
					];

					if (in_array($db_item['host_status'], [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED])
							&& (!in_array($db_item['type'], $interfaceid_types)
								|| (in_array($item['type'], array_diff($interfaceid_types, $opt_interface_types))
									&& in_array($db_item['type'], $opt_interface_types)
									&& $db_item['interfaceid'] == 0))) {
						$item += array_intersect_key($db_item, array_flip(['interfaceid']));
					}
				}

				$username_types = [ITEM_TYPE_SIMPLE, ITEM_TYPE_DB_MONITOR, ITEM_TYPE_SSH, ITEM_TYPE_TELNET,
					ITEM_TYPE_JMX, ITEM_TYPE_HTTPAGENT
				];

				if (in_array($item['type'], [ITEM_TYPE_SSH, ITEM_TYPE_TELNET])) {
					$opt_username_types = array_diff($username_types, [ITEM_TYPE_SSH, ITEM_TYPE_TELNET]);

					if (!in_array($db_item['type'], $username_types)
							|| (in_array($db_item['type'], $opt_username_types) && $db_item['username'] === '')) {
						$item += array_intersect_key($db_item, array_flip(['username']));
					}
				}

				$params_types = [ITEM_TYPE_DB_MONITOR, ITEM_TYPE_SSH, ITEM_TYPE_TELNET, ITEM_TYPE_CALCULATED,
					ITEM_TYPE_SCRIPT
				];

				if (in_array($item['type'], $params_types) && !in_array($db_item['type'], $params_types)) {
					$item += array_intersect_key($db_item, array_flip(['params']));
				}

				$delay_types = [ITEM_TYPE_ZABBIX, ITEM_TYPE_SIMPLE, ITEM_TYPE_INTERNAL, ITEM_TYPE_ZABBIX_ACTIVE,
					ITEM_TYPE_EXTERNAL, ITEM_TYPE_DB_MONITOR, ITEM_TYPE_IPMI, ITEM_TYPE_SSH, ITEM_TYPE_TELNET,
					ITEM_TYPE_CALCULATED, ITEM_TYPE_JMX, ITEM_TYPE_HTTPAGENT, ITEM_TYPE_SNMP, ITEM_TYPE_SCRIPT
				];

				if (in_array($item['type'], $delay_types)) {
					if (!in_array($db_item['type'], $delay_types)
							|| ($db_item['type'] == ITEM_TYPE_ZABBIX_ACTIVE
								&& strncmp($db_item['key_'], 'mqtt.get', 8) === 0)) {
						$item += array_intersect_key($db_item, array_flip(['delay']));
					}
				}

				if ($item['type'] == ITEM_TYPE_DEPENDENT && $db_item['type'] != ITEM_TYPE_DEPENDENT) {
					$item += array_intersect_key($db_item, array_flip(['master_itemid']));
				}

				if ($item['type'] == ITEM_TYPE_HTTPAGENT) {
					$post_types = [ZBX_POSTTYPE_JSON, ZBX_POSTTYPE_XML];

					if (in_array($item['post_type'], $post_types) && !in_array($db_item['post_type'], $post_types)) {
						$item += array_intersect_key($db_item, array_flip(['posts']));
					}
				}

				if ($item['type'] == ITEM_TYPE_IPMI
						&& ($db_item['type'] != ITEM_TYPE_IPMI
							|| ($item['key_'] !== $db_item['key_'] && $db_item['key_'] === 'ipmi.get'))) {
					$item += array_intersect_key($db_item, array_flip(['ipmi_sensor']));
				}

				if ($item['type'] == ITEM_TYPE_JMX && $db_item['type'] != ITEM_TYPE_JMX) {
					$item += array_intersect_key($db_item, array_flip(['jmx_endpoint']));
				}

				if ($item['type'] == ITEM_TYPE_SNMP && $db_item['type'] != ITEM_TYPE_SNMP) {
					$item += array_intersect_key($db_item, array_flip(['snmp_oid']));
				}

				if ($item['type'] === ITEM_TYPE_SSH && $item['authtype'] == ITEM_AUTHTYPE_PUBLICKEY
						&& $db_item['authtype'] != ITEM_AUTHTYPE_PUBLICKEY) {
					$item += array_intersect_key($db_item, array_flip(['publickey', 'privatekey']));
				}

				$api_input_rules['fields'] += $item_type::getUpdateValidationRules($db_item);
			}

			$api_input_rules['fields'] += CItemType::getDefaultValidationRules();

			if (!CApiInputValidator::validate($api_input_rules, $item, '/'.($i + 1), $error)) {
				self::exception(ZBX_API_ERROR_PARAMETERS, $error);
			}

			if ($item['type'] == ITEM_TYPE_JMX) {
				if (array_key_exists('username', $item) || array_key_exists('password', $item)
						|| ($db_item !== null && $db_item['type'] != ITEM_TYPE_JMX)) {
					$_item = array_intersect_key($item, array_flip(['username', 'password']));

					if ($db_item === null) {
						$_item += array_fill_keys(['username', 'password'], '');
					}
					else {
						$_item += array_intersect_key($db_item, array_flip(['username', 'password']));
					}

					if (($_item['username'] === '') !== ($_item['password'] === '')) {
						self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.', '/'.($i + 1),
							_('both username and password should be either present or empty')
						));
					}
				}
			}

			if (array_key_exists('query_fields', $item)) {
				foreach ($item['query_fields'] as $query_field) {
					if (count($query_field) != 1 || key($query_field) === '') {
						self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
							'/'.($i + 1).'/query_fields', _('nonempty key and value pair expected'))
						);
					}
				}

				$item['query_fields'] = $item['query_fields'] ? json_encode($item['query_fields']) : '';

				if (strlen($item['query_fields']) > DB::getFieldLength('items', 'query_fields')) {
					self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
						'/'.($i + 1).'/query_fields', _('value is too long')
					));
				}
			}

			if (array_key_exists('headers', $item)) {
				foreach ($item['headers'] as $name => $value) {
					if (trim($name) === '' || !is_string($value) || $value === '') {
						self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
							'/'.($i + 1).'/headers', _('nonempty key and value pair expected')
						));
					}
				}

				$item['headers'] = self::headersArrayToString($item['headers']);

				if (strlen($item['headers']) > DB::getFieldLength('items', 'headers')) {
					self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
						'/'.($i + 1).'/headers', _('value is too long')
					));
				}
			}
		}
		unset($item);
	}

	/**
	 * @param array $items
	 */
	protected static function validateUniqueness(array &$items): void {
		$api_input_rules = ['type' => API_OBJECTS, 'uniq' => [['hostid', 'key_']], 'fields' => [
			'hostid' =>	['type' => API_ANY],
			'key_' =>	['type' => API_ANY]
		]];

		if (!CApiInputValidator::validateUniqueness($api_input_rules, $items, '/', $error)) {
			self::exception(ZBX_API_ERROR_PARAMETERS, $error);
		}
	}

	/**
	 * @return array
	 */
	protected static function getTagsValidationRules(): array {
		return ['type' => API_OBJECTS, 'uniq' => [['tag', 'value']], 'fields' => [
			'tag' =>	['type' => API_STRING_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY, 'length' => DB::getFieldLength('item_tag', 'tag')],
			'value' =>	['type' => API_STRING_UTF8, 'length' => DB::getFieldLength('item_tag', 'value')]
		]];
	}

	/**
	 * @param int $flags
	 *
	 * @return array
	 */
	public static function getPreprocessingValidationRules(int $flags = 0x00): array {
		return [
			'type' => API_OBJECTS,
			'uniq_by_values' => [
				['type' => [ZBX_PREPROC_DELTA_VALUE, ZBX_PREPROC_DELTA_SPEED]],
				['type' => [ZBX_PREPROC_THROTTLE_VALUE, ZBX_PREPROC_THROTTLE_TIMED_VALUE]],
				['type' => [ZBX_PREPROC_PROMETHEUS_PATTERN, ZBX_PREPROC_PROMETHEUS_TO_JSON]],
				['type' => [ZBX_PREPROC_VALIDATE_NOT_SUPPORTED]]
			],
			'fields' => [
				'type' =>					['type' => API_INT32, 'flags' => API_REQUIRED, 'in' => implode(',', static::SUPPORTED_PREPROCESSING_TYPES)],
				'params' =>					['type' => API_MULTIPLE, 'rules' => [
												['if' => ['field' => 'type', 'in' => implode(',', static::PREPROC_TYPES_WITH_PARAMS)], 'type' => API_PREPROC_PARAMS, 'flags' => API_REQUIRED | API_ALLOW_USER_MACRO | ($flags & API_ALLOW_LLD_MACRO), 'preproc_type' => ['field' => 'type'], 'length' => DB::getFieldLength('item_preproc', 'params')],
												['else' => true, 'type' => API_STRING_UTF8, 'in' => DB::getDefault('item_preproc', 'params')]
				]],
				'error_handler' =>			['type' => API_MULTIPLE, 'rules' => [
												['if' => ['field' => 'type', 'in' => implode(',', array_diff(static::PREPROC_TYPES_WITH_ERR_HANDLING, [ZBX_PREPROC_VALIDATE_NOT_SUPPORTED]))], 'type' => API_INT32, 'flags' => API_REQUIRED, 'in' => implode(',', [ZBX_PREPROC_FAIL_DEFAULT, ZBX_PREPROC_FAIL_DISCARD_VALUE, ZBX_PREPROC_FAIL_SET_VALUE, ZBX_PREPROC_FAIL_SET_ERROR])],
												['if' => ['field' => 'type', 'in' => ZBX_PREPROC_VALIDATE_NOT_SUPPORTED], 'type' => API_INT32, 'flags' => API_REQUIRED, 'in' => implode(',', [ZBX_PREPROC_FAIL_DISCARD_VALUE, ZBX_PREPROC_FAIL_SET_VALUE, ZBX_PREPROC_FAIL_SET_ERROR])],
												['else' => true, 'type' => API_INT32, 'in' => DB::getDefault('item_preproc', 'error_handler')]
				]],
				'error_handler_params' =>	['type' => API_MULTIPLE, 'rules' => [
												['if' => static function (array $data): bool {
													return array_key_exists('error_handler', $data) && $data['error_handler'] == ZBX_PREPROC_FAIL_SET_VALUE;
												},  'type' => API_STRING_UTF8, 'flags' => API_REQUIRED, 'length' => DB::getFieldLength('item_preproc', 'error_handler_params')],
												['if' => static function (array $data): bool {
													return array_key_exists('error_handler', $data) && $data['error_handler'] == ZBX_PREPROC_FAIL_SET_ERROR;
												},  'type' => API_STRING_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY, 'length' => DB::getFieldLength('item_preproc', 'error_handler_params')],
												['else' => true, 'type' => API_STRING_UTF8, 'in' => DB::getDefault('item_preproc', 'error_handler_params')]
				]]
			]
		];
	}

	/**
	 * Check that host IDs of given items are valid.
	 * If host IDs are valid, $db_hosts and $db_templates parameters will be filled with found hosts and templates.
	 *
	 * @param array      $items
	 * @param array|null $db_hosts
	 * @param array|null $db_templates
	 *
	 * @throws APIException
	 */
	protected static function checkHostsAndTemplates(array $items, array &$db_hosts = null,
			array &$db_templates = null): void {
		$hostids = array_unique(array_column($items, 'hostid'));

		$db_templates = API::Template()->get([
			'output' => [],
			'templateids' => $hostids,
			'editable' => true,
			'preservekeys' => true
		]);

		$_hostids = array_diff($hostids, array_keys($db_templates));

		$db_hosts = $_hostids
			? API::Host()->get([
				'output' => ['status'],
				'hostids' => $_hostids,
				'editable' => true,
				'preservekeys' => true
			])
			: [];

		if (count($db_templates) + count($db_hosts) != count($hostids)) {
			self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
		}
	}

	/**
	 * Add host_status property to given items in accordance of given hosts and templates statuses.
	 *
	 * @param array $items
	 * @param array $db_hosts
	 * @param array $db_templates
	 */
	protected static function addHostStatus(array &$items, array $db_hosts, array $db_templates): void {
		foreach ($items as &$item) {
			if (array_key_exists($item['hostid'], $db_templates)) {
				$item['host_status'] = HOST_STATUS_TEMPLATE;
			}
			else {
				$item['host_status'] = $db_hosts[$item['hostid']]['status'];
			}
		}
		unset($item);
	}

	/**
	 * Add flags property to given items with the given flags value.
	 *
	 * @param array $items
	 * @param int   $flags
	 */
	protected static function addFlags(array &$items, int $flags): void {
		foreach ($items as &$item) {
			$item['flags'] = $flags;
		}
		unset($item);
	}

	/**
	 * Check and add UUID to all item prototypes on templates, if it doesn't exist.
	 *
	 * @param array $items
	 *
	 * @throws APIException
	 */
	protected static function checkAndAddUuid(array &$items): void {
		foreach ($items as &$item) {
			if ($item['host_status'] == HOST_STATUS_TEMPLATE && !array_key_exists('uuid', $item)) {
				$item['uuid'] = generateUuidV4();
			}
		}
		unset($item);

		$uuids = array_column($items, 'uuid');

		if (!$uuids) {
			return;
		}

		$duplicates = DB::select('items', [
			'output' => ['uuid'],
			'filter' => ['uuid' => $uuids],
			'limit' => 1
		]);

		if ($duplicates) {
			self::exception(ZBX_API_ERROR_PARAMETERS,
				_s('Entry with UUID "%1$s" already exists.', $duplicates[0]['uuid'])
			);
		}
	}

	/**
	 * @param array      $items
	 * @param array|null $hostids
	 *
	 * @return array
	 */
	protected static function getTemplateLinks(array $items, ?array $hostids): array {
		if ($hostids !== null) {
			$db_hosts = DB::select('hosts', [
				'output' => ['hostid', 'status'],
				'hostids' => $hostids,
				'preservekeys' => true
			]);

			$tpl_links = [];

			foreach ($items as $item) {
				$tpl_links[$item['hostid']] = $db_hosts;
			}
		}
		else {
			$templateids = [];

			foreach ($items as $item) {
				if ($item['host_status'] == HOST_STATUS_TEMPLATE) {
					$templateids[$item['hostid']] = true;
				}
			}

			if (!$templateids) {
				return [];
			}

			$result = DBselect(
				'SELECT ht.templateid,ht.hostid,h.status'.
				' FROM hosts_templates ht,hosts h'.
				' WHERE ht.hostid=h.hostid'.
					' AND '.dbConditionId('ht.templateid', array_keys($templateids))
			);

			$tpl_links = [];

			while ($row = DBfetch($result)) {
				$tpl_links[$row['templateid']][$row['hostid']] = [
					'hostid' => $row['hostid'],
					'status' => $row['status']
				];
			}
		}

		return $tpl_links;
	}

	/**
	 * Filter out inheritable items from the given items.
	 *
	 * @param array $items
	 * @param array $db_items
	 * @param array $tpl_links
	 */
	protected static function filterObjectsToInherit(array &$items, array &$db_items, array $tpl_links): void {
		foreach ($items as $i => $item) {
			if (!array_key_exists($item['hostid'], $tpl_links)) {
				unset($items[$i]);

				if (array_key_exists($item['itemid'], $db_items)) {
					unset($db_items[$item['itemid']]);
				}
			}
		}
	}

	/**
	 * Check that no items with repeating keys would be inherited to a single host or template.
	 *
	 * @param array $items
	 * @param array $db_items
	 * @param array $tpl_links
	 *
	 * @throws APIException
	 */
	protected static function checkDoubleInheritedNames(array $items, array $db_items, array $tpl_links): void {
		$item_indexes = [];

		foreach ($items as $i => $item) {
			if (array_key_exists($item['itemid'], $db_items) && $item['key_'] === $db_items[$item['itemid']]['key_']) {
				continue;
			}

			$item_indexes[$item['key_']][] = $i;
		}

		foreach ($item_indexes as $key => $indexes) {
			if (count($indexes) == 1) {
				continue;
			}

			$tpl_items = array_column(array_intersect_key($items, array_flip($indexes)), null, 'hostid');
			$templateids = array_keys($tpl_items);
			$template_count = count($templateids) - 1;

			for ($i = 0; $i < $template_count - 1; $i++) {
				for ($j = $i + 1; $j < $template_count; $j++) {
					$same_hosts = array_intersect_key($tpl_links[$templateids[$i]], $tpl_links[$templateids[$j]]);

					if ($same_hosts) {
						$same_host = reset($same_hosts);

						$hosts = DB::select('hosts', [
							'output' => ['hostid', 'host'],
							'hostids' => [$templateids[$i], $templateids[$j], $same_host['hostid']],
							'preservekeys' => true
						]);

						$target_is_host = in_array($same_host['status'],
							[HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED]
						);

						switch ($tpl_items[$templateids[$i]]['flags']) {
							case ZBX_FLAG_DISCOVERY_NORMAL:
									$error = $target_is_host
									? _('Cannot inherit items with key "%1$s" of both "%2$s" and "%3$s" templates, because the key must be unique on host "%4$s".')
									: _('Cannot inherit items with key "%1$s" of both "%2$s" and "%3$s" templates, because the key must be unique on template "%4$s".');
								break;

							case ZBX_FLAG_DISCOVERY_PROTOTYPE:
								$error = $target_is_host
									? _('Cannot inherit item prototypes with key "%1$s" of both "%2$s" and "%3$s" templates, because the key must be unique on host "%4$s".')
									: _('Cannot inherit item prototypes with key "%1$s" of both "%2$s" and "%3$s" templates, because the key must be unique on template "%4$s".');
								break;

							case ZBX_FLAG_DISCOVERY_RULE:
								$error = $target_is_host
									? _('Cannot inherit LDD rules with key "%1$s" of both "%2$s" and "%3$s" templates, because the key must be unique on host "%4$s".')
									: _('Cannot inherit LDD rules with key "%1$s" of both "%2$s" and "%3$s" templates, because the key must be unique on template "%4$s".');
								break;
						}

						self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $key,
							$hosts[$templateids[$i]]['host'], $hosts[$templateids[$j]]['host'],
							$hosts[$same_host['hostid']]['host']
						));
					}
				}
			}
		}
	}

	/**
	 * Get item chunks to inherit.
	 *
	 * @param array $items
	 * @param array $tpl_links
	 *
	 * @return array
	 */
	protected static function getInheritChunks(array $items, array $tpl_links): array {
		$chunks = [
			[
				'item_indexes' => [],
				'hosts' => [],
				'size' => 0
			]
		];
		$last = 0;

		foreach ($items as $i => $item) {
			$hosts_chunks = array_chunk($tpl_links[$item['hostid']], self::INHERIT_CHUNK_SIZE, true);

			foreach ($hosts_chunks as $hosts) {
				if ($chunks[$last]['size'] < self::INHERIT_CHUNK_SIZE) {
					$_hosts = array_slice($hosts, 0, self::INHERIT_CHUNK_SIZE - $chunks[$last]['size'], true);

					$can_add_hosts = true;

					foreach ($chunks[$last]['item_indexes'] as $_i) {
						$new_hosts = array_diff_key($_hosts, $chunks[$last]['hosts']);

						if (array_intersect_key($tpl_links[$items[$_i]['hostid']], $new_hosts)) {
							$can_add_hosts = false;
							break;
						}
					}

					if ($can_add_hosts) {
						$chunks[$last]['item_indexes'][] = $i;
						$chunks[$last]['hosts'] += $_hosts;
						$chunks[$last]['size'] += count($_hosts);

						$hosts = array_diff_key($hosts, $_hosts);
					}
				}

				if ($hosts) {
					$chunks[++$last] = [
						'item_indexes' => [$i],
						'hosts' => $hosts,
						'size' => count($hosts)
					];
				}
			}
		}

		return $chunks;
	}

	/**
	 * @param array $item
	 * @param array $upd_db_item
	 *
	 * @throws APIException
	 */
	protected static function showObjectMismatchError(array $item, array $upd_db_item): void {
		$target_is_host = in_array($upd_db_item['host_status'], [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED]);

		$hosts = DB::select('hosts', [
			'output' => ['host'],
			'hostids' => [$item['hostid'], $upd_db_item['hostid']],
			'preservekeys' => true
		]);

		$error = '';

		switch ($item['flags']) {
			case ZBX_FLAG_DISCOVERY_NORMAL:
				switch ($upd_db_item['flags']) {
					case ZBX_FLAG_DISCOVERY_RULE:
						$error = $target_is_host
							? _('Cannot inherit item with key "%1$s" of template "%2$s" to host "%3$s", because an LLD rule with the same key already exists.')
							: _('Cannot inherit item with key "%1$s" of template "%2$s" to template "%3$s", because an LLD rule with the same key already exists.');
						break 2;

					case ZBX_FLAG_DISCOVERY_PROTOTYPE:
						$error = $target_is_host
							? _('Cannot inherit item with key "%1$s" of template "%2$s" to host "%3$s", because an item prototype with the same key already exists.')
							: _('Cannot inherit item with key "%1$s" of template "%2$s" to template "%3$s", because an item prototype with the same key already exists.');
						break 2;

					case ZBX_FLAG_DISCOVERY_CREATED:
						$error = $target_is_host
							? _('Cannot inherit item with key "%1$s" of template "%2$s" to host "%3$s", because a discovered item with the same key already exists.')
							: _('Cannot inherit item with key "%1$s" of template "%2$s" to template "%3$s", because a discovered item with the same key already exists.');
						break 2;
				}

			case ZBX_FLAG_DISCOVERY_RULE:
				switch ($upd_db_item['flags']) {
					case ZBX_FLAG_DISCOVERY_NORMAL:
						$error = $target_is_host
							? _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to host "%3$s", because a discovered item with the same key already exists.')
							: _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to template "%3$s", because a discovered item with the same key already exists.');
						break 2;

					case ZBX_FLAG_DISCOVERY_PROTOTYPE:
						$error = $target_is_host
							? _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to host "%3$s", because an item prototype with the same key already exists.')
							: _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to template "%3$s", because an item prototype with the same key already exists.');
						break 2;

					case ZBX_FLAG_DISCOVERY_CREATED:
						$error = $target_is_host
							? _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to host "%3$s", because a discovered item with the same key already exists.')
							: _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to template "%3$s", because a discovered item with the same key already exists.');
						break 2;
				}

			case ZBX_FLAG_DISCOVERY_PROTOTYPE:
				switch ($upd_db_item['flags']) {
					case ZBX_FLAG_DISCOVERY_NORMAL:
						$error = $target_is_host
							? _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to host "%3$s", because a discovered item with the same key already exists.')
							: _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to template "%3$s", because a discovered item with the same key already exists.');
						break 2;

					case ZBX_FLAG_DISCOVERY_RULE:
						$error = $target_is_host
							? _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to host "%3$s", because an LLD rule with the same key already exists.')
							: _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to template "%3$s", because an LLD rule with the same key already exists.');
						break 2;

					case ZBX_FLAG_DISCOVERY_CREATED:
						$error = $target_is_host
							? _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to host "%3$s", because a discovered item with the same key already exists.')
							: _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to template "%3$s", because a discovered item with the same key already exists.');
						break 2;
				}
		}

		if ($error) {
			self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $upd_db_item['key_'],
				$hosts[$item['hostid']]['host'], $hosts[$upd_db_item['hostid']]['host']
			));
		}

		if ($upd_db_item['templateid'] == 0) {
			return;
		}

		$template = DBfetch(DBselect(
			'SELECT h.host'.
			' FROM items i,hosts h'.
			' WHERE i.hostid=h.hostid'.
				' AND '.dbConditionId('i.itemid', [$upd_db_item['templateid']])
		));

		switch ($item['flags']) {
			case ZBX_FLAG_DISCOVERY_NORMAL:
				$error = $target_is_host
					? _('Cannot inherit item with key "%1$s" of template "%2$s" to host "%3$s", because an item with the same key is already inherited from template "%4$s".')
					: _('Cannot inherit item with key "%1$s" of template "%2$s" to template "%3$s", because an item with the same key is already inherited from template "%4$s".');
				break;

			case ZBX_FLAG_DISCOVERY_RULE:
				$error = $target_is_host
					? _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to host "%3$s", because an item with the same key is already inherited from template "%4$s".')
					: _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to template "%3$s", because an item with the same key is already inherited from template "%4$s".');
				break;

			case ZBX_FLAG_DISCOVERY_PROTOTYPE:
				$error = $target_is_host
					? _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to host "%3$s", because an item with the same key is already inherited from template "%4$s".')
					: _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to template "%3$s", because an item with the same key is already inherited from template "%4$s".');
				break;
		}

		self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $upd_db_item['key_'], $hosts[$item['hostid']]['host'],
			$hosts[$upd_db_item['hostid']]['host'], $template['host']
		));
	}

	/**
	 * @param array $item
	 *
	 * @return array
	 */
	protected static function unsetNestedObjectIds(array $item): array {
		if (array_key_exists('tags', $item)) {
			foreach ($item['tags'] as &$tag) {
				unset($tag['itemtagid']);
			}
			unset($tag);
		}

		if (array_key_exists('preprocessing', $item)) {
			foreach ($item['preprocessing'] as &$preprocessing) {
				unset($preprocessing['item_preprocid']);
			}
			unset($preprocessing);
		}

		if (array_key_exists('parameters', $item)) {
			foreach ($item['parameters'] as &$parameter) {
				unset($parameter['item_parameterid']);
			}
			unset($parameter);
		}

		return $item;
	}

	/**
	 * Update relation to master item for inherited dependent items.
	 *
	 * @param array $upd_items
	 * @param array $ins_items
	 * @param array $hostids
	 */
	protected static function setChildMasterItemIds(array &$upd_items, array &$ins_items, array $hostids): void {
		$upd_item_indexes = [];
		$ins_item_indexes = [];

		foreach ($upd_items as $i => $upd_item) {
			if ($upd_item['type'] == ITEM_TYPE_DEPENDENT && array_key_exists('master_itemid', $upd_item)) {
				$upd_item_indexes[$upd_item['master_itemid']][$upd_item['hostid']][] = $i;
			}
		}

		foreach ($ins_items as $i => $ins_item) {
			if ($ins_item['type'] == ITEM_TYPE_DEPENDENT) {
				$ins_item_indexes[$ins_item['master_itemid']][$ins_item['hostid']][] = $i;
			}
		}

		if (!$upd_item_indexes && !$ins_item_indexes) {
			return;
		}

		$options = [
			'output' => ['itemid', 'hostid', 'templateid'],
			'filter' => [
				'templateid' => array_keys($ins_item_indexes + $upd_item_indexes),
				'hostid' => $hostids
			]
		];
		$result = DBselect(DB::makeSql('items', $options));

		while ($row = DBfetch($result)) {
			if (array_key_exists($row['templateid'], $upd_item_indexes)
					&& array_key_exists($row['hostid'], $upd_item_indexes[$row['templateid']])) {
				foreach ($upd_item_indexes[$row['templateid']][$row['hostid']] as $i) {
					$upd_items[$i]['master_itemid'] = $row['itemid'];
				}
			}

			if (array_key_exists($row['templateid'], $ins_item_indexes)
					&& array_key_exists($row['hostid'], $ins_item_indexes[$row['templateid']])) {
				foreach ($ins_item_indexes[$row['templateid']][$row['hostid']] as $i) {
					$ins_items[$i]['master_itemid'] = $row['itemid'];
				}
			}
		}
	}

	/**
	 * @param array $upd_items
	 * @param array $upd_db_items
	 * @param array $ins_items
	 *
	 * @throws APIException
	 */
	protected static function addInterfaceIds(array &$upd_items, array $upd_db_items, array &$ins_items): void {
		$upd_item_indexes = [];
		$ins_item_indexes = [];
		$interface_types = [];

		$required_interface_types = [INTERFACE_TYPE_AGENT, INTERFACE_TYPE_SNMP, INTERFACE_TYPE_IPMI,
			INTERFACE_TYPE_JMX
		];

		$upd_item_indexes_by_interfaceid = [];

		foreach ($upd_items as $i => $upd_item) {
			if (!in_array($upd_item['host_status'], [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED])) {
				continue;
			}

			$interface_type = itemTypeInterface($upd_item['type']);

			if (!in_array($interface_type, $required_interface_types)) {
				continue;
			}

			if ($upd_db_items[$upd_item['itemid']]['interfaceid'] != 0) {
				$upd_item_indexes_by_interfaceid[$upd_db_items[$upd_item['itemid']]['interfaceid']][] = $i;
			}
			else {
				$upd_item_indexes[$upd_item['hostid']][$interface_type][] = $i;
				$interface_types[$interface_type] = true;
			}
		}

		if ($upd_item_indexes_by_interfaceid) {
			$options = [
				'output' => ['interfaceid', 'type'],
				'interfaceids' => array_keys($upd_item_indexes_by_interfaceid)
			];
			$result = DBselect(DB::makeSql('interface', $options));

			while ($row = DBfetch($result)) {
				foreach ($upd_item_indexes_by_interfaceid[$row['interfaceid']] as $i) {
					$upd_item = $upd_items[$i];
					$interface_type = itemTypeInterface($upd_item['type']);

					if ($interface_type != $row['type']) {
						$upd_item_indexes[$upd_item['hostid']][$interface_type][] = $i;
						$interface_types[$interface_type] = true;
					}
				}
			}
		}

		foreach ($ins_items as $i => $ins_item) {
			if (!in_array($ins_item['host_status'], [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED])) {
				continue;
			}

			$interface_type = itemTypeInterface($ins_item['type']);

			if (!in_array($interface_type, $required_interface_types)) {
				continue;
			}

			$ins_item_indexes[$ins_item['hostid']][$interface_type][] = $i;
			$interface_types[$interface_type] = true;
		}

		if (!$upd_item_indexes && !$ins_item_indexes) {
			return;
		}

		$options = [
			'output' => ['interfaceid', 'hostid', 'type'],
			'filter' => [
				'hostid' => array_keys($upd_item_indexes + $ins_item_indexes),
				'type' => array_keys($interface_types),
				'main' => INTERFACE_PRIMARY
			]
		];
		$result = DBselect(DB::makeSql('interface', $options));

		while ($row = DBfetch($result)) {
			if (array_key_exists($row['hostid'], $upd_item_indexes)
					&& array_key_exists($row['type'], $upd_item_indexes[$row['hostid']])) {
				foreach ($upd_item_indexes[$row['hostid']][$row['type']] as $_i => $i) {
					$upd_items[$i]['interfaceid'] = $row['interfaceid'];

					unset($upd_item_indexes[$row['hostid']][$row['type']][$_i]);
				}

				if (!$upd_item_indexes[$row['hostid']][$row['type']]) {
					unset($upd_item_indexes[$row['hostid']][$row['type']]);
				}

				if (!$upd_item_indexes[$row['hostid']]) {
					unset($upd_item_indexes[$row['hostid']]);
				}
			}

			if (array_key_exists($row['hostid'], $ins_item_indexes)
					&& array_key_exists($row['type'], $ins_item_indexes[$row['hostid']])) {
				foreach ($ins_item_indexes[$row['hostid']][$row['type']] as $_i => $i) {
					$ins_items[$i]['interfaceid'] = $row['interfaceid'];

					unset($ins_item_indexes[$row['hostid']][$row['type']][$_i]);
				}

				if (!$ins_item_indexes[$row['hostid']][$row['type']]) {
					unset($ins_item_indexes[$row['hostid']][$row['type']]);
				}

				if (!$ins_item_indexes[$row['hostid']]) {
					unset($ins_item_indexes[$row['hostid']]);
				}
			}
		}

		$item = null;

		if ($upd_item_indexes) {
			$hostid = key($upd_item_indexes);
			$interface_type = key($upd_item_indexes[$hostid]);
			$i = reset($upd_item_indexes[$hostid][$interface_type]);

			$item = $upd_items[$i];
		}
		elseif ($ins_item_indexes) {
			$hostid = key($ins_item_indexes);
			$interface_type = key($ins_item_indexes[$hostid]);
			$i = reset($ins_item_indexes[$hostid][$interface_type]);

			$item = $ins_items[$i];
		}

		if ($item === null) {
			return;
		}

		$templates = DBfetchArray(DBselect(
			'SELECT h.host'.
			' FROM items i,hosts h'.
			' WHERE i.hostid=h.hostid'.
				' AND '.dbConditionId('i.itemid', [$item['templateid']])
		));

		$hosts = DB::select('hosts', [
			'output' => ['host'],
			'hostids' => $item['hostid']
		]);

		switch ($item['flags']) {
			case ZBX_FLAG_DISCOVERY_NORMAL:
				$error = _('Cannot inherit item with key "%1$s" of template "%2$s" to host "%3$s", because a host interface of type "%4$s" is required.');
				break;

			case ZBX_FLAG_DISCOVERY_CREATED:
				$error = _('Cannot inherit LLD rule with key "%1$s" of template "%2$s" to host "%3$s", because a host interface of type "%4$s" is required.');
				break;

			case ZBX_FLAG_DISCOVERY_PROTOTYPE:
				$error = _('Cannot inherit item prototype with key "%1$s" of template "%2$s" to host "%3$s", because a host interface of type "%4$s" is required.');
				break;
		}

		self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $item['key_'], $templates[0]['host'],
			$hosts[0]['host'], interfaceType2str($interface_type)
		));
	}

	/**
	 * Inherit dependent items in nesting order.
	 *
	 * @param array $dep_items_to_link[<master item index>][<dependent item index>]
	 * @param array $items_to_link
	 * @param array $hostids
	 */
	protected static function inheritDependentItems(array $dep_items_to_link, array $items_to_link,
			array $hostids): void {
		while ($dep_items_to_link) {
			$items = [];

			foreach ($dep_items_to_link as $i => $_items) {
				if (array_key_exists($i, $items_to_link)) {
					$items += $_items;
					unset($dep_items_to_link[$i]);
				}
			}

			static::inherit(array_values($items), [], $hostids, true);

			$items_to_link = $items;
		}
	}

	/**
	 * @param array      $items
	 * @param array      $db_items
	 * @param array|null $hostids
	 * @param bool       $is_dep_items  Inherit called for dependent items.
	 */
	abstract protected static function inherit(array $items, array $db_items = [], array $hostids = null,
			bool $is_dep_items = false): void;

	/**
	 * Add default values for fields that became unnecessary as the result of the change of the type fields.
	 *
	 * @param array $items
	 * @param array $db_items
	 */
	protected static function addFieldDefaultsByType(array &$items, array $db_items): void {
		$type_field_defaults = [
			// The fields used for multiple item types.
			'interfaceid' => 0,
			'authtype' => DB::getDefault('items', 'authtype'),
			'username' => DB::getDefault('items', 'username'),
			'password' => DB::getDefault('items', 'password'),
			'params' => DB::getDefault('items', 'params'),
			'timeout' => DB::getDefault('items', 'timeout'),
			'delay' => DB::getDefault('items', 'delay'),
			'trapper_hosts' => DB::getDefault('items', 'trapper_hosts'),

			// Dependent item type specific fields.
			'master_itemid' => 0,

			// HTTP Agent item type specific fields.
			'url' => DB::getDefault('items', 'url'),
			'query_fields' => DB::getDefault('items', 'query_fields'),
			'request_method' => DB::getDefault('items', 'request_method'),
			'post_type' => DB::getDefault('items', 'post_type'),
			'posts' => DB::getDefault('items', 'posts'),
			'headers' => DB::getDefault('items', 'headers'),
			'status_codes' => DB::getDefault('items', 'status_codes'),
			'follow_redirects' => DB::getDefault('items', 'follow_redirects'),
			'retrieve_mode' => DB::getDefault('items', 'retrieve_mode'),
			'output_format' => DB::getDefault('items', 'output_format'),
			'http_proxy' => DB::getDefault('items', 'http_proxy'),
			'verify_peer' => DB::getDefault('items', 'verify_peer'),
			'verify_host' => DB::getDefault('items', 'verify_host'),
			'ssl_cert_file' => DB::getDefault('items', 'ssl_cert_file'),
			'ssl_key_file' => DB::getDefault('items', 'ssl_key_file'),
			'ssl_key_password' => DB::getDefault('items', 'ssl_key_password'),
			'allow_traps' => DB::getDefault('items', 'allow_traps'),

			// IPMI item type specific fields.
			'ipmi_sensor' => DB::getDefault('items', 'ipmi_sensor'),

			// JMX item type specific fields.
			'jmx_endpoint' => DB::getDefault('items', 'jmx_endpoint'),

			// Script item type specific fields.
			'parameters' => [],

			// SNMP item type specific fields.
			'snmp_oid' => DB::getDefault('items', 'snmp_oid'),

			// SSH item type specific fields.
			'publickey' => DB::getDefault('items', 'publickey'),
			'privatekey' => DB::getDefault('items', 'privatekey')
		];

		$value_type_field_defaults = [
			'units' => DB::getDefault('items', 'units'),
			'trends' => DB::getDefault('items', 'trends'),
			'valuemapid' => 0,
			'logtimefmt' => DB::getDefault('items', 'logtimefmt'),
			'inventory_link' => DB::getDefault('items', 'inventory_link')
		];

		foreach ($items as &$item) {
			if (!array_key_exists('type', $db_items[$item['itemid']])) {
				continue;
			}

			$db_item = $db_items[$item['itemid']];

			if ($item['type'] != $db_item['type']) {
				$type_field_names = CItemTypeFactory::getObject($item['type'])::FIELD_NAMES;
				$db_type_field_names = CItemTypeFactory::getObject($db_item['type'])::FIELD_NAMES;

				$field_names = array_flip(array_diff($db_type_field_names, $type_field_names));

				if ($item['type'] == ITEM_TYPE_ZABBIX_ACTIVE && strncmp($item['key_'], 'mqtt.get', 8) == 0) {
					$field_names += array_flip(['delay']);
				}

				if (array_intersect([$item['type'], $db_item['type']], [ITEM_TYPE_SSH, ITEM_TYPE_HTTPAGENT])) {
					$field_names += array_flip(['authtype']);
				}

				if ($item['host_status'] == HOST_STATUS_TEMPLATE && array_key_exists('interfaceid', $field_names)) {
					unset($field_names['interfaceid']);
				}

				$item += array_intersect_key($type_field_defaults, $field_names);
			}
			elseif ($item['type'] == ITEM_TYPE_ZABBIX_ACTIVE) {
				if (array_key_exists('key_', $item) && $item['key_'] !== $db_item['key_']
						&& strncmp($item['key_'], 'mqtt.get', 8) == 0) {
					$item += array_intersect_key($type_field_defaults, array_flip(['delay']));
				}
			}
			elseif ($item['type'] == ITEM_TYPE_SSH) {
				if (array_key_exists('authtype', $item) && $item['authtype'] !== $db_item['authtype']
						&& $item['authtype'] == ITEM_AUTHTYPE_PASSWORD) {
					$item += array_intersect_key($type_field_defaults, array_flip(['publickey', 'privatekey']));
				}
			}
			elseif ($item['type'] == ITEM_TYPE_HTTPAGENT) {
				if (array_key_exists('request_method', $item) && $item['request_method'] != $db_item['request_method']
						&& $item['request_method'] == HTTPCHECK_REQUEST_HEAD) {
					$item += ['retrieve_mode' => HTTPTEST_STEP_RETRIEVE_MODE_HEADERS];
				}

				if (array_key_exists('authtype', $item) && $item['authtype'] != $db_item['authtype']
						&& $item['authtype'] == HTTPTEST_AUTH_NONE) {
					$item += array_intersect_key($type_field_defaults, array_flip(['username', 'password']));
				}

				if (array_key_exists('allow_traps', $item) && $item['allow_traps'] != $db_item['allow_traps']
						&& $item['allow_traps'] == HTTPCHECK_ALLOW_TRAPS_OFF) {
					$item += array_intersect_key($type_field_defaults, array_flip(['trapper_hosts']));
				}
			}

			if (array_key_exists('value_type', $item) && $item['value_type'] != $db_item['value_type']) {
				$type_field_names = static::VALUE_TYPE_FIELD_NAMES[$item['value_type']];
				$db_type_field_names = static::VALUE_TYPE_FIELD_NAMES[$db_item['value_type']];

				$field_names = array_flip(array_diff($db_type_field_names, $type_field_names));

				if (array_key_exists('trends', $field_names)) {
					$item += ['trends' => 0];
				}

				$item += array_intersect_key($value_type_field_defaults, $field_names);
			}
		}
		unset($item);
	}

	/**
	 * @param array      $items
	 * @param array|null $db_items
	 * @param array|null $upd_itemids
	 */
	protected static function updateParameters(array &$items, array $db_items = null,
			array &$upd_itemids = null): void {
		$ins_item_parameters = [];
		$upd_item_parameters = [];
		$del_item_parameterids = [];

		foreach ($items as $i => &$item) {
			$update = false;

			if ($db_items === null) {
				if ($item['type'] == ITEM_TYPE_SCRIPT && array_key_exists('parameters', $item) && $item['parameters']) {
					$update = true;
				}
			}
			else {
				if (!array_key_exists('type', $db_items[$item['itemid']])) {
					continue;
				}

				if ($item['type'] == ITEM_TYPE_SCRIPT) {
					if (array_key_exists('parameters', $item)) {
						$update = true;
					}
				}
				elseif ($db_items[$item['itemid']]['type'] == ITEM_TYPE_SCRIPT
						&& $db_items[$item['itemid']]['parameters']) {
					$update = true;
				}
			}

			if (!$update) {
				continue;
			}

			$changed = false;
			$db_item_parameters = ($db_items !== null)
				? array_column($db_items[$item['itemid']]['parameters'], null, 'name')
				: [];

			foreach ($item['parameters'] as &$item_parameter) {
				if (array_key_exists($item_parameter['name'], $db_item_parameters)) {
					$db_item_parameter = $db_item_parameters[$item_parameter['name']];
					$item_parameter['item_parameterid'] = $db_item_parameter['item_parameterid'];
					unset($db_item_parameters[$db_item_parameter['name']]);

					$upd_item_parameter = DB::getUpdatedValues('item_parameter', $item_parameter, $db_item_parameter);

					if ($upd_item_parameter) {
						$upd_item_parameters[] = [
							'values' => $upd_item_parameter,
							'where' => ['item_parameterid' => $db_item_parameter['item_parameterid']]
						];
						$changed = true;
					}
				}
				else {
					$ins_item_parameters[] = ['itemid' => $item['itemid']] + $item_parameter;
					$changed = true;
				}
			}
			unset($item_parameter);

			if ($db_item_parameters) {
				$del_item_parameterids =
					array_merge($del_item_parameterids, array_column($db_item_parameters, 'item_parameterid'));
				$changed = true;
			}

			if ($db_items !== null) {
				if ($changed) {
					$upd_itemids[$i] = $item['itemid'];
				}
				else {
					unset($item['parameters']);
				}
			}
		}
		unset($item);

		if ($del_item_parameterids) {
			DB::delete('item_parameter', ['item_parameterid' => $del_item_parameterids]);
		}

		if ($upd_item_parameters) {
			DB::update('item_parameter', $upd_item_parameters);
		}

		if ($ins_item_parameters) {
			$item_parameterids = DB::insert('item_parameter', $ins_item_parameters);
		}

		foreach ($items as &$item) {
			if (!array_key_exists('parameters', $item)) {
				continue;
			}

			foreach ($item['parameters'] as &$item_parameter) {
				if (!array_key_exists('item_parameterid', $item_parameter)) {
					$item_parameter['item_parameterid'] = array_shift($item_parameterids);
				}
			}
			unset($item_parameter);
		}
		unset($item);
	}

	/**
	 * @param array      $items
	 * @param array|null $db_items
	 * @param array|null $upd_itemids
	 */
	protected static function updatePreprocessing(array &$items, array $db_items = null,
			array &$upd_itemids = null): void {
		$ins_item_preprocs = [];
		$upd_item_preprocs = [];
		$del_item_preprocids = [];

		foreach ($items as $i => &$item) {
			if (!array_key_exists('preprocessing', $item)) {
				continue;
			}

			$changed = false;
			$db_item_preprocs = ($db_items !== null)
				? array_column($db_items[$item['itemid']]['preprocessing'], null, 'step')
				: [];

			$step = 1;

			foreach ($item['preprocessing'] as &$item_preproc) {
				$item_preproc['step'] = ($item_preproc['type'] == ZBX_PREPROC_VALIDATE_NOT_SUPPORTED) ? 0 : $step++;

				if (array_key_exists($item_preproc['step'], $db_item_preprocs)) {
					$db_item_preproc = $db_item_preprocs[$item_preproc['step']];
					$item_preproc['item_preprocid'] = $db_item_preproc['item_preprocid'];
					unset($db_item_preprocs[$db_item_preproc['step']]);

					$upd_item_preproc = DB::getUpdatedValues('item_preproc', $item_preproc, $db_item_preproc);

					if ($upd_item_preproc) {
						$upd_item_preprocs[] = [
							'values' => $upd_item_preproc,
							'where' => ['item_preprocid' => $db_item_preproc['item_preprocid']]
						];
						$changed = true;
					}
				}
				else {
					$ins_item_preprocs[] = ['itemid' => $item['itemid']] + $item_preproc;
					$changed = true;
				}
			}
			unset($item_preproc);

			if ($db_item_preprocs) {
				$del_item_preprocids =
					array_merge($del_item_preprocids, array_column($db_item_preprocs, 'item_preprocid'));
				$changed = true;
			}

			if ($db_items !== null) {
				if ($changed) {
					$upd_itemids[$i] = $item['itemid'];
				}
				else {
					unset($item['preprocessing']);
				}
			}
		}
		unset($item);

		if ($del_item_preprocids) {
			DB::delete('item_preproc', ['item_preprocid' => $del_item_preprocids]);
		}

		if ($upd_item_preprocs) {
			DB::update('item_preproc', $upd_item_preprocs);
		}

		if ($ins_item_preprocs) {
			$item_preprocids = DB::insert('item_preproc', $ins_item_preprocs);
		}

		foreach ($items as &$item) {
			if (!array_key_exists('preprocessing', $item)) {
				continue;
			}

			foreach ($item['preprocessing'] as &$item_preproc) {
				if (!array_key_exists('item_preprocid', $item_preproc)) {
					$item_preproc['item_preprocid'] = array_shift($item_preprocids);
				}
			}
			unset($item_preproc);
		}
		unset($item);
	}

	/**
	 * @param array      $items
	 * @param array|null $db_items
	 * @param array|null $upd_itemids
	 */
	protected static function updateTags(array &$items, array $db_items = null, array &$upd_itemids = null): void {
		$ins_tags = [];
		$del_itemtagids = [];

		foreach ($items as $i => &$item) {
			if (!array_key_exists('tags', $item)) {
				continue;
			}

			$changed = false;
			$db_tags = ($db_items !== null) ? $db_items[$item['itemid']]['tags'] : [];

			foreach ($item['tags'] as &$tag) {
				$db_itemtagid = key(array_filter($db_tags, static function (array $db_tag) use ($tag): bool {
					return $tag['tag'] === $db_tag['tag']
						&& (!array_key_exists('value', $tag) || $tag['value'] === $db_tag['value']);
				}));

				if ($db_itemtagid !== null) {
					$tag['itemtagid'] = $db_itemtagid;
					unset($db_tags[$db_itemtagid]);
				}
				else {
					$ins_tags[] = ['itemid' => $item['itemid']] + $tag;
					$changed = true;
				}
			}
			unset($tag);

			if ($db_tags) {
				$del_itemtagids = array_merge($del_itemtagids, array_keys($db_tags));
				$changed = true;
			}

			if ($db_items !== null) {
				if ($changed) {
					$upd_itemids[$i] = $item['itemid'];
				}
				else {
					unset($item['tags']);
				}
			}
		}
		unset($item);

		if ($del_itemtagids) {
			DB::delete('item_tag', ['itemtagid' => $del_itemtagids]);
		}

		if ($ins_tags) {
			$itemtagids = DB::insert('item_tag', $ins_tags);
		}

		foreach ($items as &$item) {
			if (!array_key_exists('tags', $item)) {
				continue;
			}

			foreach ($item['tags'] as &$tag) {
				if (!array_key_exists('itemtagid', $tag)) {
					$tag['itemtagid'] = array_shift($itemtagids);
				}
			}
			unset($tag);
		}
		unset($item);
	}

	/**
	 * Check for unique item keys.
	 *
	 * @param array      $items
	 * @param array|null $db_items
	 *
	 * @throws APIException if item keys are not unique.
	 */
	protected static function checkDuplicates(array $items, array $db_items = null): void {
		$host_keys = [];

		foreach ($items as $item) {
			if ($db_items === null || $item['key_'] !== $db_items[$item['itemid']]['key_']) {
				$host_keys[$item['hostid']][] = $item['key_'];
			}
		}

		if (!$host_keys) {
			return;
		}

		$where = [];
		foreach ($host_keys as $hostid => $keys) {
			$where[] = '('.dbConditionId('i.hostid', [$hostid]).' AND '.dbConditionString('i.key_', $keys).')';
		}

		$duplicates = DBfetchArray(DBselect(
			'SELECT i.key_,i.flags,h.host,h.status'.
			' FROM items i,hosts h'.
			' WHERE i.hostid=h.hostid'.
				' AND ('.implode(' OR ', $where).')',
			1
		));

		if ($duplicates) {
			$target_is_template = ($duplicates[0]['status'] == HOST_STATUS_TEMPLATE);

			switch ($duplicates[0]['flags']) {
				case ZBX_FLAG_DISCOVERY_NORMAL:
				case ZBX_FLAG_DISCOVERY_CREATED:
					$error = $target_is_template
						? _('An item with key "%1$s" already exists on the template "%2$s".')
						: _('An item with key "%1$s" already exists on the host "%2$s".');
					break;

				case ZBX_FLAG_DISCOVERY_PROTOTYPE:
					$error = $target_is_template
						? _('An item prototype with key "%1$s" already exists on the template "%2$s".')
						: _('An item prototype with key "%1$s" already exists on the host "%2$s".');
					break;

				case ZBX_FLAG_DISCOVERY_RULE:
					$error = $target_is_template
						? _('An LLD rule with key "%1$s" already exists on the template "%2$s".')
						: _('An LLD rule with key "%1$s" already exists on the host "%2$s".');
					break;
			}

			self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $duplicates[0]['key_'], $duplicates[0]['host']));
		}
	}

	/**
	 * @param array      $items
	 * @param array|null $db_items
	 *
	 * @throws APIException
	 */
	protected static function checkHostInterfaces(array $items, array $db_items = null): void {
		foreach ($items as $i => &$item) {
			$interface_type = itemTypeInterface($item['type']);

			if (!in_array($item['host_status'], [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED])
					|| $interface_type === false) {
				unset($items[$i]);
				continue;
			}

			$check = false;

			if ($db_items === null) {
				if (array_key_exists('interfaceid', $item)) {
					if ($item['interfaceid'] != 0) {
						$check = true;
					}
					elseif ($interface_type != INTERFACE_TYPE_OPT) {
						self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
							'/'.($i + 1).'/interfaceid', _('the host interface ID is expected')
						));
					}
				}
			}
			else {
				$db_item = $db_items[$item['itemid']];

				if ($item['type'] == $db_item['type']) {
					if (array_key_exists('interfaceid', $item)) {
						if ($item['interfaceid'] != 0) {
							if (bccomp($item['interfaceid'], $db_item['interfaceid']) != 0) {
								$check = true;
							}
						}
						elseif ($interface_type != INTERFACE_TYPE_OPT) {
							self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
								'/'.($i + 1).'/interfaceid', _('the host interface ID is expected')
							));
						}
					}
				}
				else {
					$db_interface_type = itemTypeInterface($db_item['type']);

					if (array_key_exists('interfaceid', $item)) {
						if ($item['interfaceid'] != 0) {
							if (bccomp($item['interfaceid'], $db_item['interfaceid']) != 0
									|| ($interface_type != INTERFACE_TYPE_OPT
										&& $interface_type != $db_interface_type)) {
								$check = true;
							}
						}
						elseif ($interface_type != INTERFACE_TYPE_OPT) {
							self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
								'/'.($i + 1).'/interfaceid', _('the host interface ID is expected')
							));
						}
					}
					else {
						if ($db_item['interfaceid'] != 0) {
							if ($interface_type != INTERFACE_TYPE_OPT && $interface_type != $db_interface_type) {
								$item += ['interfaceid' => $db_item['interfaceid']];

								$check = true;
							}
						}
						elseif ($interface_type != INTERFACE_TYPE_OPT) {
							self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
								'/'.($i + 1), _s('the parameter "%1$s" is missing', 'interfaceid')
							));
						}
					}
				}
			}

			if (!$check) {
				unset($items[$i]);
			}
		}
		unset($item);

		if (!$items) {
			return;
		}

		$db_interfaces = DB::select('interface', [
			'output' => ['interfaceid', 'hostid', 'type'],
			'interfaceids' => array_unique(array_column($items, 'interfaceid')),
			'preservekeys' => true
		]);

		foreach ($items as $i => $item) {
			if (!array_key_exists($item['interfaceid'], $db_interfaces)) {
				self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
					'/'.($i + 1).'/interfaceid', _('the host interface ID is expected')
				));
			}

			if (bccomp($db_interfaces[$item['interfaceid']]['hostid'], $item['hostid']) != 0) {
				self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
					'/'.($i + 1).'/interfaceid', _('cannot be the host interface ID from another host')
				));
			}

			$interface_type = itemTypeInterface($item['type']);

			if ($interface_type != INTERFACE_TYPE_OPT
					&& $db_interfaces[$item['interfaceid']]['type'] != $interface_type) {
				self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
					'/'.($i + 1).'/interfaceid',
					_s('the host interface ID of type "%1$s" is expected', interfaceType2str($interface_type))
				));
			}
		}
	}

	protected function addRelatedObjects(array $options, array $result) {
		$result = parent::addRelatedObjects($options, $result);

		// adding hosts
		if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) {
			$relationMap = $this->createRelationMap($result, 'itemid', 'hostid');
			$hosts = API::Host()->get([
				'hostids' => $relationMap->getRelatedIds(),
				'templated_hosts' => true,
				'output' => $options['selectHosts'],
				'nopermissions' => true,
				'preservekeys' => true
			]);
			$result = $relationMap->mapMany($result, $hosts, 'hosts');
		}

		// adding preprocessing
		if ($options['selectPreprocessing'] !== null && $options['selectPreprocessing'] != API_OUTPUT_COUNT) {
			$db_item_preproc = API::getApiService()->select('item_preproc', [
				'output' => $this->outputExtend($options['selectPreprocessing'], ['itemid', 'step']),
				'filter' => ['itemid' => array_keys($result)]
			]);

			CArrayHelper::sort($db_item_preproc, ['step']);

			foreach ($result as &$item) {
				$item['preprocessing'] = [];
			}
			unset($item);

			foreach ($db_item_preproc as $step) {
				$itemid = $step['itemid'];
				unset($step['item_preprocid'], $step['itemid'], $step['step']);

				if (array_key_exists($itemid, $result)) {
					$result[$itemid]['preprocessing'][] = $step;
				}
			}
		}

		// Add value mapping.
		if (($this instanceof CItemPrototype || $this instanceof CItem) && $options['selectValueMap'] !== null) {
			if ($options['selectValueMap'] === API_OUTPUT_EXTEND) {
				$options['selectValueMap'] = ['valuemapid', 'name', 'mappings'];
			}

			foreach ($result as &$item) {
				$item['valuemap'] = [];
			}
			unset($item);

			$valuemaps = DB::select('valuemap', [
				'output' => array_diff($this->outputExtend($options['selectValueMap'], ['valuemapid', 'hostid']),
					['mappings']
				),
				'filter' => ['valuemapid' => array_keys(array_flip(array_column($result, 'valuemapid')))],
				'preservekeys' => true
			]);

			if ($this->outputIsRequested('mappings', $options['selectValueMap']) && $valuemaps) {
				$params = [
					'output' => ['valuemapid', 'type', 'value', 'newvalue'],
					'filter' => ['valuemapid' => array_keys($valuemaps)],
					'sortfield' => ['sortorder']
				];
				$query = DBselect(DB::makeSql('valuemap_mapping', $params));

				while ($mapping = DBfetch($query)) {
					$valuemaps[$mapping['valuemapid']]['mappings'][] = [
						'type' => $mapping['type'],
						'value' => $mapping['value'],
						'newvalue' => $mapping['newvalue']
					];
				}
			}

			foreach ($result as &$item) {
				if (array_key_exists('valuemapid', $item) && array_key_exists($item['valuemapid'], $valuemaps)) {
					$item['valuemap'] = array_intersect_key($valuemaps[$item['valuemapid']],
						array_flip($options['selectValueMap'])
					);
				}
			}
			unset($item);
		}

		if (!$options['countOutput'] && $this->outputIsRequested('parameters', $options['output'])) {
			$item_parameters = DBselect(
				'SELECT ip.itemid,ip.name,ip.value'.
				' FROM item_parameter ip'.
				' WHERE '.dbConditionInt('ip.itemid', array_keys($result))
			);

			foreach ($result as &$item) {
				$item['parameters'] = [];
			}
			unset($item);

			while ($row = DBfetch($item_parameters)) {
				$result[$row['itemid']]['parameters'][] = [
					'name' =>  $row['name'],
					'value' =>  $row['value']
				];
			}
		}

		return $result;
	}

	/**
	 * Check that dependent items of given items are valid.
	 *
	 * @param array $items
	 * @param array $db_items
	 * @param bool  $inherited
	 *
	 * @throws APIException
	 */
	protected static function checkDependentItems(array $items, array $db_items = [], bool $inherited = false): void {
		$del_links = [];

		foreach ($items as $i => $item) {
			$check = false;

			if ($item['type'] == ITEM_TYPE_DEPENDENT) {
				if (!array_key_exists('itemid', $item)) {
					if ($item['master_itemid'] != 0) {
						$check = true;
					}
					else {
						$error = $item['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE
							? _('an item/item prototype ID is expected')
							: _('an item ID is expected');

						self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
							'/'.($i + 1).'/master_itemid', $error
						));
					}
				}
				else {
					if (array_key_exists('master_itemid', $item)) {
						if ($item['master_itemid'] != 0) {
							if (bccomp($item['master_itemid'], $db_items[$item['itemid']]['master_itemid']) != 0) {
								$check = true;

								if ($db_items[$item['itemid']]['master_itemid'] != 0) {
									$del_links[$item['itemid']] = $db_items[$item['itemid']]['master_itemid'];
								}
							}
						}
						else {
							$error = $item['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE
								? _('an item/item prototype ID is expected')
								: _('an item ID is expected');

							self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
								'/'.($i + 1).'/master_itemid', $error
							));
						}
					}
				}
			}
			elseif (array_key_exists('itemid', $item) && $db_items[$item['itemid']]['type'] == ITEM_TYPE_DEPENDENT) {
				$del_links[$item['itemid']] = $db_items[$item['itemid']]['master_itemid'];
			}

			if (!$check) {
				unset($items[$i]);
			}
		}

		if (!$items) {
			return;
		}

		if (!$inherited) {
			self::checkMasterItems($items, $db_items);
		}

		$dep_item_links = self::getDependentItemLinks($items, $del_links);

		if (!$inherited && $db_items) {
			self::checkCircularDependencies($items, $dep_item_links);
		}

		$root_itemids = [];

		foreach ($dep_item_links as $itemid => $master_itemid) {
			if ($master_itemid == 0) {
				$root_itemids[] = $itemid;
			}
		}

		$master_item_links = self::getMasterItemLinks($items, $root_itemids, $del_links);

		foreach ($root_itemids as $root_itemid) {
			if (self::maxDependencyLevelExceeded($master_item_links, $root_itemid, $links_path)) {
				[$flags, $key, $master_flags, $master_key, $is_template, $host] =
					self::getProblemCausedItemData($links_path, $items);

				$error = self::getDependentItemError($flags, $master_flags, $is_template);

				self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $key, $master_key, $host,
					_('allowed count of dependency levels would be exceeded')
				));
			}

			if (self::maxDependentItemCountExceeded($master_item_links, $root_itemid, $links_path)) {
				[$flags, $key, $master_flags, $master_key, $is_template, $host] =
					self::getProblemCausedItemData($links_path, $items);

				$error = self::getDependentItemError($flags, $master_flags, $is_template);

				self::exception(ZBX_API_ERROR_PARAMETERS, sprintf($error, $key, $master_key, $host,
					_('allowed count of dependent items would be exceeded')
				));
			}
		}
	}

	/**
	 * Check that master item IDs of given dependent items are valid.
	 *
	 * @param array $items
	 * @param array $db_items
	 *
	 * @throws APIException
	 */
	private static function checkMasterItems(array $items, array $db_items): void {
		$master_itemids = array_unique(array_column($items, 'master_itemid'));
		$flags = $items[key($items)]['flags'];

		if ($flags == ZBX_FLAG_DISCOVERY_PROTOTYPE) {
			$db_master_items = DBfetchArrayAssoc(DBselect(
				'SELECT i.itemid,i.hostid,i.master_itemid,i.flags,id.parent_itemid AS ruleid'.
				' FROM items i'.
				' LEFT JOIN item_discovery id ON i.itemid=id.itemid'.
				' WHERE '.dbConditionId('i.itemid', $master_itemids).
					' AND '.dbConditionInt('i.flags', [ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_PROTOTYPE])
			), 'itemid');
		}
		else {
			$db_master_items = DB::select('items', [
				'output' => ['itemid', 'hostid', 'master_itemid'],
				'itemids' => $master_itemids,
				'filter' => [
					'flags' => ZBX_FLAG_DISCOVERY_NORMAL
				],
				'preservekeys' => true
			]);
		}

		foreach ($items as $i => $item) {
			if (!array_key_exists($item['master_itemid'], $db_master_items)) {
				$error = $flags == ZBX_FLAG_DISCOVERY_PROTOTYPE
					? _('an item/item prototype ID is expected')
					: _('an item ID is expected');

				self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
					'/'.($i + 1).'/master_itemid', $error
				));
			}

			$db_master_item = $db_master_items[$item['master_itemid']];

			if (bccomp($db_master_item['hostid'], $item['hostid']) != 0) {
				$error = $flags == ZBX_FLAG_DISCOVERY_PROTOTYPE
					? _('cannot be an item/item prototype ID from another host or template')
					: _('cannot be an item ID from another host or template');

				self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
					'/'.($i + 1).'/master_itemid', $error
				));
			}

			if ($flags == ZBX_FLAG_DISCOVERY_PROTOTYPE && $db_master_item['ruleid'] != 0) {
				$item_ruleid = array_key_exists('itemid', $item)
					? $db_items[$item['itemid']]['ruleid']
					: $item['ruleid'];

				if (bccomp($db_master_item['ruleid'], $item_ruleid) != 0) {
					self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
						'/'.($i + 1).'/master_itemid', _('cannot be an item prototype ID from another LLD rule')
					));
				}
			}
		}
	}

	/**
	 * Get dependent item links starting from the given dependent items and till the highest dependency level.
	 *
	 * @param  array $items
	 * @param  array $del_links
	 *
	 * @return array  Array of the links where each key contain the ID of dependent item and value contain the
	 *                appropriate ID of the master item.
	 */
	private static function getDependentItemLinks(array $items, array $del_links): array {
		$links = array_column($items, 'master_itemid', 'itemid');
		$master_itemids = array_flip(array_column($items, 'master_itemid'));

		while ($master_itemids) {
			$options = [
				'output' => ['itemid', 'hostid', 'master_itemid'],
				'itemids' => array_keys($master_itemids)
			];
			$db_master_items = DBselect(DB::makeSql('items', $options));

			$master_itemids = [];

			while ($db_master_item = DBfetch($db_master_items)) {
				if (array_key_exists($db_master_item['itemid'], $del_links)
						&& bccomp($db_master_item['master_itemid'], $del_links[$db_master_item['itemid']]) == 0) {
					$links[$db_master_item['itemid']] = 0;
					continue;
				}

				$links[$db_master_item['itemid']] = $db_master_item['master_itemid'];

				if ($db_master_item['master_itemid'] != 0) {
					$master_itemids[$db_master_item['master_itemid']] = true;
				}
			}
		}

		return $links;
	}

	/**
	 * Check that the changed master item IDs of dependent items do not create a circular dependencies.
	 *
	 * @param array $items
	 * @param array $dep_item_links
	 *
	 * @throws APIException
	 */
	private static function checkCircularDependencies(array $items, array $dep_item_links): void {
		foreach ($items as $i => $item) {
			$master_itemid = $item['master_itemid'];

			while ($master_itemid != 0) {
				if (bccomp($master_itemid, $item['itemid']) == 0) {
					self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
						'/'.($i + 1).'/master_itemid', _('circular item dependency is not allowed')
					));
				}

				$master_itemid = $dep_item_links[$master_itemid];
			}
		}
	}

	/**
	 * Get master item links starting from the given master items and till the lowest level master items.
	 *
	 * @param  array $items
	 * @param  array $master_itemids
	 * @param  array $del_links
	 *
	 * @return array  Array of the links where each key contain the ID of master item and value contain the array of
	 *                appropriate dependent item IDs.
	 */
	private static function getMasterItemLinks(array $items, array $master_itemids, array $del_links): array {
		$ins_links = [];
		$upd_item_links = [];

		foreach ($items as $item) {
			if (array_key_exists('itemid', $item)) {
				$upd_item_links[$item['master_itemid']][] = $item['itemid'];
			}
			else {
				$ins_links[$item['master_itemid']][] = 0;
			}
		}

		$links = [];

		do {
			$options = [
				'output' => ['master_itemid', 'itemid'],
				'filter' => [
					'master_itemid' => $master_itemids
				]
			];
			$db_items = DBselect(DB::makeSql('items', $options));

			$_master_itemids = [];

			while ($db_item = DBfetch($db_items)) {
				if (array_key_exists($db_item['itemid'], $del_links)
						&& bccomp($db_item['master_itemid'], $del_links[$db_item['itemid']]) == 0) {
					continue;
				}

				$links[$db_item['master_itemid']][] = $db_item['itemid'];
				$_master_itemids[] = $db_item['itemid'];
			}

			foreach ($master_itemids as $master_itemid) {
				if (array_key_exists($master_itemid, $upd_item_links)) {
					foreach ($upd_item_links[$master_itemid] as $itemid) {
						$_master_itemids[] = $itemid;
						$links[$master_itemid][] = $itemid;
					}
				}
			}

			$master_itemids = $_master_itemids;
		} while ($master_itemids);

		foreach ($ins_links as $master_itemid => $ins_items) {
			$links[$master_itemid] = array_key_exists($master_itemid, $links)
				? array_merge($links[$master_itemid], $ins_items)
				: $ins_items;
		}

		return $links;
	}

	/**
	 * Check whether maximum number of dependency levels is exceeded.
	 *
	 * @param array      $master_item_links
	 * @param string     $master_itemid
	 * @param array|null $links_path
	 * @param int        $level
	 *
	 * @return bool
	 */
	private static function maxDependencyLevelExceeded(array $master_item_links, string $master_itemid,
			array &$links_path = null, int $level = 0): bool {
		if (!array_key_exists($master_itemid, $master_item_links)) {
			return false;
		}

		if ($links_path === null) {
			$links_path = [];
		}

		$links_path[] = $master_itemid;
		$level++;

		if ($level > ZBX_DEPENDENT_ITEM_MAX_LEVELS) {
			return true;
		}

		foreach ($master_item_links[$master_itemid] as $itemid) {
			$_links_path = $links_path;

			if (self::maxDependencyLevelExceeded($master_item_links, $itemid, $_links_path, $level)) {
				$links_path = $_links_path;

				return true;
			}
		}

		return false;
	}


	/**
	 * Check whether maximum count of dependent items is exceeded.
	 *
	 * @param array      $master_item_links
	 * @param string     $master_itemid
	 * @param array|null $links_path
	 * @param int        $count
	 *
	 * @return bool
	 */
	private static function maxDependentItemCountExceeded(array $master_item_links, string $master_itemid,
			array &$links_path = null, int &$count = 0): bool {
		if (!array_key_exists($master_itemid, $master_item_links)) {
			return false;
		}

		if ($links_path === null) {
			$links_path = [];
		}

		$links_path[] = $master_itemid;
		$count += count($master_item_links[$master_itemid]);

		if ($count > ZBX_DEPENDENT_ITEM_MAX_COUNT) {
			return true;
		}

		foreach ($master_item_links[$master_itemid] as $itemid) {
			$_links_path = $links_path;

			if (self::maxDependentItemCountExceeded($master_item_links, $itemid, $_links_path, $count)) {
				$links_path = $_links_path;

				return true;
			}
		}

		return false;
	}

	/**
	 * Get data for a dependent item that causes a problem, based on the given path where the problem was detected.
	 *
	 * @param array $links_path
	 * @param array $items
	 *
	 * @return array
	 */
	private static function getProblemCausedItemData(array $links_path, array $items): array {
		foreach ($items as $item) {
			if (in_array($item['master_itemid'], $links_path)) {
				break;
			}
		}

		$master_item_data = DBfetch(DBselect(
			'SELECT i.flags,i.key_,h.host'.
			' FROM items i,hosts h'.
			' WHERE i.hostid=h.hostid'.
				' AND '.dbConditionId('i.itemid', [$item['master_itemid']])
		));

		$flags = $item['flags'];
		$key = $item['key_'];
		$master_flags = $master_item_data['flags'];
		$master_key = $master_item_data['key_'];
		$is_template = $item['host_status'] == HOST_STATUS_TEMPLATE;
		$host = $master_item_data['host'];

		return [$flags, $key, $master_flags, $master_key, $is_template, $host];
	}

	/**
	 * Get the error message about problem with dependent item according to given data.
	 *
	 * @param int  $flags
	 * @param int  $master_flags
	 * @param bool $is_template
	 *
	 * @return string
	 */
	private static function getDependentItemError(int $flags, int $master_flags, bool $is_template): string {
		if ($flags == ZBX_FLAG_DISCOVERY_NORMAL) {
			return $is_template
				? _('Cannot set dependency for item with key "%1$s" on the master item with key "%2$s" on the template "%3$s": %4$s.')
				: _('Cannot set dependency for item with key "%1$s" on the master item with key "%2$s" on the host "%3$s": %4$s.');
		}
		elseif ($flags == ZBX_FLAG_DISCOVERY_PROTOTYPE) {
			if ($master_flags == ZBX_FLAG_DISCOVERY_NORMAL) {
				return $is_template
					? _('Cannot set dependency for item prototype with key "%1$s" on the master item with key "%2$s" on the template "%3$s": %4$s.')
					: _('Cannot set dependency for item prototype with key "%1$s" on the master item with key "%2$s" on the host "%3$s": %4$s.');
			}
			else {
				return $is_template
					? _('Cannot set dependency for item prototype with key "%1$s" on the master item prototype with key "%2$s" on the template "%3$s": %4$s.')
					: _('Cannot set dependency for item prototype with key "%1$s" on the master item prototype with key "%2$s" on the host "%3$s": %4$s.');
			}
		}
		elseif ($flags == ZBX_FLAG_DISCOVERY_RULE) {
			return $is_template
				? _('Cannot set dependency for LLD rule with key "%1$s" on the master item with key "%2$s" on the template "%3$s": %4$s.')
				: _('Cannot set dependency for LLD rule with key "%1$s" on the master item with key "%2$s" on the host "%3$s": %4$s.');
		}
	}

	/**
	 * Converts headers field text to hash with header name as key.
	 *
	 * @param string $headers  Headers string, one header per line, line delimiter "\r\n".
	 *
	 * @return array
	 */
	protected static function headersStringToArray(string $headers): array {
		$result = [];

		foreach (explode("\r\n", $headers) as $header) {
			$header = explode(': ', $header, 2);

			if (count($header) == 2) {
				$result[$header[0]] = $header[1];
			}
		}

		return $result;
	}

	/**
	 * Converts headers fields hash to string.
	 *
	 * @param array $headers  Array of headers where key is header name.
	 *
	 * @return string
	 */
	protected static function headersArrayToString(array $headers): string {
		$result = [];

		foreach ($headers as $k => $v) {
			$result[] = $k.': '.$v;
		}

		return implode("\r\n", $result);
	}

	/**
	 * Remove NCLOB value type fields from resulting query SELECT part if DISTINCT will be used.
	 *
	 * @param string $table_name     Table name.
	 * @param string $table_alias    Table alias value.
	 * @param array  $options        Array of query options.
	 * @param array  $sql_parts      Array of query parts already initialized from $options.
	 *
	 * @return array    The resulting SQL parts array.
	 */
	protected function applyQueryOutputOptions($table_name, $table_alias, array $options, array $sql_parts) {
		if (!$options['countOutput'] && self::dbDistinct($sql_parts)) {
			$schema = $this->getTableSchema();
			$nclob_fields = [];

			foreach ($schema['fields'] as $field_name => $field) {
				if ($field['type'] == DB::FIELD_TYPE_NCLOB
						&& $this->outputIsRequested($field_name, $options['output'])) {
					$nclob_fields[] = $field_name;
				}
			}

			if ($nclob_fields) {
				$output = ($options['output'] === API_OUTPUT_EXTEND)
					? array_keys($schema['fields'])
					: $options['output'];

				$options['output'] = array_diff($output, $nclob_fields);
			}
		}

		return parent::applyQueryOutputOptions($table_name, $table_alias, $options, $sql_parts);
	}

	/**
	 * Add NCLOB type fields if there was DISTINCT in query.
	 *
	 * @param array $options    Array of query options.
	 * @param array $result     Query results.
	 *
	 * @return array    The result array with added NCLOB fields.
	 */
	protected function addNclobFieldValues(array $options, array $result): array {
		$schema = $this->getTableSchema();
		$nclob_fields = [];

		foreach ($schema['fields'] as $field_name => $field) {
			if ($field['type'] == DB::FIELD_TYPE_NCLOB && $this->outputIsRequested($field_name, $options['output'])) {
				$nclob_fields[] = $field_name;
			}
		}

		if (!$nclob_fields) {
			return $result;
		}

		$pk = $schema['key'];
		$options = [
			'output' => $nclob_fields,
			'filter' => [$pk => array_keys($result)]
		];

		$db_items = DBselect(DB::makeSql($this->tableName, $options));

		while ($db_item = DBfetch($db_items)) {
			$result[$db_item[$pk]] += $db_item;
		}

		return $result;
	}

	/**
	 * Check that valuemap belong to same host as item.
	 *
	 * @param array      $items
	 * @param array|null $db_items
	 *
	 * @throws APIException
	 */
	protected static function checkValueMaps(array $items, array $db_items = null): void {
		$item_indexes = [];

		foreach ($items as $i => $item) {
			if (array_key_exists('valuemapid', $item) && $item['valuemapid'] != 0
					&& ($db_items === null
						|| bccomp($item['valuemapid'], $db_items[$item['itemid']]['valuemapid']) != 0)) {
				$item_indexes[$item['valuemapid']][] = $i;
			}
		}

		if (!$item_indexes) {
			return;
		}

		$options = [
			'output' => ['valuemapid', 'hostid'],
			'valuemapids' => array_keys($item_indexes)
		];
		$db_valuemaps = DBselect(DB::makeSql('valuemap', $options));

		while ($db_valuemap = DBfetch($db_valuemaps)) {
			foreach ($item_indexes[$db_valuemap['valuemapid']] as $i) {
				if (bccomp($db_valuemap['hostid'], $items[$i]['hostid']) != 0) {
					self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.',
						'/'.($i + 1).'/valuemapid', _('cannot be a value map ID from another host or template')
					));
				}
			}
		}
	}

	/**
	 * Add the internally used fields to the given $db_items.
	 *
	 * @param array $db_items
	 */
	protected static function addInternalFields(array &$db_items): void {
		$result = DBselect(
			'SELECT i.itemid,i.hostid,i.templateid,i.flags,h.status AS host_status'.
			' FROM items i,hosts h'.
			' WHERE i.hostid=h.hostid'.
				' AND '.dbConditionId('i.itemid', array_keys($db_items))
		);

		while ($row = DBfetch($result)) {
			$db_items[$row['itemid']] += $row;
		}
	}

	/**
	 * Note: instances may override this to add e.g. tags.
	 *
	 * @param array $items
	 * @param array $db_items
	 */
	protected static function addAffectedObjects(array $items, array &$db_items): void {
		self::addAffectedTags($items, $db_items);
		self::addAffectedPreprocessing($items, $db_items);
		self::addAffectedParameters($items, $db_items);
	}

	/**
	 * @param array $items
	 * @param array $db_items
	 */
	protected static function addAffectedTags(array $items, array &$db_items): void {
		$itemids = [];

		foreach ($items as $item) {
			if (array_key_exists('tags', $item)) {
				$itemids[] = $item['itemid'];
				$db_items[$item['itemid']]['tags'] = [];
			}
		}

		if (!$itemids) {
			return;
		}

		$options = [
			'output' => ['itemtagid', 'itemid', 'tag', 'value'],
			'filter' => ['itemid' => $itemids]
		];
		$db_item_tags = DBselect(DB::makeSql('item_tag', $options));

		while ($db_item_tag = DBfetch($db_item_tags)) {
			$db_items[$db_item_tag['itemid']]['tags'][$db_item_tag['itemtagid']] =
				array_diff_key($db_item_tag, array_flip(['itemid']));
		}
	}

	/**
	 * @param array $items
	 * @param array $db_items
	 */
	protected static function addAffectedPreprocessing(array $items, array &$db_items): void {
		$itemids = [];

		foreach ($items as $item) {
			if (array_key_exists('preprocessing', $item)) {
				$itemids[] = $item['itemid'];
				$db_items[$item['itemid']]['preprocessing'] = [];
			}
		}

		if (!$itemids) {
			return;
		}

		$options = [
			'output' => [
				'item_preprocid', 'itemid', 'step', 'type', 'params', 'error_handler', 'error_handler_params'
			],
			'filter' => ['itemid' => $itemids]
		];
		$db_item_preprocs = DBselect(DB::makeSql('item_preproc', $options));

		while ($db_item_preproc = DBfetch($db_item_preprocs)) {
			$db_items[$db_item_preproc['itemid']]['preprocessing'][$db_item_preproc['item_preprocid']] =
				array_diff_key($db_item_preproc, array_flip(['itemid']));
		}
	}

	/**
	 * @param array $items
	 * @param array $db_items
	 */
	protected static function addAffectedParameters(array $items, array &$db_items): void {
		$itemids = [];

		foreach ($items as $item) {
			$db_type = $db_items[$item['itemid']]['type'];

			if ((array_key_exists('parameters', $item) && $item['type'] == ITEM_TYPE_SCRIPT)
					|| ($item['type'] != $db_type && $db_type == ITEM_TYPE_SCRIPT)) {
				$itemids[] = $item['itemid'];
				$db_items[$item['itemid']]['parameters'] = [];
			}
			elseif (array_key_exists('parameters', $item)) {
				$db_items[$item['itemid']]['parameters'] = [];
			}
		}

		if (!$itemids) {
			return;
		}

		$options = [
			'output' => ['item_parameterid', 'itemid', 'name', 'value'],
			'filter' => ['itemid' => $itemids]
		];
		$db_item_parameters = DBselect(DB::makeSql('item_parameter', $options));

		while ($db_item_parameter = DBfetch($db_item_parameters)) {
			$db_items[$db_item_parameter['itemid']]['parameters'][$db_item_parameter['item_parameterid']] =
				array_diff_key($db_item_parameter, array_flip(['itemid']));
		}
	}

	/**
	 * Add the inherited items of the given items to the given item array.
	 *
	 * @param array $db_items
	 */
	public static function addInheritedItems(array &$db_items): void {
		$templateids = array_keys($db_items);

		do {
			$options = [
				'output' => ['itemid', 'name'],
				'filter' => ['templateid' => $templateids]
			];
			$result = DBselect(DB::makeSql('items', $options));

			$templateids = [];

			while ($row = DBfetch($result)) {
				if (!array_key_exists($row['itemid'], $db_items)) {
					$templateids[] = $row['itemid'];

					$db_items[$row['itemid']] = $row;
				}
			}
		} while ($templateids);
	}

	/**
	 * Reset the MIN and MAX values of Y axis in the graphs, if such are calculated using the given items.
	 *
	 * @param array $del_itemids
	 */
	protected static function resetGraphsYAxis(array $del_itemids): void {
		DB::update('graphs', [
			'values' => [
				'ymin_type' => GRAPH_YAXIS_TYPE_CALCULATED,
				'ymin_itemid' => null
			],
			'where' => ['ymin_itemid' => $del_itemids]
		]);

		DB::update('graphs', [
			'values' => [
				'ymax_type' => GRAPH_YAXIS_TYPE_CALCULATED,
				'ymax_itemid' => null
			],
			'where' => ['ymax_itemid' => $del_itemids]
		]);
	}

	/**
	 * Delete triggers and trigger prototypes, which contain the given items in the expression.
	 *
	 * @param array $del_itemids
	 */
	protected static function deleteAffectedTriggers(array $del_itemids): void {
		$result = DBselect(
			'SELECT DISTINCT f.triggerid,t.flags'.
			' FROM functions f,triggers t'.
			' WHERE f.triggerid=t.triggerid'.
				' AND '.dbConditionInt('f.itemid', $del_itemids)
		);

		$del_trigger_prototypeids = [];
		$del_triggerids = [];

		while ($row = DBfetch($result)) {
			if ($row['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE) {
				$del_trigger_prototypeids[] = $row['triggerid'];
			}
			else {
				$del_triggerids[] = $row['triggerid'];
			}
		}

		if ($del_triggerids) {
			CTriggerManager::delete($del_triggerids);
		}

		if ($del_trigger_prototypeids) {
			CTriggerPrototypeManager::delete($del_trigger_prototypeids);
		}
	}
}