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
|
<?php
/*
** Zabbix
** Copyright (C) 2001-2019 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 {
const ERROR_EXISTS_TEMPLATE = 'existsTemplate';
const ERROR_EXISTS = 'exists';
const ERROR_NO_INTERFACE = 'noInterface';
const ERROR_INVALID_KEY = 'invalidKey';
protected $fieldRules;
/**
* @abstract
*
* @param array $options
*
* @return array
*/
abstract public function get($options = []);
public function __construct() {
parent::__construct();
// template - if templated item, value is taken from template item, cannot be changed on host
// system - values should not be updated
// host - value should be null for template items
$this->fieldRules = [
'type' => ['template' => 1],
'snmp_community' => [],
'snmp_oid' => ['template' => 1],
'hostid' => [],
'name' => ['template' => 1],
'description' => [],
'key_' => ['template' => 1],
'master_itemid' => ['template' => 1],
'delay' => [],
'history' => [],
'trends' => [],
'status' => [],
'value_type' => ['template' => 1],
'trapper_hosts' => [],
'units' => ['template' => 1],
'snmpv3_contextname' => [],
'snmpv3_securityname' => [],
'snmpv3_securitylevel' => [],
'snmpv3_authprotocol' => [],
'snmpv3_authpassphrase' => [],
'snmpv3_privprotocol' => [],
'snmpv3_privpassphrase' => [],
'formula' => ['template' => 1],
'error' => ['system' => 1],
'lastlogsize' => ['system' => 1],
'logtimefmt' => [],
'templateid' => ['system' => 1],
'valuemapid' => ['template' => 1],
'params' => [],
'ipmi_sensor' => ['template' => 1],
'authtype' => [],
'username' => [],
'password' => [],
'publickey' => [],
'privatekey' => [],
'mtime' => ['system' => 1],
'flags' => [],
'filter' => [],
'interfaceid' => ['host' => 1],
'port' => [],
'inventory_link' => [],
'lifetime' => [],
'preprocessing' => ['template' => 1],
'jmx_endpoint' => [],
'master_itemid' => ['template' => 1],
'url' => ['template' => 1],
'timeout' => ['template' => 1],
'query_fields' => ['template' => 1],
'posts' => ['template' => 1],
'status_codes' => ['template' => 1],
'follow_redirects' => ['template' => 1],
'post_type' => ['template' => 1],
'http_proxy' => ['template' => 1],
'headers' => ['template' => 1],
'retrieve_mode' => ['template' => 1],
'request_method' => ['template' => 1],
'output_format' => ['template' => 1],
'allow_traps' => [],
'ssl_cert_file' => ['template' => 1],
'ssl_key_file' => ['template' => 1],
'ssl_key_password' => ['template' => 1],
'verify_peer' => ['template' => 1],
'verify_host' => ['template' => 1]
];
$this->errorMessages = array_merge($this->errorMessages, [
self::ERROR_NO_INTERFACE => _('Cannot find host interface on "%1$s" for item key "%2$s".')
]);
}
/**
* Check items data.
*
* Any system field passed to the function will be unset.
*
* @throw APIException
*
* @param array $items passed by reference
* @param bool $update
*/
protected function checkInput(array &$items, $update = false) {
if ($update) {
$itemDbFields = ['itemid' => null];
$dbItemsFields = ['itemid', 'templateid'];
foreach ($this->fieldRules as $field => $rule) {
if (!isset($rule['system'])) {
$dbItemsFields[] = $field;
}
}
$dbItems = $this->get([
'output' => $dbItemsFields,
'itemids' => zbx_objectValues($items, 'itemid'),
'editable' => true,
'preservekeys' => true
]);
$dbHosts = API::Host()->get([
'output' => ['hostid', 'status', 'name'],
'hostids' => zbx_objectValues($dbItems, 'hostid'),
'templated_hosts' => true,
'editable' => true,
'selectApplications' => ['applicationid', 'flags'],
'preservekeys' => true
]);
}
else {
$itemDbFields = [
'name' => null,
'key_' => null,
'hostid' => null,
'type' => null,
'value_type' => null,
'delay' => null
];
$dbHosts = API::Host()->get([
'output' => ['hostid', 'status', 'name'],
'hostids' => zbx_objectValues($items, 'hostid'),
'templated_hosts' => true,
'editable' => true,
'selectApplications' => ['applicationid', 'flags'],
'preservekeys' => true
]);
$discovery_rules = [];
if ($this instanceof CItemPrototype) {
$itemDbFields['ruleid'] = null;
$druleids = zbx_objectValues($items, 'ruleid');
if ($druleids) {
$discovery_rules = API::DiscoveryRule()->get([
'output' => ['hostid'],
'itemids' => $druleids,
'preservekeys' => true
]);
}
}
}
// interfaces
$interfaces = API::HostInterface()->get([
'output' => ['interfaceid', 'hostid', 'type'],
'hostids' => zbx_objectValues($dbHosts, 'hostid'),
'nopermissions' => true,
'preservekeys' => true
]);
if ($update) {
$updateDiscoveredValidator = new CUpdateDiscoveredValidator([
'allowed' => ['itemid', 'status'],
'messageAllowedField' => _('Cannot update "%2$s" for a discovered item "%1$s".')
]);
foreach ($items as &$item) {
// check permissions
if (!array_key_exists($item['itemid'], $dbItems)) {
self::exception(ZBX_API_ERROR_PERMISSIONS,
_('No permissions to referred object or it does not exist!')
);
}
$dbItem = $dbItems[$item['itemid']];
if (array_key_exists('hostid', $item) && bccomp($dbItem['hostid'], $item['hostid']) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'hostid', _('cannot be changed'))
);
}
$itemName = array_key_exists('name', $item) ? $item['name'] : $dbItem['name'];
// discovered fields, except status, cannot be updated
$updateDiscoveredValidator->setObjectName($itemName);
$this->checkPartialValidator($item, $updateDiscoveredValidator, $dbItem);
$item += [
'hostid' => $dbItem['hostid'],
'type' => $dbItem['type'],
'name' => $dbItem['name'],
'key_' => $dbItem['key_'],
'flags' => $dbItem['flags']
];
}
unset($item);
}
$item_key_parser = new CItemKey();
$ip_range_parser = new CIPRangeParser([
'v6' => ZBX_HAVE_IPV6,
'ranges' => false,
'usermacros' => true,
'macros' => [
'{HOST.HOST}', '{HOSTNAME}', '{HOST.NAME}', '{HOST.CONN}', '{HOST.IP}', '{IPADDRESS}', '{HOST.DNS}'
]
]);
$update_interval_parser = new CUpdateIntervalParser([
'usermacros' => true,
'lldmacros' => (get_class($this) === 'CItemPrototype')
]);
foreach ($items as $inum => &$item) {
$item = $this->clearValues($item);
$fullItem = $items[$inum];
if (!check_db_fields($itemDbFields, $item)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
if ($update) {
$type = array_key_exists('type', $item) ? $item['type'] : $dbItems[$item['itemid']]['type'];
if ($type == ITEM_TYPE_HTTPAGENT) {
$this->validateHTTPCheck($fullItem, $dbItems[$item['itemid']]);
}
check_db_fields($dbItems[$item['itemid']], $fullItem);
$this->checkNoParameters(
$item,
['templateid', 'state'],
_('Cannot update "%1$s" for item "%2$s".'),
$item['name']
);
// apply rules
foreach ($this->fieldRules as $field => $rules) {
if ((0 != $fullItem['templateid'] && isset($rules['template'])) || isset($rules['system'])) {
unset($item[$field]);
// For templated item and fields that should not be modified, use the value from DB.
if (array_key_exists($field, $dbItems[$item['itemid']])
&& array_key_exists($field, $fullItem)) {
$fullItem[$field] = $dbItems[$item['itemid']][$field];
}
}
}
if (!isset($item['key_'])) {
$item['key_'] = $fullItem['key_'];
}
if (!isset($item['hostid'])) {
$item['hostid'] = $fullItem['hostid'];
}
// if a templated item is being assigned to an interface with a different type, ignore it
$itemInterfaceType = itemTypeInterface($dbItems[$item['itemid']]['type']);
if ($fullItem['templateid'] && isset($item['interfaceid']) && isset($interfaces[$item['interfaceid']])
&& $itemInterfaceType !== INTERFACE_TYPE_ANY && $interfaces[$item['interfaceid']]['type'] != $itemInterfaceType) {
unset($item['interfaceid']);
}
}
else {
if ($fullItem['type'] == ITEM_TYPE_HTTPAGENT) {
$this->validateHTTPCheck($fullItem, []);
}
if (!isset($dbHosts[$item['hostid']])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
}
check_db_fields($itemDbFields, $fullItem);
$this->checkNoParameters(
$item,
['templateid', 'state'],
_('Cannot set "%1$s" for item "%2$s".'),
$item['name']
);
if ($this instanceof CItemPrototype && (!array_key_exists($fullItem['ruleid'], $discovery_rules)
|| $discovery_rules[$fullItem['ruleid']]['hostid'] != $fullItem['hostid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('No permissions to referred object or it does not exist!')
);
}
}
$host = $dbHosts[$fullItem['hostid']];
// Validate update interval.
if (!in_array($fullItem['type'], [ITEM_TYPE_TRAPPER, ITEM_TYPE_SNMPTRAP, ITEM_TYPE_DEPENDENT])) {
if ($update_interval_parser->parse($fullItem['delay']) != CParser::PARSE_SUCCESS) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'delay', _('invalid delay'))
);
}
$delay = $update_interval_parser->getDelay();
// Check if not macros. If delay is a macro, skip this step, otherwise check if delay is valid.
if ($delay[0] !== '{') {
$delay_sec = timeUnitToSeconds($delay);
$intervals = $update_interval_parser->getIntervals();
$flexible_intervals = $update_interval_parser->getIntervals(ITEM_DELAY_FLEXIBLE);
$has_scheduling_intervals = (bool) $update_interval_parser->getIntervals(ITEM_DELAY_SCHEDULING);
$has_macros = false;
foreach ($intervals as $interval) {
if (strpos($interval['interval'], '{') !== false) {
$has_macros = true;
break;
}
}
// If delay is 0, there must be at least one either flexible or scheduling interval.
if ($delay_sec == 0 && !$intervals) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Item will not be refreshed. Specified update interval requires having at least one either flexible or scheduling interval.')
);
}
elseif ($delay_sec < 0 || $delay_sec > SEC_PER_DAY) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Item will not be refreshed. Update interval should be between 1s and 1d. Also Scheduled/Flexible intervals can be used.')
);
}
if ($fullItem['type'] == ITEM_TYPE_ZABBIX_ACTIVE) {
// Remove flexible and scheduling intervals and leave only the delay part.
$item['delay'] = $delay;
}
// If there are scheduling intervals or intervals with macros, skip the next check calculation.
elseif (!$has_macros && !$has_scheduling_intervals && $flexible_intervals
&& calculateItemNextCheck(0, $delay_sec, $flexible_intervals, time()) == ZBX_JAN_2038) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Item will not be refreshed. Please enter a correct update interval.')
);
}
}
elseif ($fullItem['type'] == ITEM_TYPE_ZABBIX_ACTIVE) {
// Remove flexible and scheduling intervals and leave only the delay part.
$item['delay'] = $delay;
}
}
// For non-numeric types, whichever value was entered in trends field, is overwritten to zero.
if ($fullItem['value_type'] == ITEM_VALUE_TYPE_STR || $fullItem['value_type'] == ITEM_VALUE_TYPE_LOG
|| $fullItem['value_type'] == ITEM_VALUE_TYPE_TEXT) {
$item['trends'] = '0';
}
// check if the item requires an interface
if ($host['status'] == HOST_STATUS_TEMPLATE) {
unset($item['interfaceid']);
}
else {
$itemInterfaceType = itemTypeInterface($fullItem['type']);
if ($itemInterfaceType !== false) {
if (!array_key_exists('interfaceid', $fullItem) || !$fullItem['interfaceid']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No interface found.'));
}
elseif (!isset($interfaces[$fullItem['interfaceid']]) || bccomp($interfaces[$fullItem['interfaceid']]['hostid'], $fullItem['hostid']) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Item uses host interface from non-parent host.'));
}
elseif ($itemInterfaceType !== INTERFACE_TYPE_ANY && $interfaces[$fullItem['interfaceid']]['type'] != $itemInterfaceType) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Item uses incorrect interface type.'));
}
}
// no interface required, just set it to null
else {
$item['interfaceid'] = 0;
}
}
// item key
if ($fullItem['type'] == ITEM_TYPE_DB_MONITOR) {
if (!isset($fullItem['flags']) || $fullItem['flags'] != ZBX_FLAG_DISCOVERY_RULE) {
if (strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_DB_MONITOR) == 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Check the key, please. Default example was passed.')
);
}
}
elseif ($fullItem['flags'] == ZBX_FLAG_DISCOVERY_RULE) {
if (strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_DB_MONITOR_DISCOVERY) == 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Check the key, please. Default example was passed.')
);
}
}
}
elseif (($fullItem['type'] == ITEM_TYPE_SSH && strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_SSH) == 0)
|| ($fullItem['type'] == ITEM_TYPE_TELNET && strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_TELNET) == 0)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Check the key, please. Default example was passed.'));
}
// key
if ($item_key_parser->parse($fullItem['key_']) != CParser::PARSE_SUCCESS) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_params($this->getErrorMsg(self::ERROR_INVALID_KEY), [
$fullItem['key_'], $fullItem['name'], $host['name'], $item_key_parser->getError()
])
);
}
// parameters
if ($fullItem['type'] == ITEM_TYPE_AGGREGATE) {
$params_num = $item_key_parser->getParamsNum();
if (!str_in_array($item_key_parser->getKey(), ['grpmax', 'grpmin', 'grpsum', 'grpavg'])
|| $params_num > 4 || $params_num < 3
|| ($params_num == 3 && $item_key_parser->getParam(2) !== 'last')
|| !str_in_array($item_key_parser->getParam(2), ['last', 'min', 'max', 'avg', 'sum', 'count'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Key "%1$s" does not match <grpmax|grpmin|grpsum|grpavg>["Host group(s)", "Item key",'.
' "<last|min|max|avg|sum|count>", "parameter"].', $item_key_parser->getKey()));
}
}
// type of information
if ($fullItem['type'] == ITEM_TYPE_AGGREGATE && $fullItem['value_type'] != ITEM_VALUE_TYPE_UINT64
&& $fullItem['value_type'] != ITEM_VALUE_TYPE_FLOAT) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Type of information must be "Numeric (unsigned)" or "Numeric (float)" for aggregate items.'));
}
if (($fullItem['type'] == ITEM_TYPE_TRAPPER || $fullItem['type'] == ITEM_TYPE_HTTPAGENT)
&& array_key_exists('trapper_hosts', $fullItem) && $fullItem['trapper_hosts'] !== ''
&& !$ip_range_parser->parse($fullItem['trapper_hosts'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'trapper_hosts', $ip_range_parser->getError())
);
}
// jmx
if ($fullItem['type'] == ITEM_TYPE_JMX) {
if (!array_key_exists('jmx_endpoint', $fullItem) && !$update) {
$item['jmx_endpoint'] = ZBX_DEFAULT_JMX_ENDPOINT;
}
if (array_key_exists('jmx_endpoint', $fullItem) && $fullItem['jmx_endpoint'] === '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'jmx_endpoint', _('cannot be empty'))
);
}
if (($fullItem['username'] === '') !== ($fullItem['password'] === '')) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'username',
_('both username and password should be either present or empty'))
);
}
}
else {
if (array_key_exists('jmx_endpoint', $item) && $item['jmx_endpoint'] !== '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'jmx_endpoint', _('should be empty'))
);
}
elseif (array_key_exists('jmx_endpoint', $fullItem) && $fullItem['jmx_endpoint'] !== '') {
$item['jmx_endpoint'] = '';
}
}
// Dependent item.
if ($fullItem['type'] == ITEM_TYPE_DEPENDENT) {
if ($update) {
if (array_key_exists('master_itemid', $item) && !$item['master_itemid']) {
self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('cannot be empty')
));
}
if ($dbItems[$fullItem['itemid']]['type'] != ITEM_TYPE_DEPENDENT
&& !array_key_exists('master_itemid', $item)) {
self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('cannot be empty')
));
}
}
elseif (!array_key_exists('master_itemid', $item) || !$item['master_itemid']) {
self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('cannot be empty')
));
}
if (array_key_exists('master_itemid', $item) && !is_int($item['master_itemid'])
&& !(is_string($item['master_itemid']) && ctype_digit($item['master_itemid']))) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" for "%2$s" field.',
$item['master_itemid'], 'master_itemid'
));
}
}
else {
if (array_key_exists('master_itemid', $item) && $item['master_itemid']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('should be empty')
));
}
$item['master_itemid'] = 0;
}
// ssh, telnet
if ($fullItem['type'] == ITEM_TYPE_SSH || $fullItem['type'] == ITEM_TYPE_TELNET) {
if (zbx_empty($fullItem['username'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No authentication user name specified.'));
}
if ($fullItem['type'] == ITEM_TYPE_SSH && $fullItem['authtype'] == ITEM_AUTHTYPE_PUBLICKEY) {
if (zbx_empty($fullItem['publickey'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No public key file specified.'));
}
if (zbx_empty($fullItem['privatekey'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No private key file specified.'));
}
}
}
// snmp trap
if ($fullItem['type'] == ITEM_TYPE_SNMPTRAP
&& $fullItem['key_'] !== 'snmptrap.fallback' && $item_key_parser->getKey() !== 'snmptrap') {
self::exception(ZBX_API_ERROR_PARAMETERS, _('SNMP trap key is invalid.'));
}
// snmp oid
if ((in_array($fullItem['type'], [ITEM_TYPE_SNMPV1, ITEM_TYPE_SNMPV2C, ITEM_TYPE_SNMPV3]))
&& zbx_empty($fullItem['snmp_oid'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No SNMP OID specified.'));
}
// snmp community
if (in_array($fullItem['type'], [ITEM_TYPE_SNMPV1, ITEM_TYPE_SNMPV2C])
&& zbx_empty($fullItem['snmp_community'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('No SNMP community specified.'));
}
// snmp port
if (isset($fullItem['port']) && !zbx_empty($fullItem['port']) && !validatePortNumberOrMacro($fullItem['port'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Item "%1$s:%2$s" has invalid port: "%3$s".', $fullItem['name'], $fullItem['key_'], $fullItem['port']));
}
if (isset($fullItem['snmpv3_securitylevel']) && $fullItem['snmpv3_securitylevel'] != ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV) {
// snmpv3 authprotocol
if (str_in_array($fullItem['snmpv3_securitylevel'], [ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV, ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV])) {
if (isset($fullItem['snmpv3_authprotocol']) && (zbx_empty($fullItem['snmpv3_authprotocol'])
|| !str_in_array($fullItem['snmpv3_authprotocol'],
[ITEM_AUTHPROTOCOL_MD5, ITEM_AUTHPROTOCOL_SHA]))) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect authentication protocol for item "%1$s".', $fullItem['name']));
}
}
// snmpv3 privprotocol
if ($fullItem['snmpv3_securitylevel'] == ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV) {
if (isset($fullItem['snmpv3_privprotocol']) && (zbx_empty($fullItem['snmpv3_privprotocol'])
|| !str_in_array($fullItem['snmpv3_privprotocol'],
[ITEM_PRIVPROTOCOL_DES, ITEM_PRIVPROTOCOL_AES]))) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect privacy protocol for item "%1$s".', $fullItem['name']));
}
}
}
if (isset($item['applications']) && $item['applications']) {
/*
* 'flags' is available for update and item prototypes.
* Don't allow discovered or any other application types for item prototypes in 'applications' option.
*/
if (array_key_exists('flags', $fullItem) && $fullItem['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE) {
foreach ($host['applications'] as $num => $application) {
if ($application['flags'] != ZBX_FLAG_DISCOVERY_NORMAL) {
unset($host['applications'][$num]);
}
}
}
// check that the given applications belong to the item's host
$dbApplicationIds = zbx_objectValues($host['applications'], 'applicationid');
foreach ($item['applications'] as $appId) {
if (!in_array($appId, $dbApplicationIds)) {
$error = _s('Application with ID "%1$s" is not available on "%2$s".', $appId, $host['name']);
self::exception(ZBX_API_ERROR_PARAMETERS, $error);
}
}
}
$this->checkSpecificFields($fullItem, $update ? 'update' : 'create');
}
unset($item);
$this->checkExistingItems($items);
}
/**
* Check item specific fields. Each API like Item, Itemprototype and Discovery rule may inherit different fields
* to validate.
*
* @param array $item An array of single item data.
* @param string $method A string of "create" or "update" method.
*
* @return bool
*/
protected function checkSpecificFields(array $item, $method) {
return true;
}
protected function clearValues(array $item) {
if (isset($item['port']) && $item['port'] != '') {
$item['port'] = ltrim($item['port'], '0');
if ($item['port'] == '') {
$item['port'] = 0;
}
}
if (array_key_exists('type', $item) &&
($item['type'] == ITEM_TYPE_DEPENDENT || $item['type'] == ITEM_TYPE_TRAPPER)) {
$item['delay'] = 0;
}
return $item;
}
protected function errorInheritFlags($flag, $key, $host) {
switch ($flag) {
case ZBX_FLAG_DISCOVERY_NORMAL:
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item with key "%1$s" already exists on "%2$s" as an item.', $key, $host));
break;
case ZBX_FLAG_DISCOVERY_RULE:
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item with key "%1$s" already exists on "%2$s" as a discovery rule.', $key, $host));
break;
case ZBX_FLAG_DISCOVERY_PROTOTYPE:
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item with key "%1$s" already exists on "%2$s" as an item prototype.', $key, $host));
break;
case ZBX_FLAG_DISCOVERY_CREATED:
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item with key "%1$s" already exists on "%2$s" as an item created from item prototype.', $key, $host));
break;
default:
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item with key "%1$s" already exists on "%2$s" as unknown item element.', $key, $host));
}
}
/**
* Returns the interface that best matches the given item.
*
* @param array $item_type An item type
* @param array $interfaces An array of interfaces to choose from
*
* @return array|boolean The best matching interface;
* an empty array of no matching interface was found;
* false, if the item does not need an interface
*/
public static function findInterfaceForItem($item_type, array $interfaces) {
$interface_by_type = [];
foreach ($interfaces as $interface) {
if ($interface['main'] == 1) {
$interface_by_type[$interface['type']] = $interface;
}
}
// find item interface type
$type = itemTypeInterface($item_type);
// the item can use any interface
if ($type == INTERFACE_TYPE_ANY) {
$interface_types = [INTERFACE_TYPE_AGENT, INTERFACE_TYPE_SNMP, INTERFACE_TYPE_JMX, INTERFACE_TYPE_IPMI];
foreach ($interface_types as $interface_type) {
if (array_key_exists($interface_type, $interface_by_type)) {
return $interface_by_type[$interface_type];
}
}
}
// the item uses a specific type of interface
elseif ($type !== false) {
return array_key_exists($type, $interface_by_type) ? $interface_by_type[$type] : [];
}
// the item does not need an interface
else {
return false;
}
}
/**
* Updates the children of the item on the given hosts and propagates the inheritance to the child hosts.
*
* @param array $tpl_items An array of items to inherit.
* @param array|null $hostids An array of hosts to inherit to; if set to null, the items will be inherited to all
* linked hosts or templates.
*/
protected function inherit(array $tpl_items, array $hostids = null) {
$tpl_items = zbx_toHash($tpl_items, 'itemid');
// Inherit starting from common items and finishing up dependent.
while ($tpl_items) {
$_tpl_items = [];
foreach ($tpl_items as $tpl_item) {
if ($tpl_item['type'] != ITEM_TYPE_DEPENDENT
|| !array_key_exists($tpl_item['master_itemid'], $tpl_items)) {
$_tpl_items[$tpl_item['itemid']] = $tpl_item;
}
}
foreach ($_tpl_items as $itemid => $_tpl_item) {
unset($tpl_items[$itemid]);
}
$this->_inherit($_tpl_items, $hostids);
}
}
/**
* Auxiliary method for item inheritance. See full description in inherit() method.
*/
private function _inherit(array $tpl_items, array $hostids = null) {
// Prepare the child items.
$new_items = $this->prepareInheritedItems($tpl_items, $hostids);
if (!$new_items) {
return;
}
$ins_items = [];
$upd_items = [];
foreach ($new_items as $new_item) {
if (array_key_exists('itemid', $new_item)) {
if ($this instanceof CItemPrototype) {
unset($new_item['ruleid']);
}
$upd_items[] = $new_item;
}
else {
$ins_items[] = $new_item;
}
}
if ($this instanceof CItem || $this instanceof CItemPrototype) {
$this->validateDependentItems($new_items);
}
// Save the new items.
if ($ins_items) {
if ($this instanceof CItem) {
static::validateInventoryLinks($ins_items, false);
}
$this->createReal($ins_items);
}
if ($upd_items) {
if ($this instanceof CItem) {
static::validateInventoryLinks($upd_items, true);
}
$this->updateReal($upd_items);
}
$new_items = array_merge($upd_items, $ins_items);
// Inheriting items from the templates.
$db_items = DBselect(
'SELECT i.itemid'.
' FROM items i,hosts h'.
' WHERE i.hostid=h.hostid'.
' AND '.dbConditionInt('i.itemid', zbx_objectValues($new_items, 'itemid')).
' AND '.dbConditionInt('h.status', [HOST_STATUS_TEMPLATE])
);
$tpl_itemids = [];
while ($db_item = DBfetch($db_items)) {
$tpl_itemids[$db_item['itemid']] = true;
}
foreach ($new_items as $index => $new_item) {
if (!array_key_exists($new_item['itemid'], $tpl_itemids)) {
unset($new_items[$index]);
}
}
$this->inherit($new_items);
}
/**
* Prepares and returns an array of child items, inherited from items $tpl_items on the given hosts.
*
* @param array $tpl_items
* @param string $tpl_items[<itemid>]['itemid']
* @param string $tpl_items[<itemid>]['hostid']
* @param string $tpl_items[<itemid>]['key_']
* @param int $tpl_items[<itemid>]['type']
* @param array $tpl_items[<itemid>]['applicationPrototypes'] (optional) Suitable for item
* prototypes.
* @param string $tpl_items[<itemid>]['applicationPrototypes'][]['name']
* @param array $tpl_items[<itemid>]['applications'] (optional) Array of applicationids.
* @param array $tpl_items[<itemid>]['preprocessing'] (optional) Suitable for items and item
* prototypes.
* @param int $tpl_items[<itemid>]['preprocessing'][]['type']
* @param string $tpl_items[<itemid>]['preprocessing'][]['params']
* @param int $tpl_items[<itemid>]['flags']
* @param string $tpl_items[<itemid>]['master_itemid'] (optional)
* @param mixed $tpl_items[<itemid>][<field_name>] (optional)
* @param array|null $hostids
*
* @return array an array of unsaved child items
*/
private function prepareInheritedItems(array $tpl_items, array $hostids = null) {
$class = get_class($this);
$itemids_by_templateid = [];
foreach ($tpl_items as $tpl_item) {
$itemids_by_templateid[$tpl_item['hostid']][] = $tpl_item['itemid'];
}
// Fetch all child hosts.
$chd_hosts = API::Host()->get([
'output' => ['hostid', 'host', 'status'],
'selectParentTemplates' => ['templateid'],
'selectInterfaces' => ['interfaceid', 'main', 'type'],
'templateids' => array_keys($itemids_by_templateid),
'hostids' => $hostids,
'preservekeys' => true,
'nopermissions' => true,
'templated_hosts' => true
]);
if (!$chd_hosts) {
return [];
}
$chd_items_tpl = [];
$chd_items_key = [];
// Preparing list of items by item templateid.
$sql = 'SELECT i.itemid,i.hostid,i.type,i.key_,i.flags,i.templateid'.
' FROM items i'.
' WHERE '.dbConditionInt('i.templateid', zbx_objectValues($tpl_items, 'itemid'));
if ($hostids !== null) {
$sql .= ' AND '.dbConditionInt('i.hostid', $hostids);
}
$db_items = DBselect($sql);
while ($db_item = DBfetch($db_items)) {
$hostid = $db_item['hostid'];
unset($db_item['hostid']);
$chd_items_tpl[$hostid][$db_item['templateid']] = $db_item;
}
$hostids_by_key = [];
// Preparing list of items by item key.
foreach ($chd_hosts as $chd_host) {
$tpl_itemids = [];
foreach ($chd_host['parentTemplates'] as $parent_template) {
if (array_key_exists($parent_template['templateid'], $itemids_by_templateid)) {
$tpl_itemids = array_merge($tpl_itemids, $itemids_by_templateid[$parent_template['templateid']]);
}
}
foreach ($tpl_itemids as $tpl_itemid) {
if (!array_key_exists($chd_host['hostid'], $chd_items_tpl)
|| !array_key_exists($tpl_itemid, $chd_items_tpl[$chd_host['hostid']])) {
$hostids_by_key[$tpl_items[$tpl_itemid]['key_']][] = $chd_host['hostid'];
}
}
}
foreach ($hostids_by_key as $key_ => $key_hostids) {
$sql_select = ($class === 'CItemPrototype') ? ',id.parent_itemid AS ruleid' : '';
$sql_join = ($class === 'CItemPrototype') ? ' JOIN item_discovery id ON i.itemid=id.itemid' : '';
$db_items = DBselect(
'SELECT i.itemid,i.hostid,i.type,i.key_,i.flags,i.templateid'.$sql_select.
' FROM items i'.$sql_join.
' WHERE '.dbConditionInt('i.hostid', $key_hostids).
' AND '.dbConditionString('i.key_', [$key_])
);
while ($db_item = DBfetch($db_items)) {
$hostid = $db_item['hostid'];
unset($db_item['hostid']);
$chd_items_key[$hostid][$db_item['key_']] = $db_item;
}
}
// Preparing list of application prototypes.
if ($class === 'CItemPrototype') {
$tpl_app_prototypes = [];
$item_prototypeids = [];
foreach ($tpl_items as $tpl_item) {
if (array_key_exists('applicationPrototypes', $tpl_item) && $tpl_item['applicationPrototypes']) {
$item_prototypeids[] = $tpl_item['itemid'];
}
}
if ($item_prototypeids) {
$db_tpl_app_prototypes = DBselect(
'SELECT iap.itemid,iap.application_prototypeid,ap.name'.
' FROM item_application_prototype iap,application_prototype ap'.
' WHERE iap.application_prototypeid=ap.application_prototypeid'.
' AND '.dbConditionInt('iap.itemid', $item_prototypeids)
);
while ($db_tpl_app_prototype = DBfetch($db_tpl_app_prototypes)) {
$tpl_app_prototypes[$db_tpl_app_prototype['itemid']][$db_tpl_app_prototype['name']] =
$db_tpl_app_prototype['application_prototypeid'];
}
}
}
// List of the discovery rules.
if ($class === 'CItemPrototype') {
// List of itemids without 'ruleid' property.
$tpl_itemids = [];
$tpl_ruleids = [];
foreach ($tpl_items as $tpl_item) {
if (!array_key_exists('ruleid', $tpl_item)) {
$tpl_itemids[] = $tpl_item['itemid'];
}
else {
$tpl_ruleids[$tpl_item['ruleid']] = true;
}
}
if ($tpl_itemids) {
$db_rules = DBselect(
'SELECT id.parent_itemid,id.itemid'.
' FROM item_discovery id'.
' WHERE '.dbConditionInt('id.itemid', $tpl_itemids)
);
while ($db_rule = DBfetch($db_rules)) {
$tpl_items[$db_rule['itemid']]['ruleid'] = $db_rule['parent_itemid'];
$tpl_ruleids[$db_rule['parent_itemid']] = true;
}
}
$sql = 'SELECT i.hostid,i.templateid,i.itemid'.
' FROM items i'.
' WHERE '.dbConditionInt('i.templateid', array_keys($tpl_ruleids));
if ($hostids !== null) {
$sql .= ' AND '.dbConditionInt('i.hostid', $hostids);
}
$db_rules = DBselect($sql);
// List of child lld ruleids by child hostid and parent lld ruleid.
$chd_ruleids = [];
while ($db_rule = DBfetch($db_rules)) {
$chd_ruleids[$db_rule['hostid']][$db_rule['templateid']] = $db_rule['itemid'];
}
}
$new_items = [];
// List of the updated item keys by hostid.
$upd_hostids_by_key = [];
foreach ($chd_hosts as $chd_host) {
$tpl_itemids = [];
foreach ($chd_host['parentTemplates'] as $parent_template) {
if (array_key_exists($parent_template['templateid'], $itemids_by_templateid)) {
$tpl_itemids = array_merge($tpl_itemids, $itemids_by_templateid[$parent_template['templateid']]);
}
}
foreach ($tpl_itemids as $tpl_itemid) {
$tpl_item = $tpl_items[$tpl_itemid];
$chd_item = null;
// Update by templateid.
if (array_key_exists($chd_host['hostid'], $chd_items_tpl)
&& array_key_exists($tpl_item['itemid'], $chd_items_tpl[$chd_host['hostid']])) {
$chd_item = $chd_items_tpl[$chd_host['hostid']][$tpl_item['itemid']];
if ($tpl_item['key_'] !== $chd_item['key_']) {
$upd_hostids_by_key[$tpl_item['key_']][] = $chd_host['hostid'];
}
}
// Update by key.
elseif (array_key_exists($chd_host['hostid'], $chd_items_key)
&& array_key_exists($tpl_item['key_'], $chd_items_key[$chd_host['hostid']])) {
$chd_item = $chd_items_key[$chd_host['hostid']][$tpl_item['key_']];
// Check if an item of a different type with the same key exists.
if ($tpl_item['flags'] != $chd_item['flags']) {
$this->errorInheritFlags($chd_item['flags'], $chd_item['key_'], $chd_host['host']);
}
// Check if item already linked to another template.
if ($chd_item['templateid'] != 0 && bccomp($chd_item['templateid'], $tpl_item['itemid']) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS, _params(
$this->getErrorMsg(self::ERROR_EXISTS_TEMPLATE), [$tpl_item['key_'], $chd_host['host']]
));
}
if ($class === 'CItemPrototype') {
$chd_ruleid = $chd_ruleids[$chd_host['hostid']][$tpl_item['ruleid']];
if (bccomp($chd_item['ruleid'], $chd_ruleid) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Item prototype "%1$s" already exists on "%2$s", linked to another rule.',
$chd_item['key_'], $chd_host['host']
)
);
}
}
}
// copying item
$new_item = $tpl_item;
if ($chd_item !== null) {
$new_item['itemid'] = $chd_item['itemid'];
}
else {
unset($new_item['itemid']);
if ($class === 'CItemPrototype') {
$new_item['ruleid'] = $chd_ruleids[$chd_host['hostid']][$tpl_item['ruleid']];
}
}
$new_item['hostid'] = $chd_host['hostid'];
$new_item['templateid'] = $tpl_item['itemid'];
if ($chd_host['status'] != HOST_STATUS_TEMPLATE) {
if ($chd_item === null || $new_item['type'] != $chd_item['type']) {
$interface = self::findInterfaceForItem($new_item['type'], $chd_host['interfaces']);
if ($interface) {
$new_item['interfaceid'] = $interface['interfaceid'];
}
elseif ($interface !== false) {
self::exception(ZBX_API_ERROR_PARAMETERS, _params(
$this->getErrorMsg(self::ERROR_NO_INTERFACE), [$chd_host['host'], $new_item['key_']]
));
}
}
}
// For items and item prototypes.
if (($class === 'CItem' || $class === 'CItemPrototype')
&& array_key_exists('preprocessing', $new_item)) {
foreach ($new_item['preprocessing'] as $preprocessing) {
if ($chd_item) {
$preprocessing['itemid'] = $chd_item['itemid'];
}
else {
unset($preprocessing['itemid']);
}
}
}
if ($class === 'CItemPrototype' && array_key_exists('applicationPrototypes', $new_item)) {
foreach ($new_item['applicationPrototypes'] as &$application_prototype) {
$application_prototype['templateid'] =
$tpl_app_prototypes[$tpl_item['itemid']][$application_prototype['name']];
}
unset($application_prototype);
}
$new_items[] = $new_item;
}
}
// Check if item with a new key already exists on the child host.
if ($upd_hostids_by_key) {
$sql_where = [];
foreach ($upd_hostids_by_key as $key => $hostids) {
$sql_where[] = dbConditionInt('i.hostid', $hostids).' AND i.key_='.zbx_dbstr($key);
}
$sql = 'SELECT i.hostid,i.key_'.
' FROM items i'.
' WHERE ('.implode(') OR (', $sql_where).')';
$db_items = DBselect($sql, 1);
if ($db_item = DBfetch($db_items)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _params($this->getErrorMsg(self::ERROR_EXISTS),
[$db_item['key_'], $chd_hosts[$db_item['hostid']]['host']]
));
}
}
// Setting item applications.
if ($class === 'CItem' || $class === 'CItemPrototype') {
$tpl_applicationids = [];
foreach ($tpl_items as $tpl_item) {
if (array_key_exists('applications', $tpl_item)) {
foreach ($tpl_item['applications'] as $applicationid) {
$tpl_applicationids[$applicationid] = true;
}
}
}
if ($tpl_applicationids) {
$db_applications = DBselect('SELECT a.hostid,at.templateid,a.applicationid'.
' FROM application_template at,applications a'.
' WHERE at.applicationid=a.applicationid'.
' AND '.dbConditionInt('at.templateid', array_keys($tpl_applicationids)).
' AND '.dbConditionInt('a.hostid', array_keys($chd_hosts))
);
$app_links = [];
while ($db_application = DBfetch($db_applications)) {
$app_links[$db_application['hostid']][$db_application['templateid']] =
$db_application['applicationid'];
}
foreach ($new_items as &$new_item) {
if (array_key_exists('applications', $new_item)) {
$applicationids = [];
foreach ($new_item['applications'] as $applicationid) {
if (array_key_exists($applicationid, $app_links[$new_item['hostid']])) {
$applicationids[] = $app_links[$new_item['hostid']][$applicationid];
}
}
$new_item['applications'] = $applicationids;
}
}
unset($new_item);
}
}
if ($class === 'CItem' || $class === 'CItemPrototype') {
$new_items = $this->prepareDependentItems($tpl_items, $new_items, $hostids);
}
return $new_items;
}
/**
* Update relations for inherited dependent items to master items.
*
* @param array $tpl_items
* @param int $tpl_items[<itemid>]['type']
* @param string $tpl_items[<itemid>]['master_itemid']
* @param array $new_items
* @param string $new_items[<itemid>]['hostid']
* @param int $new_items[<itemid>]['type']
* @param string $new_items[<itemid>]['templateid']
* @param array|null $hostids
*
* @return array an array of synchronized inherited items.
*/
private function prepareDependentItems(array $tpl_items, array $new_items, array $hostids = null) {
$tpl_master_itemids = [];
foreach ($tpl_items as $tpl_item) {
if ($tpl_item['type'] == ITEM_TYPE_DEPENDENT) {
$tpl_master_itemids[$tpl_item['master_itemid']] = true;
}
}
if ($tpl_master_itemids) {
$sql = 'SELECT i.itemid,i.hostid,i.templateid'.
' FROM items i'.
' WHERE '.dbConditionId('i.templateid', array_keys($tpl_master_itemids));
if ($hostids !== null) {
$sql .= ' AND '.dbConditionId('i.hostid', $hostids);
}
$db_items = DBselect($sql);
$master_links = [];
while ($db_item = DBfetch($db_items)) {
$master_links[$db_item['templateid']][$db_item['hostid']] = $db_item['itemid'];
}
foreach ($new_items as &$new_item) {
if ($new_item['type'] == ITEM_TYPE_DEPENDENT) {
$tpl_item = $tpl_items[$new_item['templateid']];
if (array_key_exists('master_itemid', $tpl_item)) {
$new_item['master_itemid'] = $master_links[$tpl_item['master_itemid']][$new_item['hostid']];
}
}
}
unset($new_item);
}
return $new_items;
}
/**
* Validate item pre-processing.
*
* @param array $item An array of single item data.
* @param array $item['preprocessing'] An array of item pre-processing data.
* @param string $item['preprocessing'][]['type'] The preprocessing option type. Possible values:
* 1 - ZBX_PREPROC_MULTIPLIER;
* 2 - ZBX_PREPROC_RTRIM;
* 3 - ZBX_PREPROC_LTRIM;
* 4 - ZBX_PREPROC_TRIM;
* 5 - ZBX_PREPROC_REGSUB;
* 6 - ZBX_PREPROC_BOOL2DEC;
* 7 - ZBX_PREPROC_OCT2DEC;
* 8 - ZBX_PREPROC_HEX2DEC;
* 9 - ZBX_PREPROC_DELTA_VALUE;
* 10 - ZBX_PREPROC_DELTA_SPEED;
* 11 - ZBX_PREPROC_XPATH;
* 12 - ZBX_PREPROC_JSONPATH.
* @param string $item['preprocessing'][]['params'] Additional parameters used by preprocessing option. In case
* of regular expression (ZBX_PREPROC_REGSUB), multiple
* parameters are separated by LF (\n)character.
* @param string $method A string of "create" or "update" method.
*/
protected function validateItemPreprocessing(array $item, $method) {
if (array_key_exists('preprocessing', $item)) {
if (!is_array($item['preprocessing'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
$type_validator = new CLimitedSetValidator(['values' => array_keys(get_preprocessing_types(null, false))]);
$required_fields = ['type', 'params'];
$delta = false;
foreach ($item['preprocessing'] as $preprocessing) {
$missing_keys = array_diff($required_fields, array_keys($preprocessing));
if ($missing_keys) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Item pre-processing is missing parameters: %1$s', implode(', ', $missing_keys))
);
}
if (is_array($preprocessing['type'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
elseif ($preprocessing['type'] === '' || $preprocessing['type'] === null
|| $preprocessing['type'] === false) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'type', _('cannot be empty'))
);
}
if (!$type_validator->validate($preprocessing['type'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'type',
_s('unexpected value "%1$s"', $preprocessing['type'])
)
);
}
switch ($preprocessing['type']) {
case ZBX_PREPROC_MULTIPLIER:
// Check if custom multiplier is a valid number.
$params = $preprocessing['params'];
if (is_array($params)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
elseif ($params === '' || $params === null || $params === false) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'params', _('cannot be empty'))
);
}
if (!is_numeric($params)
&& (new CUserMacroParser())->parse($params) != CParser::PARSE_SUCCESS
&& (!($this instanceof CItemPrototype)
|| ((new CLLDMacroFunctionParser())->parse($params) != CParser::PARSE_SUCCESS
&& (new CLLDMacroParser())->parse($params) != CParser::PARSE_SUCCESS))) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'params', _('a numeric value is expected')
));
}
break;
case ZBX_PREPROC_RTRIM:
case ZBX_PREPROC_LTRIM:
case ZBX_PREPROC_TRIM:
case ZBX_PREPROC_XPATH:
case ZBX_PREPROC_JSONPATH:
// Check 'params' if not empty.
if (is_array($preprocessing['params'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
elseif ($preprocessing['params'] === '' || $preprocessing['params'] === null
|| $preprocessing['params'] === false) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'params', _('cannot be empty'))
);
}
break;
case ZBX_PREPROC_REGSUB:
// Check if 'params' are not empty and if second parameter contains (after \n) is not empty.
if (is_array($preprocessing['params'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
elseif ($preprocessing['params'] === '' || $preprocessing['params'] === null
|| $preprocessing['params'] === false) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'params', _('cannot be empty'))
);
}
$params = explode("\n", $preprocessing['params']);
if ($params[0] === '') {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'params', _('first parameter is expected')
));
}
if (!array_key_exists(1, $params) || $params[1] === '') {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'params', _('second parameter is expected')
));
}
break;
case ZBX_PREPROC_BOOL2DEC:
case ZBX_PREPROC_OCT2DEC:
case ZBX_PREPROC_HEX2DEC:
// Check if 'params' is empty, because it must be empty.
if (is_array($preprocessing['params'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
elseif ($preprocessing['params'] !== '' && $preprocessing['params'] !== null
&& $preprocessing['params'] !== false) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'params', _('should be empty'))
);
}
break;
case ZBX_PREPROC_DELTA_VALUE:
case ZBX_PREPROC_DELTA_SPEED:
// Check if 'params' is empty, because it must be empty.
if (is_array($preprocessing['params'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
}
elseif ($preprocessing['params'] !== '' && $preprocessing['params'] !== null
&& $preprocessing['params'] !== false) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'params', _('should be empty'))
);
}
// Check if one of the deltas (Delta per second or Delta value) already exists.
if ($delta) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Only one change step is allowed.'));
}
else {
$delta = true;
}
break;
}
}
}
}
/**
* Insert item pre-processing data into DB.
*
* @param array $items An array of items.
* @param array $items[]['preprocessing'] An array of item pre-processing data.
*/
protected function createItemPreprocessing(array $items) {
$item_preproc = [];
$step = 1;
foreach ($items as $item) {
if (array_key_exists('preprocessing', $item)) {
foreach ($item['preprocessing'] as $preprocessing) {
$item_preproc[] = [
'itemid' => $item['itemid'],
'step' => $step++,
'type' => $preprocessing['type'],
'params' => $preprocessing['params']
];
}
}
}
if ($item_preproc) {
DB::insert('item_preproc', $item_preproc);
}
}
/**
* Update item pre-processing data in DB. Delete old records and create new ones.
*
* @param array $items An array of items.
* @param array $items[]['preprocessing'] An array of item pre-processing data.
*/
protected function updateItemPreprocessing(array $items) {
$item_preproc = [];
$item_preprocids = [];
$step = 1;
foreach ($items as $item) {
if (array_key_exists('preprocessing', $item)) {
$item_preprocids[] = $item['itemid'];
foreach ($item['preprocessing'] as $preprocessing) {
$item_preproc[] = [
'itemid' => $item['itemid'],
'step' => $step++,
'type' => $preprocessing['type'],
'params' => $preprocessing['params']
];
}
}
}
if ($item_preprocids) {
DB::delete('item_preproc', ['itemid' => $item_preprocids]);
}
if ($item_preproc) {
DB::insert('item_preproc', $item_preproc);
}
}
/**
* Check if any item from list already exists.
* If items have item ids it will check for existing item with different itemid.
*
* @throw APIException
*
* @param array $items
*/
protected function checkExistingItems(array $items) {
$itemKeysByHostId = [];
$itemIds = [];
foreach ($items as $item) {
if (!isset($itemKeysByHostId[$item['hostid']])) {
$itemKeysByHostId[$item['hostid']] = [];
}
$itemKeysByHostId[$item['hostid']][] = $item['key_'];
if (isset($item['itemid'])) {
$itemIds[] = $item['itemid'];
}
}
$sqlWhere = [];
foreach ($itemKeysByHostId as $hostId => $keys) {
$sqlWhere[] = '(i.hostid='.zbx_dbstr($hostId).' AND '.dbConditionString('i.key_', $keys).')';
}
if ($sqlWhere) {
$sql = 'SELECT i.key_,h.host'.
' FROM items i,hosts h'.
' WHERE i.hostid=h.hostid AND ('.implode(' OR ', $sqlWhere).')';
// if we update existing items we need to exclude them from result.
if ($itemIds) {
$sql .= ' AND '.dbConditionInt('i.itemid', $itemIds, true);
}
$dbItems = DBselect($sql, 1);
while ($dbItem = DBfetch($dbItems)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Item with key "%1$s" already exists on "%2$s".', $dbItem['key_'], $dbItem['host']));
}
}
}
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');
}
return $result;
}
/**
* Validate items with type ITEM_TYPE_DEPENDENT for create or update operation.
*
* @param array $items
* @param string $items[]['itemid'] (mandatory for updated items and item prototypes)
* @param string $items[]['hostid']
* @param int $items[]['type']
* @param string $items[]['master_itemid'] (mandatory for ITEM_TYPE_DEPENDENT)
* @param int $items[]['flags'] (mandatory for items)
*
* @throws APIException for invalid data.
*/
protected function validateDependentItems(array $items) {
$dep_items = [];
$upd_itemids = [];
foreach ($items as $item) {
if ($item['type'] == ITEM_TYPE_DEPENDENT) {
if ($this instanceof CItemPrototype || $item['flags'] == ZBX_FLAG_DISCOVERY_NORMAL) {
$dep_items[] = $item;
}
if (array_key_exists('itemid', $item)) {
$upd_itemids[] = $item['itemid'];
}
}
}
if (!$dep_items) {
return;
}
if ($this instanceof CItemPrototype && $upd_itemids) {
$db_links = DBselect(
'SELECT id.itemid,id.parent_itemid AS ruleid'.
' FROM item_discovery id'.
' WHERE '.dbConditionId('id.itemid', $upd_itemids)
);
$links = [];
while ($db_link = DBfetch($db_links)) {
$links[$db_link['itemid']] = $db_link['ruleid'];
}
foreach ($dep_items as &$dep_item) {
if (array_key_exists('itemid', $dep_item)) {
$dep_item['ruleid'] = $links[$dep_item['itemid']];
}
}
unset($dep_item);
}
$master_itemids = [];
foreach ($dep_items as $dep_item) {
$master_itemids[$dep_item['master_itemid']] = true;
}
$master_items = [];
// Fill relations array by master items (item prototypes).
do {
if ($this instanceof CItem) {
$db_master_items = DBselect(
'SELECT i.itemid,i.hostid,i.master_itemid'.
' FROM items i'.
' WHERE '.dbConditionId('i.itemid', array_keys($master_itemids)).
' AND '.dbConditionInt('i.flags', [ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED])
);
}
else {
$db_master_items = 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', array_keys($master_itemids)).
' AND '.dbConditionInt('i.flags', [ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_PROTOTYPE])
);
}
while ($db_master_item = DBfetch($db_master_items)) {
$master_items[$db_master_item['itemid']] = $db_master_item;
unset($master_itemids[$db_master_item['itemid']]);
}
if ($master_itemids) {
reset($master_itemids);
self::exception(ZBX_API_ERROR_PERMISSIONS,
_s('Incorrect value for field "%1$s": %2$s.', 'master_itemid',
_s('Item "%1$s" does not exist or you have no access to this item', key($master_itemids))
)
);
}
$master_itemids = [];
foreach ($master_items as $master_item) {
if ($master_item['master_itemid'] != 0
&& !array_key_exists($master_item['master_itemid'], $master_items)) {
$master_itemids[$master_item['master_itemid']] = true;
}
}
} while ($master_itemids);
foreach ($dep_items as $dep_item) {
$master_item = $master_items[$dep_item['master_itemid']];
if ($dep_item['hostid'] != $master_item['hostid']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('hostid of dependent item and master item should match')
));
}
if ($this instanceof CItemPrototype && $master_item['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE
&& $dep_item['ruleid'] != $master_item['ruleid']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('ruleid of dependent item and master item should match')
));
}
if (array_key_exists('itemid', $dep_item)) {
$master_itemid = $dep_item['master_itemid'];
while ($master_itemid != 0) {
if ($master_itemid == $dep_item['itemid']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('circular item dependency is not allowed')
));
}
$master_itemid = $master_items[$master_itemid]['master_itemid'];
}
}
}
// Fill relations array by dependent items (item prototypes).
$root_itemids = [];
foreach ($master_items as $master_item) {
if ($master_item['master_itemid'] == 0) {
$root_itemids[] = $master_item['itemid'];
}
}
$dependent_items = [];
foreach ($dep_items as $dep_item) {
if (array_key_exists('itemid', $dep_item)) {
$dependent_items[$dep_item['master_itemid']][] = $dep_item['itemid'];
}
}
$master_itemids = $root_itemids;
do {
$sql = 'SELECT i.master_itemid,i.itemid'.
' FROM items i'.
' WHERE '.dbConditionId('i.master_itemid', $master_itemids);
if ($upd_itemids) {
$sql .= ' AND '.dbConditionId('i.itemid', $upd_itemids, true); // Exclude updated items.
}
$db_items = DBselect($sql);
while ($db_item = DBfetch($db_items)) {
$dependent_items[$db_item['master_itemid']][] = $db_item['itemid'];
}
$_master_itemids = $master_itemids;
$master_itemids = [];
foreach ($_master_itemids as $master_itemid) {
if (array_key_exists($master_itemid, $dependent_items)) {
$master_itemids = array_merge($master_itemids, $dependent_items[$master_itemid]);
}
}
} while ($master_itemids);
foreach ($dep_items as $dep_item) {
if (!array_key_exists('itemid', $dep_item)) {
$dependent_items[$dep_item['master_itemid']][] = false;
}
}
foreach ($root_itemids as $root_itemid) {
self::checkDependencyDepth($dependent_items, $root_itemid);
}
}
/**
* Validate depth and ammount of elements in the tree of the dependent items.
*
* @param array $dependent_items
* @param string $dependent_items[<master_itemid>][] List if the dependent item IDs ("false" for new items)
* by master_itemid.
* @param string $root_itemid ID of the item being checked.
* @param int $level Current dependency level.
*
* @throws APIException for invalid data.
*/
private static function checkDependencyDepth(array $dependent_items, $root_itemid, $level = 0) {
$count = 0;
if (array_key_exists($root_itemid, $dependent_items)) {
if (++$level > ZBX_DEPENDENT_ITEM_MAX_LEVELS) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('maximum number of dependency levels reached')
));
}
foreach ($dependent_items[$root_itemid] as $master_itemid) {
$count++;
if ($master_itemid !== false) {
$count += self::checkDependencyDepth($dependent_items, $master_itemid, $level);
}
}
if ($count > ZBX_DEPENDENT_ITEM_MAX_COUNT) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.',
'master_itemid', _('maximum dependent items count reached')
));
}
}
return $count;
}
/**
* 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 function headersStringToArray($headers) {
$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 function headersArrayToString(array $headers) {
$result = [];
foreach ($headers as $k => $v) {
$result[] = $k.': '.$v;
}
return implode("\r\n", $result);
}
/**
* Validate item with type ITEM_TYPE_HTTPAGENT.
*
* @param array $item Array of item fields.
* @param array $db_item Array of item database fields for update action or empty array for create action.
*
* @throws APIException for invalid data.
*/
protected function validateHTTPCheck(array $item, array $db_item) {
$rules = [
'timeout' => [
'type' => API_TIME_UNIT, 'flags' => ($this instanceof CItemPrototype)
? API_NOT_EMPTY | API_ALLOW_USER_MACRO | API_ALLOW_LLD_MACRO
: API_NOT_EMPTY | API_ALLOW_USER_MACRO,
'in' => '1:'.SEC_PER_MIN
],
'url' => [
'type' => API_STRING_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY,
'length' => DB::getFieldLength('items', 'url'),
],
'status_codes' => [
'type' => API_STRING_UTF8, 'length' => DB::getFieldLength('items', 'status_codes')
],
'follow_redirects' => [
'type' => API_INT32,
'in' => implode(',', [HTTPTEST_STEP_FOLLOW_REDIRECTS_OFF, HTTPTEST_STEP_FOLLOW_REDIRECTS_ON]),
],
'post_type' => [
'type' => API_INT32,
'in' => implode(',', [ZBX_POSTTYPE_RAW, ZBX_POSTTYPE_JSON, ZBX_POSTTYPE_XML])
],
'http_proxy' => [
'type' => API_STRING_UTF8, 'length' => DB::getFieldLength('items', 'http_proxy')
],
'headers' => [
'type' => API_STRINGS_UTF8
],
'retrieve_mode' => [
'type' => API_INT32,
'in' => implode(',', [
HTTPTEST_STEP_RETRIEVE_MODE_CONTENT, HTTPTEST_STEP_RETRIEVE_MODE_HEADERS,
HTTPTEST_STEP_RETRIEVE_MODE_BOTH
])
],
'request_method' => [
'type' => API_INT32,
'in' => implode(',', [
HTTPCHECK_REQUEST_GET, HTTPCHECK_REQUEST_POST, HTTPCHECK_REQUEST_PUT, HTTPCHECK_REQUEST_HEAD
])
],
'output_format' => [
'type' => API_INT32,
'in' => implode(',', [HTTPCHECK_STORE_RAW, HTTPCHECK_STORE_JSON])
],
'allow_traps' => [
'type' => API_INT32,
'in' => implode(',', [HTTPCHECK_ALLOW_TRAPS_OFF, HTTPCHECK_ALLOW_TRAPS_ON])
],
'ssl_cert_file' => [
'type' => API_STRING_UTF8, 'length' => DB::getFieldLength('items', 'ssl_cert_file'),
],
'ssl_key_file' => [
'type' => API_STRING_UTF8, 'length' => DB::getFieldLength('items', 'ssl_key_file'),
],
'ssl_key_password' => [
'type' => API_STRING_UTF8, 'length' => DB::getFieldLength('items', 'ssl_key_password'),
],
'verify_peer' => [
'type' => API_INT32,
'in' => implode(',', [HTTPTEST_VERIFY_PEER_OFF, HTTPTEST_VERIFY_PEER_ON])
],
'verify_host' => [
'type' => API_INT32,
'in' => implode(',', [HTTPTEST_VERIFY_HOST_OFF, HTTPTEST_VERIFY_HOST_ON])
],
'authtype' => [
'type' => API_INT32,
'in' => implode(',', [HTTPTEST_AUTH_NONE, HTTPTEST_AUTH_BASIC, HTTPTEST_AUTH_NTLM])
]
];
$data = $item + $db_item;
if (array_key_exists('authtype', $data)
&& ($data['authtype'] == HTTPTEST_AUTH_BASIC || $data['authtype'] == HTTPTEST_AUTH_NTLM)) {
$rules += [
'username' => [
'type' => API_STRING_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY,
'length' => DB::getFieldLength('items', 'username')
],
'password' => [
'type' => API_STRING_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY,
'length' => DB::getFieldLength('items', 'password')
]
];
}
// Strict validation for 'retrieve_mode' only for create action.
if (array_key_exists('request_method', $data) && $data['request_method'] == HTTPCHECK_REQUEST_HEAD
&& array_key_exists('retrieve_mode', $item)) {
$rules['retrieve_mode']['in'] = (string) HTTPTEST_STEP_RETRIEVE_MODE_HEADERS;
}
if (array_key_exists('post_type', $data)
&& ($data['post_type'] == ZBX_POSTTYPE_JSON || $data['post_type'] == ZBX_POSTTYPE_XML)) {
$rules['posts'] = [
'type' => API_STRING_UTF8,
'length' => DB::getFieldLength('items', 'posts')
];
}
if (array_key_exists('templateid', $data) && $data['templateid']) {
$rules['interfaceid'] = [
'type' => API_INT32, 'flags' => API_REQUIRED | API_NOT_EMPTY
];
}
if (array_key_exists('trapper_hosts', $item) && $item['trapper_hosts'] !== ''
&& (!array_key_exists('allow_traps', $data) || $data['allow_traps'] == HTTPCHECK_ALLOW_TRAPS_OFF)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'trapper_hosts', _('should be empty'))
);
}
// Keep values only for fields with defined validation rules.
$data = array_intersect_key($data, $rules);
if (!CApiInputValidator::validate(['type' => API_OBJECT, 'fields' => $rules], $data, '', $error)) {
self::exception(ZBX_API_ERROR_PARAMETERS, $error);
}
$json = new CJson();
if (array_key_exists('query_fields', $item)) {
if (!is_array($item['query_fields'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid parameter "%1$s": %2$s.', 'query_fields', _('an array is expected'))
);
}
foreach ($item['query_fields'] as $v) {
if (!is_array($v) || count($v) > 1 || key($v) === '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid parameter "%1$s": %2$s.', 'query_fields', _('nonempty key and value pair expected'))
);
}
}
$json_string = $json->encode($item['query_fields']);
if (strlen($json_string) > DB::getFieldLength('items', 'query_fields')) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid parameter "%1$s": %2$s.', 'query_fields',
_('cannot convert to JSON, result value too long')
));
}
}
if (array_key_exists('headers', $item)) {
if (!is_array($item['headers'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid parameter "%1$s": %2$s.', 'headers', _('an array is expected'))
);
}
foreach ($item['headers'] as $k => $v) {
if (trim($k) === '' || !is_string($v) || $v === '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid parameter "%1$s": %2$s.', 'headers', _('nonempty key and value pair expected'))
);
}
}
}
if (array_key_exists('status_codes', $item) && $item['status_codes']) {
$ranges_parser = new CRangesParser([
'usermacros' => true,
'lldmacros' => ($this instanceof CItemPrototype)
]);
if ($ranges_parser->parse($item['status_codes']) != CParser::PARSE_SUCCESS) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value "%1$s" for "%2$s" field.', $item['status_codes'], 'status_codes')
);
}
}
if ((array_key_exists('post_type', $item) || array_key_exists('posts', $item))
&& ($data['post_type'] == ZBX_POSTTYPE_JSON || $data['post_type'] == ZBX_POSTTYPE_XML)) {
$posts = array_key_exists('posts', $data) ? $data['posts'] : '';
libxml_use_internal_errors(true);
if ($data['post_type'] == ZBX_POSTTYPE_XML
&& simplexml_load_string($posts, null, LIBXML_IMPORT_FLAGS) === false) {
$errors = libxml_get_errors();
libxml_clear_errors();
if (!$errors) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot read XML: %1$s.', _('XML is empty')));
}
else {
$error = reset($errors);
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot read XML: %1$s.',
_s('%1$s [Line: %2$s | Column: %3$s]', '('.$error->code.') '.trim($error->message),
$error->line, $error->column
)));
}
}
if ($data['post_type'] == ZBX_POSTTYPE_JSON) {
if (trim($posts, " \r\n") === '') {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot read JSON.'));
}
$types = [
'usermacros' => true,
'macros_n' => [
'{HOST.IP}', '{HOST.CONN}', '{HOST.DNS}', '{HOST.HOST}', '{HOST.NAME}', '{ITEM.ID}',
'{ITEM.KEY}'
]
];
if ($this instanceof CItemPrototype) {
$types['lldmacros'] = true;
}
$matches = (new CMacrosResolverGeneral)->getMacroPositions($posts, $types);
$shift = 0;
foreach ($matches as $pos => $substr) {
$posts = substr_replace($posts, '1', $pos + $shift, strlen($substr));
$shift = $shift + 1 - strlen($substr);
}
$json->decode($posts);
if ($json->hasError()) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot read JSON.'));
}
}
}
}
}
|